Un tableau de facture multi-pages

Un tableau de facture, réparti sur autant de pages que ses lignes l'exigent.

Rust write_table.rs 396 lignes
  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
//! Lays an invoice table out across as many pages as its lines need.
//!
//! The table is longer than a page, so it is fitted, drawn, and continued: the
//! row it stopped at is where the next page picks up, and the headings are
//! drawn again at the top of each one.
//!
//! Every word the table draws is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which one is drawn. The quantities and the prices are
//! the same in both.
//!
//! Usage: `cargo run --example write_table -- tmp/table.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_table -- tmp/tableau.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{
    Border, Cell, ColumnWidth, Columns, Fit, Margin, Padding, Row, Rule, Stroke, Table, VAlign,
};
use hqf_pdf::{Align, Document, Font, Page, Rgb};

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

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

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

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 margin around the table, in points.
const MARGIN: f64 = 56.0;
/// The top of the table on every page.
const TOP: f64 = 780.0;
/// The lowest the table may reach before it continues on the next page.
const BOTTOM: f64 = 64.0;

/// A4's width, which the table is fitted across.
const PAGE_WIDTH: f64 = 595.276;

/// The width left to the table between the margins.
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * MARGIN;

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

/// The words the table is written in, one set per language.
///
/// What is not language stays out of it: the quantities and the unit prices are
/// drawn from `ITEMS` and read the same in every language.
#[derive(Debug)]
struct Words {
    /// What each billed line is called, in the order `ITEMS` bills them.
    items: [&'static str; ITEM_COUNT],
    /// The four column headings.
    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,
}

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

/// The table in English.
const ENGLISH: Words = Words {
    items: [
        "Rendering engine development",
        "Font engine integration, including cutting each face down to the glyphs actually drawn",
        "Invoice template rework",
        "Historical data migration",
        "Acceptance testing and fixes",
        "Team training",
        "Standby cover for the release night",
        "Performance audit",
        "Technical documentation",
        "First year of support",
    ],
    description: "Description",
    quantity: "Qty",
    unit_price: "Unit price",
    amount: "Amount",
    subtotal: "Subtotal",
    tax: "VAT at 20 %",
    total: "Total due",
};

/// The table in French.
const FRENCH: Words = Words {
    items: [
        "Développement du moteur de rendu",
        "Intégration du moteur de polices, avec réduction de chaque police aux seuls glyphes dessinés",
        "Refonte du modèle de facture",
        "Migration des données historiques",
        "Recette et corrections",
        "Formation de l'équipe",
        "Astreinte la nuit de la mise en production",
        "Audit de performance",
        "Documentation technique",
        "Première année de support",
    ],
    description: "Désignation",
    quantity: "Qté",
    unit_price: "Prix unitaire",
    amount: "Montant",
    subtotal: "Total HT",
    tax: "TVA 20 %",
    total: "Total TTC",
};

/// 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); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// One line of the invoice.
struct Item {
    /// How many.
    quantity: u32,
    /// The price of one, before tax.
    unit_price: f64,
}

/// The lines the invoice bills, in the order `Words::items` names them. Long
/// enough to run past one page, and one of them long enough to wrap onto a
/// second line inside its cell.
const ITEMS: [Item; ITEM_COUNT] = [
    Item {
        quantity: 12,
        unit_price: 620.0,
    },
    Item {
        quantity: 8,
        unit_price: 620.0,
    },
    Item {
        quantity: 3,
        unit_price: 480.0,
    },
    Item {
        quantity: 5,
        unit_price: 540.0,
    },
    Item {
        quantity: 6,
        unit_price: 480.0,
    },
    Item {
        quantity: 2,
        unit_price: 750.0,
    },
    Item {
        quantity: 1,
        unit_price: 1200.0,
    },
    Item {
        quantity: 4,
        unit_price: 690.0,
    },
    Item {
        quantity: 3,
        unit_price: 420.0,
    },
    Item {
        quantity: 12,
        unit_price: 350.0,
    },
];

/// 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 invoice's table: a heading row, the billed lines, and the totals.
fn invoice_table<'a>(
    text: &'a hqf_pdf::FontHandle,
    words: &'static Words,
) -> Result<Table<'a>, hqf_pdf::Error> {
    // The designation 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::black(0.8))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.75)))
        .rule(Rule::VerticalOther, Stroke::new(0.25, Rgb::gray(0.75)))
        // Under the headings, and above the totals.
        .rule(Rule::Horizontal(1), Stroke::black(0.8))
        .rule(Rule::HorizontalFromEnd(1), Stroke::black(0.8));

    let pad = Padding::symmetric(5.0, 4.0);
    let heading = |label: &str| {
        Cell::new(text, 9.0, label)
            .padding(pad)
            .fill(Rgb::gray(0.88))
            .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(20.0),
    );

    // The lines are billed five times over, so that the table runs past a page
    // and its continuation can be seen.
    let mut total = 0.0;
    for (index, item) in ITEMS.iter().cycle().take(ITEMS.len() * 5).enumerate() {
        let label = words.items[index % ITEM_COUNT];
        let line_total = f64::from(item.quantity) * item.unit_price;
        total += line_total;

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

        let mut row = Row::new()
            .cell(Cell::new(text, 9.0, label).padding(pad))
            .cell(figure(item.quantity.to_string()))
            .cell(figure(amount(item.unit_price)))
            .cell(figure(amount(line_total)))
            .min_height(18.0);

        // Every other line is shaded, which is what a row fill is for.
        if index % 2 == 1 {
            row = row.fill(Rgb::gray(0.97));
        }
        table.push(row);
    }

    let tax = total * 0.2;
    for (label, value, weight, 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 in a border of its own, held off the grid by
        // a margin so that it reads as a total rather than as one more line of
        // the table. The box is drawn side by side: the label carries its left
        // edge and the figure its right, so the two cells trace one box between
        // them rather than a box each.
        let (label_border, value_border, box_margin) = if is_grand_total {
            let rule = Stroke::black(0.8);
            (
                Border::none().top(&rule).bottom(&rule).left(&rule),
                Border::none().top(&rule).bottom(&rule).right(&rule),
                Margin::symmetric(0.0, 2.0),
            )
        } else {
            (Border::none(), Border::none(), Margin::NONE)
        };

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

    Ok(table)
}

fn main() -> 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 out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("table")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let font = Font::parse(fs::read(&font_path)?)?;
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let text = doc.add_font(font);

    let table = invoice_table(&text, words)?;

    // Fit, draw, and continue on a new page for as long as rows remain.
    let mut start = 0;
    let mut pages = 0;
    loop {
        let placed = table.fit(MARGIN, TOP, TOP - BOTTOM, start)?;

        let mut content = Content::new();
        placed.draw(&mut content)?;

        let mut page = Page::a4();
        page.content = content.into_bytes();
        doc.add_page(page)?;
        pages += 1;

        match placed.outcome() {
            Fit::Done => break,
            Fit::BoxFull { next_row } => start = next_row,
            Fit::RowTooTall { row } => {
                return Err(format!("row {row} is taller than a page and cannot be drawn").into());
            }
        }
    }

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!(
        "wrote {out}: {} bytes, {pages} pages, {} rows",
        bytes.len(),
        table.row_count()
    );
    Ok(())
}

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

    /// The lines two languages are allowed to write the same way. There are
    /// none: every word is a word of the language it is written in.
    const SPARED: [&str; 0] = [];

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

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