write_payslip.rs

Die Rust-Datei des Beispiels „Eine Gehaltsabrechnung“. Eine Gehaltsabrechnung: achtzehn Beitragszeilen mit Arbeitnehmer- und Arbeitgeberanteil und für jede der Monatsbetrag und dann die Summe seit Januar. Jede Zahl ist mit der Zeile und der Spalte verknüpft, unter der sie steht, für eine Software, die die Seite vorliest.

Rust 1849 Zeilen

Wofür dieses Beispiel da ist

Eine Gehaltsabrechnung geht jeden Monat an jeden Beschäftigten, und ihre Form können Sie nicht wählen: Das Gesetz sagt, was darauf stehen muss, und der Leser ist an eine bestimmte Reihenfolge gewöhnt. Das macht sie zum dichtesten Raster, das ein gewöhnliches Unternehmen druckt — hundert Zahlen auf einem Blatt, von denen jemand jede erklären können muss.

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
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
//! Writes a monthly payslip: a letterhead, the employee it names, an earnings
//! table, a dense table of contributions, and the cumulative figures a payslip
//! carries.
//!
//! The document is a table before it is anything else. Every contribution line
//! is a base, a rate for the employee and a rate for the employer, and the
//! amount each rate comes to; the section headings are rows that span the whole
//! grid; and the totals are boxed off it. Every figure on the page is worked
//! out from the earnings above it, so the sums can be checked with a pencil.
//!
//! The file says what the page is made of, not only what it looks like: here is
//! the title, here is the table of the month's lines, here are its column
//! headings and the line each figure stands on. Each figure is tied to its line
//! heading and its column heading, the two a program reading the page aloud is
//! given to announce it by. The mark says in words what it shows, and the rules
//! drawn across the page are marked as layout, outside what the page says. The
//! document claims PDF/UA-1.
//!
//! Every word the page draws is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which one is drawn. The figures, the rates, the ceiling
//! and the employee's name and staff number are the same in both.
//!
//! Usage: `cargo run --example write_payslip -- tmp/payslip.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_payslip -- tmp/bulletin.pdf`

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

use hqf_pdf::content::{Artifact, Content};
use hqf_pdf::cos::Name;
use hqf_pdf::layout::{
    Border, Cell, ColumnWidth, Columns, Margin, Padding, Row, Rule, Stroke, Table, TableFrame,
    TaggedTable, VAlign,
};
use hqf_pdf::metadata::xmp::{Metadata, PdfUa};
use hqf_pdf::{
    Align, Document, Font, FontHandle, Image, ImageHandle, Marks, Page, Rgb, StructElement,
    StructureTree,
};

#[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 employer'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 tables are 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,
};

/// When the payslip was drawn up: the day the pay was transferred. The library
/// never reads the clock, so the file is the same on every build.
const DRAWN_UP: &str = "2026-07-31T09:30:00+02:00";

/// Who the payslip is for.
const EMPLOYEE_NAME: &str = "Marion Delacroix";
const EMPLOYEE_ID: &str = "EMP-0231";

/// How many lines of pay the month has, and how many rows the contributions
/// table sets, headings included.
const EARNING_COUNT: usize = 4;
const LINE_COUNT: usize = 23;

/// What a quantity of one is counted in.
#[derive(Clone, Copy)]
enum Unit {
    /// Hours.
    Hour,
    /// Days.
    Day,
    /// Nothing: the quantity stands on its own.
    Bare,
}

/// One line of pay, apart from what it is called: a quantity of `unit`, each
/// worth `unit_rate`. The figures read the same whatever language the page is
/// set in.
struct Earning {
    /// How much of it.
    quantity: f64,
    /// What a quantity of one is counted in.
    unit: Unit,
    /// What one is worth.
    unit_rate: f64,
}

/// What the month pays, before anything is taken off it, in the order
/// `Words::earnings` names them.
const EARNINGS: [Earning; EARNING_COUNT] = [
    Earning {
        quantity: 151.67,
        unit: Unit::Hour,
        unit_rate: 27.0,
    },
    Earning {
        quantity: 6.0,
        unit: Unit::Hour,
        unit_rate: 33.75,
    },
    Earning {
        quantity: 5.0,
        unit: Unit::Day,
        unit_rate: 40.0,
    },
    Earning {
        quantity: 1.0,
        unit: Unit::Bare,
        unit_rate: 150.0,
    },
];

/// Which figure a contribution is worked out from.
#[derive(Clone, Copy)]
enum Base {
    /// The whole of the gross pay.
    Gross,
    /// Gross pay as far as the monthly social security ceiling.
    Capped,
    /// The part of gross pay above that ceiling.
    UpperBand,
    /// The part of gross pay social surcharges are levied on.
    Surcharge,
}

/// One row of the contributions table, apart from what it is called: either a
/// heading that spans the grid, or a contribution with a base and two rates.
enum Line {
    /// A heading over the contributions that follow it.
    Section,
    /// A contribution, in percent of its base.
    Charge {
        /// Which figure the rates apply to.
        base: Base,
        /// The rate taken out of the employee's pay.
        deducted: f64,
        /// The rate the employer pays on top.
        charged: f64,
        /// Whether the employee's share stays inside taxable pay.
        non_deductible: bool,
    },
}

/// Builds a contribution line, with the two rates and a deductible share.
const fn charge(base: Base, deducted: f64, charged: f64) -> Line {
    Line::Charge {
        base,
        deducted,
        charged,
        non_deductible: false,
    }
}

/// The contributions the month is charged, in the order `Words::lines` names
/// them.
const LINES: [Line; LINE_COUNT] = [
    Line::Section,
    charge(Base::Gross, 0.0, 7.0),
    charge(Base::Gross, 0.75, 1.25),
    charge(Base::Gross, 0.5, 0.0),
    Line::Section,
    charge(Base::Capped, 6.9, 8.55),
    charge(Base::Gross, 0.4, 1.9),
    charge(Base::Capped, 3.15, 4.72),
    charge(Base::UpperBand, 8.64, 12.95),
    charge(Base::Capped, 0.86, 1.29),
    charge(Base::UpperBand, 1.08, 1.62),
    Line::Section,
    charge(Base::Gross, 0.0, 5.25),
    charge(Base::Gross, 0.0, 4.05),
    charge(Base::Gross, 0.0, 0.15),
    Line::Section,
    charge(Base::Gross, 0.0, 1.1),
    charge(Base::Gross, 0.0, 0.3),
    charge(Base::Gross, 0.0, 0.68),
    charge(Base::Gross, 0.0, 1.0),
    Line::Section,
    charge(Base::Surcharge, 6.8, 0.0),
    Line::Charge {
        base: Base::Surcharge,
        deducted: 2.9,
        charged: 0.0,
        non_deductible: true,
    },
];

/// The monthly social security ceiling the capped and upper bands are cut at.
const CEILING: f64 = 3925.0;
/// The share of gross pay the social surcharges are levied on.
const SURCHARGE_SHARE: f64 = 0.9825;
/// The rate income tax is withheld at, as told to the employer by the revenue.
const TAX_RATE: f64 = 11.2;
/// How many months of the year the cumulative column adds up, this one
/// included. Every month of the year runs to the same figures.
const MONTHS: f64 = 7.0;

/// The paid leave the employee stands at, in days.
const LEAVE_EARNED: f64 = 27.5;
const LEAVE_TAKEN: f64 = 12.0;

/// Every word the page draws, in one language.
///
/// What is not language stays out of it: the figures, the rates, the ceiling
/// and the employee's name and staff number are drawn from constants of their
/// own and read the same in every language.
#[derive(Debug)]
struct Words {
    /// The BCP 47 tag the document states.
    lang: &'static str,
    /// The words the file gives in place of the mark at the head of the
    /// letterhead.
    logo_alt: &'static str,
    /// The words the document's title is built from, and the month it covers.
    payslip: &'static str,
    month: &'static str,
    /// The word set large at the head of the page.
    heading: &'static str,
    /// What stands before the month the page covers, and that month written out
    /// as this language writes a span of days.
    period_label: &'static str,
    period: &'static str,
    /// What stands before the day the pay was transferred, and that day.
    paid_label: &'static str,
    pay_date: &'static str,
    /// The heading over the employee, what the employee does, and what stands
    /// before the staff number and before the day they joined.
    employee: &'static str,
    role: &'static str,
    staff_label: &'static str,
    joined_label: &'static str,
    joined_date: &'static str,
    /// The heading over what is paid, and the line under the figure.
    net_paid: &'static str,
    transferred: &'static str,
    /// What an hour and a day are written as after a quantity.
    hour: &'static str,
    day: &'static str,
    /// The four column headings of the earnings table.
    earnings_heading: &'static str,
    quantity: &'static str,
    unit_rate: &'static str,
    earnings_amount: &'static str,
    /// What each line of pay is called, in the order `EARNINGS` pays them, and
    /// the total under them.
    earnings: [&'static str; EARNING_COUNT],
    gross_pay: &'static str,
    /// The two tiers of headings of the contributions table.
    employee_share: &'static str,
    employer_share: &'static str,
    contribution: &'static str,
    base: &'static str,
    rate: &'static str,
    amount: &'static str,
    /// What each row of the contributions table is called, in the order `LINES`
    /// sets them, headings included.
    lines: [&'static str; LINE_COUNT],
    /// The three totals under the contributions.
    total_contributions: &'static str,
    net_before_tax: &'static str,
    total_cost: &'static str,
    /// The three column headings of the cumulative table, the five lines it
    /// carries, and what is paid over at the foot of it.
    summary: &'static str,
    this_month: &'static str,
    year_to_date: &'static str,
    summary_lines: [&'static str; 5],
    net_paid_row: &'static str,
    /// The heading over the leave, and the three counts under it.
    leave: &'static str,
    leave_earned: &'static str,
    leave_taken: &'static str,
    leave_remaining: &'static str,
    /// The working week, and the small print at the foot of the page.
    working_time: &'static str,
    mentions: &'static str,
}

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

    /// What a quantity is counted in, in this language.
    const fn unit(&self, unit: Unit) -> &'static str {
        match unit {
            Unit::Hour => self.hour,
            Unit::Day => self.day,
            Unit::Bare => "",
        }
    }
}

/// The payslip in English.
const ENGLISH: Words = Words {
    lang: "en-GB",
    logo_alt: "The HQF Development mark",
    payslip: "Payslip",
    month: "July 2026",
    heading: "PAYSLIP",
    period_label: "Period",
    period: "1 – 31 July 2026",
    paid_label: "Paid on",
    pay_date: "31 July 2026",
    employee: "EMPLOYEE",
    role: "Senior software engineer — grade 3.2",
    staff_label: "Staff No.",
    joined_label: "Joined",
    joined_date: "4 September 2023",
    net_paid: "NET PAID",
    transferred: "Transferred to the account on file",
    hour: "h",
    day: "d",
    earnings_heading: "Earnings",
    quantity: "Quantity",
    unit_rate: "Unit rate",
    earnings_amount: "Amount",
    earnings: [
        "Monthly base salary",
        "Overtime, first eight hours (125 %)",
        "On-call cover, weekend",
        "Seniority bonus",
    ],
    gross_pay: "GROSS PAY",
    employee_share: "Employee share",
    employer_share: "Employer share",
    contribution: "Contribution",
    base: "Base",
    rate: "Rate",
    amount: "Amount",
    lines: [
        "HEALTH, MATERNITY, DISABILITY, DEATH",
        "Health and maternity insurance",
        "Supplementary health cover",
        "Daily sickness allowance",
        "RETIREMENT",
        "State pension, capped",
        "State pension, uncapped",
        "Supplementary pension, band 1",
        "Supplementary pension, band 2",
        "Balancing contribution, band 1",
        "Balancing contribution, band 2",
        "FAMILY AND UNEMPLOYMENT",
        "Family allowances",
        "Unemployment insurance",
        "Wage guarantee scheme",
        "OTHER EMPLOYER CONTRIBUTIONS",
        "Workplace accident cover",
        "Autonomy solidarity contribution",
        "Apprenticeship levy",
        "Continuing training levy",
        "SOCIAL SURCHARGES",
        "Social surcharge, deductible",
        "Social surcharge and debt levy, non-deductible",
    ],
    total_contributions: "TOTAL CONTRIBUTIONS",
    net_before_tax: "NET PAY BEFORE INCOME TAX",
    total_cost: "TOTAL COST OF THE MONTH TO THE EMPLOYER",
    summary: "Summary",
    this_month: "This month",
    year_to_date: "Year to date",
    summary_lines: [
        "Gross pay",
        "Employee contributions",
        "Employer contributions",
        "Taxable pay",
        "Income tax withheld at 11.20 %",
    ],
    net_paid_row: "NET PAID",
    leave: "PAID LEAVE",
    leave_earned: "Earned this year",
    leave_taken: "taken",
    leave_remaining: "remaining",
    working_time: "Working time: 35 h a week",
    mentions: "Keep this payslip without limit of time · \
        HQF Development · 42 lot les Genêts, 13480 Calas, France · \
        SIRET 752 492 777 00012 · APE 6202A",
};

/// The payslip in French.
const FRENCH: Words = Words {
    lang: "fr-FR",
    logo_alt: "Le logo de HQF Development",
    payslip: "Bulletin de paie",
    month: "juillet 2026",
    heading: "BULLETIN DE PAIE",
    period_label: "Période",
    period: "du 1er au 31 juillet 2026",
    paid_label: "Payé le",
    pay_date: "31 juillet 2026",
    employee: "SALARIÉE",
    role: "Ingénieure logiciel confirmée — niveau 3.2",
    staff_label: "Matricule",
    joined_label: "Entrée le",
    joined_date: "4 septembre 2023",
    net_paid: "NET À PAYER",
    transferred: "Virement sur le compte enregistré",
    hour: "h",
    day: "j",
    earnings_heading: "Éléments de paie",
    quantity: "Nombre",
    unit_rate: "Taux unitaire",
    earnings_amount: "Montant",
    earnings: [
        "Salaire de base mensuel",
        "Heures supplémentaires, 8 premières (125 %)",
        "Astreinte de week-end",
        "Prime d’ancienneté",
    ],
    gross_pay: "SALAIRE BRUT",
    employee_share: "Part salariale",
    employer_share: "Part patronale",
    contribution: "Cotisation",
    base: "Base",
    rate: "Taux",
    amount: "Montant",
    lines: [
        "SANTÉ, MATERNITÉ, INVALIDITÉ, DÉCÈS",
        "Assurance maladie et maternité",
        "Complémentaire santé",
        "Indemnités journalières",
        "RETRAITE",
        "Assurance vieillesse plafonnée",
        "Assurance vieillesse déplafonnée",
        "Retraite complémentaire, tranche 1",
        "Retraite complémentaire, tranche 2",
        "Contribution d’équilibre, tranche 1",
        "Contribution d’équilibre, tranche 2",
        "FAMILLE ET CHÔMAGE",
        "Allocations familiales",
        "Assurance chômage",
        "Garantie des salaires",
        "AUTRES COTISATIONS PATRONALES",
        "Accidents du travail",
        "Contribution solidarité autonomie",
        "Taxe d’apprentissage",
        "Formation professionnelle",
        "CSG ET CRDS",
        "CSG déductible",
        "CSG et CRDS non déductibles",
    ],
    total_contributions: "TOTAL DES COTISATIONS",
    net_before_tax: "NET À PAYER AVANT IMPÔT",
    total_cost: "COÛT TOTAL DU MOIS POUR L’EMPLOYEUR",
    summary: "Récapitulatif",
    this_month: "Ce mois",
    year_to_date: "Cumul annuel",
    summary_lines: [
        "Salaire brut",
        "Cotisations salariales",
        "Cotisations patronales",
        "Net imposable",
        "Prélèvement à la source, 11.20 %",
    ],
    net_paid_row: "NET À PAYER",
    leave: "CONGÉS PAYÉS",
    leave_earned: "Acquis cette année",
    leave_taken: "pris",
    leave_remaining: "solde",
    working_time: "Temps de travail : 35 h par semaine",
    mentions: "Bulletin à conserver sans limitation de durée · \
        HQF Development · 42 lot les Genêts, 13480 Calas, France · \
        SIRET 752 492 777 00012 · APE 6202A",
};

/// The payslip in Dutch.
const DUTCH: Words = Words {
    lang: "nl-NL",
    logo_alt: "Het logo van HQF Development",
    payslip: "Loonstrook",
    month: "Juli 2026",
    heading: "LOONSTROOK",
    period_label: "Periode",
    period: "1 – 31 juli 2026",
    paid_label: "Betaald op",
    pay_date: "31 juli 2026",
    employee: "WERKNEMER",
    role: "Senior software-engineer — schaal 3.2",
    staff_label: "Personeelsnr.",
    joined_label: "In dienst",
    joined_date: "4 september 2023",
    net_paid: "NETTO BETAALD",
    transferred: "Overgemaakt naar de bekende rekening",
    hour: "h",
    day: "d",
    earnings_heading: "Inkomsten",
    quantity: "Aantal",
    unit_rate: "Tarief",
    earnings_amount: "Bedrag",
    earnings: [
        "Maandelijks basissalaris",
        "Overwerk, eerste acht uur (125 %)",
        "Bereikbaarheidsdienst, weekend",
        "Dienstjarentoeslag",
    ],
    gross_pay: "BRUTOLOON",
    employee_share: "Deel werknemer",
    employer_share: "Deel werkgever",
    contribution: "Premie",
    base: "Grondslag",
    rate: "Tarief",
    amount: "Bedrag",
    lines: [
        "ZIEKTE, MOEDERSCHAP, INVALIDITEIT, OVERLIJDEN",
        "Ziekte- en moederschapsverzekering",
        "Aanvullende ziektekostendekking",
        "Dagelijkse ziekte-uitkering",
        "PENSIOEN",
        "Staatspensioen, gemaximeerd",
        "Staatspensioen, niet gemaximeerd",
        "Aanvullend pensioen, schijf 1",
        "Aanvullend pensioen, schijf 2",
        "Evenwichtsbijdrage, schijf 1",
        "Evenwichtsbijdrage, schijf 2",
        "GEZIN EN WERKLOOSHEID",
        "Kinderbijslag",
        "Werkloosheidsverzekering",
        "Loongarantiefonds",
        "OVERIGE WERKGEVERSPREMIES",
        "Dekking arbeidsongevallen",
        "Solidariteitsbijdrage autonomie",
        "Leerlingwezenheffing",
        "Heffing permanente scholing",
        "SOCIALE HEFFINGEN",
        "Sociale heffing, aftrekbaar",
        "Sociale en schuldheffing, niet aftrekbaar",
    ],
    total_contributions: "TOTAAL PREMIES",
    net_before_tax: "NETTO VÓÓR INKOMSTENBELASTING",
    total_cost: "TOTALE MAANDKOSTEN VOOR DE WERKGEVER",
    summary: "Overzicht",
    this_month: "Deze maand",
    year_to_date: "Dit jaar tot nu",
    summary_lines: [
        "Brutoloon",
        "Premies werknemer",
        "Premies werkgever",
        "Belastbaar loon",
        "Ingehouden inkomstenbelasting tegen 11,20 %",
    ],
    net_paid_row: "NETTO BETAALD",
    leave: "BETAALD VERLOF",
    leave_earned: "Opgebouwd dit jaar",
    leave_taken: "opgenomen",
    leave_remaining: "resterend",
    working_time: "Arbeidsduur: 35 u per week",
    mentions: "Bewaar deze loonstrook onbeperkt · HQF Development · 42 lot les Genêts, 13480 Calas, Frankrijk · SIRET 752 492 777 00012 · APE 6202A",
};

/// The payslip in Portuguese.
const PORTUGUESE: Words = Words {
    lang: "pt-PT",
    logo_alt: "A marca da HQF Development",
    payslip: "Recibo de vencimento",
    month: "Julho de 2026",
    heading: "RECIBO DE VENCIMENTO",
    period_label: "Período",
    period: "1 – 31 de julho de 2026",
    paid_label: "Pago em",
    pay_date: "31 de julho de 2026",
    employee: "TRABALHADOR",
    role: "Engenheiro de software sénior — nível 3.2",
    staff_label: "N.º de funcionário",
    joined_label: "Admissão",
    joined_date: "4 de setembro de 2023",
    net_paid: "LÍQUIDO PAGO",
    transferred: "Transferido para a conta registada",
    hour: "h",
    day: "d",
    earnings_heading: "Remunerações",
    quantity: "Quantidade",
    unit_rate: "Valor unitário",
    earnings_amount: "Montante",
    earnings: [
        "Vencimento base mensal",
        "Horas extra, primeiras oito horas (125 %)",
        "Prevenção, fim de semana",
        "Diuturnidades",
    ],
    gross_pay: "REMUNERAÇÃO ILÍQUIDA",
    employee_share: "Parte do trabalhador",
    employer_share: "Parte da entidade patronal",
    contribution: "Contribuição",
    base: "Base",
    rate: "Taxa",
    amount: "Montante",
    lines: [
        "DOENÇA, MATERNIDADE, INVALIDEZ, MORTE",
        "Seguro de doença e maternidade",
        "Seguro de saúde complementar",
        "Subsídio diário de doença",
        "REFORMA",
        "Pensão pública, com teto",
        "Pensão pública, sem teto",
        "Pensão complementar, escalão 1",
        "Pensão complementar, escalão 2",
        "Contribuição de equilíbrio, escalão 1",
        "Contribuição de equilíbrio, escalão 2",
        "FAMÍLIA E DESEMPREGO",
        "Abonos de família",
        "Seguro de desemprego",
        "Fundo de garantia salarial",
        "OUTRAS CONTRIBUIÇÕES DA ENTIDADE PATRONAL",
        "Seguro de acidentes de trabalho",
        "Contribuição solidária para a autonomia",
        "Taxa de aprendizagem",
        "Taxa de formação contínua",
        "CONTRIBUIÇÕES SOCIAIS",
        "Contribuição social, dedutível",
        "Contribuição social e para a dívida, não dedutíveis",
    ],
    total_contributions: "TOTAL DE CONTRIBUIÇÕES",
    net_before_tax: "LÍQUIDO ANTES DO IMPOSTO SOBRE O RENDIMENTO",
    total_cost: "CUSTO TOTAL DO MÊS PARA A ENTIDADE PATRONAL",
    summary: "Resumo",
    this_month: "Este mês",
    year_to_date: "Acumulado no ano",
    summary_lines: [
        "Remuneração ilíquida",
        "Contribuições do trabalhador",
        "Contribuições da entidade patronal",
        "Rendimento coletável",
        "Imposto sobre o rendimento retido a 11,20 %",
    ],
    net_paid_row: "LÍQUIDO PAGO",
    leave: "FÉRIAS PAGAS",
    leave_earned: "Adquiridas este ano",
    leave_taken: "gozadas",
    leave_remaining: "por gozar",
    working_time: "Horário de trabalho: 35 h semanais",
    mentions: "Guarde este recibo sem limite de tempo · HQF Development · 42 lot les Genêts, 13480 Calas, França · SIRET 752 492 777 00012 · APE 6202A",
};

/// The payslip in Italian.
const ITALIAN: Words = Words {
    lang: "it-IT",
    logo_alt: "Il marchio di HQF Development",
    payslip: "Busta paga",
    month: "Luglio 2026",
    heading: "BUSTA PAGA",
    period_label: "Periodo",
    period: "1 – 31 luglio 2026",
    paid_label: "Pagata il",
    pay_date: "31 luglio 2026",
    employee: "DIPENDENTE",
    role: "Ingegnere del software senior — livello 3.2",
    staff_label: "Matricola",
    joined_label: "Assunto il",
    joined_date: "4 settembre 2023",
    net_paid: "NETTO PAGATO",
    transferred: "Accreditato sul conto registrato",
    hour: "h",
    day: "g",
    earnings_heading: "Competenze",
    quantity: "Quantità",
    unit_rate: "Tariffa unitaria",
    earnings_amount: "Importo",
    earnings: [
        "Stipendio base mensile",
        "Straordinari, prime otto ore (125 %)",
        "Reperibilità, fine settimana",
        "Scatto di anzianità",
    ],
    gross_pay: "RETRIBUZIONE LORDA",
    employee_share: "Quota dipendente",
    employer_share: "Quota datore di lavoro",
    contribution: "Contributo",
    base: "Imponibile",
    rate: "Aliquota",
    amount: "Importo",
    lines: [
        "MALATTIA, MATERNITÀ, INVALIDITÀ, MORTE",
        "Assicurazione malattia e maternità",
        "Copertura sanitaria integrativa",
        "Indennità giornaliera di malattia",
        "PENSIONE",
        "Pensione pubblica, con massimale",
        "Pensione pubblica, senza massimale",
        "Pensione integrativa, fascia 1",
        "Pensione integrativa, fascia 2",
        "Contributo di equilibrio, fascia 1",
        "Contributo di equilibrio, fascia 2",
        "FAMIGLIA E DISOCCUPAZIONE",
        "Assegni familiari",
        "Assicurazione contro la disoccupazione",
        "Fondo di garanzia retributiva",
        "ALTRI CONTRIBUTI DEL DATORE DI LAVORO",
        "Assicurazione infortuni sul lavoro",
        "Contributo di solidarietà per l’autonomia",
        "Contributo per l’apprendistato",
        "Contributo per la formazione continua",
        "PRELIEVI SOCIALI",
        "Prelievo sociale, deducibile",
        "Prelievo sociale e contributo al debito, non deducibili",
    ],
    total_contributions: "TOTALE CONTRIBUTI",
    net_before_tax: "NETTO PRIMA DELL’IMPOSTA SUL REDDITO",
    total_cost: "COSTO TOTALE DEL MESE PER IL DATORE DI LAVORO",
    summary: "Riepilogo",
    this_month: "Questo mese",
    year_to_date: "Da inizio anno",
    summary_lines: [
        "Retribuzione lorda",
        "Contributi del dipendente",
        "Contributi del datore di lavoro",
        "Imponibile fiscale",
        "Imposta sul reddito trattenuta all’11,20 %",
    ],
    net_paid_row: "NETTO PAGATO",
    leave: "FERIE RETRIBUITE",
    leave_earned: "Maturate quest’anno",
    leave_taken: "godute",
    leave_remaining: "residue",
    working_time: "Orario di lavoro: 35 h settimanali",
    mentions: "Conservare questa busta paga senza limiti di tempo · HQF Development · 42 lot les Genêts, 13480 Calas, Francia · SIRET 752 492 777 00012 · APE 6202A",
};

/// The payslip in Spanish.
const SPANISH: Words = Words {
    lang: "es-ES",
    logo_alt: "El logotipo de HQF Development",
    payslip: "Nómina",
    month: "Julio de 2026",
    heading: "NÓMINA",
    period_label: "Periodo",
    period: "1 – 31 de julio de 2026",
    paid_label: "Pagada el",
    pay_date: "31 de julio de 2026",
    employee: "EMPLEADO",
    role: "Ingeniero de software sénior — grado 3.2",
    staff_label: "N.º de personal",
    joined_label: "Alta",
    joined_date: "4 de septiembre de 2023",
    net_paid: "LÍQUIDO PAGADO",
    transferred: "Transferido a la cuenta registrada",
    hour: "h",
    day: "d",
    earnings_heading: "Devengos",
    quantity: "Cantidad",
    unit_rate: "Precio unitario",
    earnings_amount: "Importe",
    earnings: [
        "Salario base mensual",
        "Horas extra, primeras ocho horas (125 %)",
        "Guardia, fin de semana",
        "Complemento de antigüedad",
    ],
    gross_pay: "SALARIO BRUTO",
    employee_share: "Parte del empleado",
    employer_share: "Parte del empleador",
    contribution: "Cotización",
    base: "Base",
    rate: "Tipo",
    amount: "Importe",
    lines: [
        "SALUD, MATERNIDAD, INVALIDEZ, FALLECIMIENTO",
        "Seguro de enfermedad y maternidad",
        "Seguro médico complementario",
        "Subsidio diario por enfermedad",
        "JUBILACIÓN",
        "Pensión pública, con tope",
        "Pensión pública, sin tope",
        "Pensión complementaria, tramo 1",
        "Pensión complementaria, tramo 2",
        "Cotización de equilibrio, tramo 1",
        "Cotización de equilibrio, tramo 2",
        "FAMILIA Y DESEMPLEO",
        "Prestaciones familiares",
        "Seguro de desempleo",
        "Fondo de garantía salarial",
        "OTRAS COTIZACIONES DEL EMPLEADOR",
        "Cobertura de accidentes de trabajo",
        "Contribución solidaria por la autonomía",
        "Tasa de aprendizaje",
        "Tasa de formación continua",
        "RECARGOS SOCIALES",
        "Recargo social, deducible",
        "Recargo social y tasa de deuda, no deducibles",
    ],
    total_contributions: "TOTAL COTIZACIONES",
    net_before_tax: "LÍQUIDO ANTES DEL IMPUESTO SOBRE LA RENTA",
    total_cost: "COSTE TOTAL DEL MES PARA EL EMPLEADOR",
    summary: "Resumen",
    this_month: "Este mes",
    year_to_date: "En el año",
    summary_lines: [
        "Salario bruto",
        "Cotizaciones del empleado",
        "Cotizaciones del empleador",
        "Base imponible",
        "Retención del impuesto sobre la renta al 11,20 %",
    ],
    net_paid_row: "LÍQUIDO PAGADO",
    leave: "VACACIONES PAGADAS",
    leave_earned: "Generadas este año",
    leave_taken: "disfrutadas",
    leave_remaining: "pendientes",
    working_time: "Jornada: 35 h semanales",
    mentions: "Conserve esta nómina sin límite de tiempo · HQF Development · 42 lot les Genêts, 13480 Calas, Francia · SIRET 752 492 777 00012 · APE 6202A",
};

/// The payslip in German.
const GERMAN: Words = Words {
    lang: "de-DE",
    logo_alt: "Das Logo von HQF Development",
    payslip: "Gehaltsabrechnung",
    month: "Juli 2026",
    heading: "GEHALTSABRECHNUNG",
    period_label: "Zeitraum",
    period: "1. – 31. Juli 2026",
    paid_label: "Gezahlt am",
    pay_date: "31. Juli 2026",
    employee: "MITARBEITER",
    role: "Senior-Softwareentwickler — Stufe 3.2",
    staff_label: "Personalnr.",
    joined_label: "Eintritt",
    joined_date: "4. September 2023",
    net_paid: "AUSGEZAHLT",
    transferred: "Auf das hinterlegte Konto überwiesen",
    hour: "h",
    day: "T",
    earnings_heading: "Bezüge",
    quantity: "Menge",
    unit_rate: "Satz",
    earnings_amount: "Betrag",
    earnings: [
        "Monatliches Grundgehalt",
        "Überstunden, erste acht Stunden (125 %)",
        "Rufbereitschaft, Wochenende",
        "Betriebszugehörigkeitszulage",
    ],
    gross_pay: "BRUTTOBEZÜGE",
    employee_share: "Arbeitnehmeranteil",
    employer_share: "Arbeitgeberanteil",
    contribution: "Beitrag",
    base: "Basis",
    rate: "Satz",
    amount: "Betrag",
    lines: [
        "KRANKHEIT, MUTTERSCHAFT, INVALIDITÄT, TOD",
        "Kranken- und Mutterschaftsversicherung",
        "Krankenzusatzversicherung",
        "Krankentagegeld",
        "RENTE",
        "Gesetzliche Rente, gedeckelt",
        "Gesetzliche Rente, ungedeckelt",
        "Zusatzrente, Stufe 1",
        "Zusatzrente, Stufe 2",
        "Ausgleichsbeitrag, Stufe 1",
        "Ausgleichsbeitrag, Stufe 2",
        "FAMILIE UND ARBEITSLOSIGKEIT",
        "Familienbeihilfen",
        "Arbeitslosenversicherung",
        "Lohngarantiefonds",
        "SONSTIGE ARBEITGEBERBEITRÄGE",
        "Arbeitsunfallversicherung",
        "Solidaritätsbeitrag für die Pflege",
        "Ausbildungsabgabe",
        "Weiterbildungsabgabe",
        "SOZIALABGABEN",
        "Sozialabgabe, abzugsfähig",
        "Sozialabgabe und Schuldentilgungsabgabe, nicht abzugsfähig",
    ],
    total_contributions: "BEITRÄGE GESAMT",
    net_before_tax: "NETTO VOR EINKOMMENSTEUER",
    total_cost: "GESAMTKOSTEN DES MONATS FÜR DEN ARBEITGEBER",
    summary: "Übersicht",
    this_month: "Dieser Monat",
    year_to_date: "Seit Jahresbeginn",
    summary_lines: [
        "Bruttobezüge",
        "Arbeitnehmerbeiträge",
        "Arbeitgeberbeiträge",
        "Steuerpflichtiges Entgelt",
        "Einbehaltene Einkommensteuer zu 11,20 %",
    ],
    net_paid_row: "AUSGEZAHLT",
    leave: "BEZAHLTER URLAUB",
    leave_earned: "In diesem Jahr erworben",
    leave_taken: "genommen",
    leave_remaining: "verbleibend",
    working_time: "Arbeitszeit: 35 Std. pro Woche",
    mentions: "Diese Gehaltsabrechnung unbefristet aufbewahren · HQF Development · 42 lot les Genêts, 13480 Calas, Frankreich · SIRET 752 492 777 00012 · APE 6202A",
};

/// 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),
];

/// A value rounded to the hundredth, the way every figure on a payslip is
/// carried: each line is rounded before it is added, so the totals are the sum
/// of what is printed.
fn round2(value: f64) -> f64 {
    let hundredths = value * 100.0;
    (hundredths + 0.5).floor() / 100.0
}

/// An amount, as a payslip writes it: "4 647.59".
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}")
}

/// A rate, as a payslip writes it: "6.90 %". A rate of nothing is a dash, so
/// that a column of rates reads as a column.
fn percent(rate: f64) -> String {
    if rate == 0.0 {
        return "—".to_string();
    }
    format!("{rate:.2} %")
}

/// What the month comes to: the gross pay, the two sides of the contributions,
/// and the surcharge that taxable pay takes back.
struct Payroll {
    /// The pay the contributions are worked out from.
    gross: f64,
    /// What the employee's shares add up to.
    employee: f64,
    /// What the employer's shares add up to.
    employer: f64,
    /// The employee's share that taxable pay adds back.
    non_deductible: f64,
}

impl Payroll {
    /// Adds the earnings up, then charges every contribution against them.
    fn compute() -> Self {
        let gross = EARNINGS
            .iter()
            .map(|earning| round2(earning.quantity * earning.unit_rate))
            .sum::<f64>();

        let mut payroll = Self {
            gross,
            employee: 0.0,
            employer: 0.0,
            non_deductible: 0.0,
        };

        for line in &LINES {
            let Line::Charge {
                base,
                deducted,
                charged,
                non_deductible,
            } = line
            else {
                continue;
            };

            let base = payroll.base(*base);
            let share = round2(base * deducted / 100.0);
            payroll.employee += share;
            payroll.employer += round2(base * charged / 100.0);
            if *non_deductible {
                payroll.non_deductible += share;
            }
        }

        payroll
    }

    /// The figure a contribution's rates are applied to.
    fn base(&self, base: Base) -> f64 {
        match base {
            Base::Gross => self.gross,
            Base::Capped => CEILING,
            Base::UpperBand => self.gross - CEILING,
            Base::Surcharge => round2(self.gross * SURCHARGE_SHARE),
        }
    }

    /// Gross pay less everything the employee contributes.
    fn net_before_tax(&self) -> f64 {
        round2(self.gross - self.employee)
    }

    /// What income tax is charged on: net pay before tax, plus the share of the
    /// social surcharges that tax does not let through.
    fn taxable(&self) -> f64 {
        round2(self.net_before_tax() + self.non_deductible)
    }

    /// The tax the employer withholds and pays over.
    fn tax(&self) -> f64 {
        round2(self.taxable() * TAX_RATE / 100.0)
    }

    /// What lands in the employee's account.
    fn net_paid(&self) -> f64 {
        round2(self.net_before_tax() - self.tax())
    }
}

/// 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`, marked as layout: it
/// separates what is on the page and says nothing itself.
fn rule(content: &mut Content, y: f64, width: f64, color: Rgb) -> Result<(), hqf_pdf::Error> {
    content.begin_artifact(Artifact::Layout);
    content.set_stroke(color)?;
    content.set_line_width(width)?;
    content.move_to(LEFT, y)?;
    content.line_to(RIGHT, y)?;
    content.stroke();
    content.end_marked();
    Ok(())
}

/// The padding every cell of every table on this page is set in.
const fn pad() -> Padding {
    Padding::symmetric(4.0, 1.5)
}

/// A cell holding a figure: small, right-aligned, centred in its row.
fn figure(font: &FontHandle, size: f64, value: String) -> Cell<'_> {
    Cell::new(font, size, value)
        .padding(pad())
        .align(Align::Right)
        .valign(VAlign::Middle)
}

/// A heading cell: white on the accent, centred in its row.
fn heading<'a>(font: &'a FontHandle, label: &str) -> Cell<'a> {
    Cell::new(font, 7.0, label)
        .padding(pad())
        .fill(ACCENT)
        .color(Rgb::gray(1.0))
        .valign(VAlign::Middle)
}

/// The earnings table: what the month pays, line by line, and the gross it
/// comes to.
fn earnings_table<'a>(
    font: &'a FontHandle,
    words: &'static Words,
    payroll: &Payroll,
) -> 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(70.0),
            ColumnWidth::Points(70.0),
            ColumnWidth::Points(80.0),
        ],
        TABLE_WIDTH,
    )?;

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

    table.push(
        Row::new()
            .cell(heading(font, words.earnings_heading))
            .cell(heading(font, words.quantity).align(Align::Right))
            .cell(heading(font, words.unit_rate).align(Align::Right))
            .cell(heading(font, words.earnings_amount).align(Align::Right))
            .min_height(15.0),
    );

    for (index, (earning, label)) in EARNINGS.iter().zip(words.earnings).enumerate() {
        let unit = words.unit(earning.unit);
        let quantity = if unit.is_empty() {
            format!("{:.2}", earning.quantity)
        } else {
            format!("{:.2} {unit}", earning.quantity)
        };

        let mut row = Row::new()
            .cell(
                Cell::new(font, 7.5, label)
                    .padding(pad())
                    .valign(VAlign::Middle),
            )
            .cell(figure(font, 7.5, quantity))
            .cell(figure(font, 7.5, format!("{:.4}", earning.unit_rate)))
            .cell(figure(
                font,
                7.5,
                amount(round2(earning.quantity * earning.unit_rate)),
            ))
            .min_height(13.0);

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

    table.push(
        Row::new()
            .cell(
                Cell::new(font, 8.0, words.gross_pay)
                    .span(3)
                    .align(Align::Right)
                    .padding(pad())
                    .valign(VAlign::Middle),
            )
            .cell(figure(font, 8.0, amount(payroll.gross)))
            .min_height(15.0),
    );

    Ok(table)
}

/// The contributions table: two tiers of headings, a heading row for each
/// family of contributions, one row per contribution, and the three totals.
fn contributions_table<'a>(
    font: &'a FontHandle,
    words: &'static Words,
    payroll: &Payroll,
) -> Result<Table<'a>, hqf_pdf::Error> {
    // Four figure columns for the two shares, one for the base, and whatever is
    // left over for the wording.
    let columns = Columns::new(
        vec![
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(62.0),
            ColumnWidth::Points(42.0),
            ColumnWidth::Points(62.0),
            ColumnWidth::Points(42.0),
            ColumnWidth::Points(62.0),
        ],
        TABLE_WIDTH,
    )?;

    let mut table = Table::new(columns);
    // Both tiers of the heading repeat if the table ever continues on a second
    // page.
    table.header(2).row_headers(1);
    table
        .rule(Rule::Frame, Stroke::new(0.8, ACCENT))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.85)))
        .rule(Rule::Horizontal(1), Stroke::new(0.4, Rgb::gray(1.0)))
        .rule(Rule::Horizontal(2), Stroke::new(0.8, ACCENT))
        .rule(Rule::HorizontalFromEnd(3), Stroke::new(0.8, ACCENT))
        .rule(Rule::Vertical(2), Stroke::new(0.4, Rgb::gray(0.72)))
        .rule(Rule::Vertical(4), Stroke::new(0.4, Rgb::gray(0.72)));

    table.push(
        Row::new()
            .cell(heading(font, "").span(2))
            .cell(
                heading(font, words.employee_share)
                    .span(2)
                    .align(Align::Center),
            )
            .cell(
                heading(font, words.employer_share)
                    .span(2)
                    .align(Align::Center),
            )
            .min_height(13.0),
    );
    table.push(
        Row::new()
            .cell(heading(font, words.contribution))
            .cell(heading(font, words.base).align(Align::Right))
            .cell(heading(font, words.rate).align(Align::Right))
            .cell(heading(font, words.amount).align(Align::Right))
            .cell(heading(font, words.rate).align(Align::Right))
            .cell(heading(font, words.amount).align(Align::Right))
            .min_height(13.0),
    );

    for (line, label) in LINES.iter().zip(words.lines) {
        match line {
            Line::Section => table.push(
                Row::new()
                    .cell(
                        Cell::new(font, 7.0, label)
                            .span(6)
                            .padding(pad())
                            .color(ACCENT)
                            .valign(VAlign::Middle),
                    )
                    .fill(Rgb::gray(0.91))
                    .min_height(12.0),
            ),
            Line::Charge {
                base,
                deducted,
                charged,
                ..
            } => {
                let base = payroll.base(*base);
                let share = |rate: f64| {
                    if rate == 0.0 {
                        String::new()
                    } else {
                        amount(round2(base * rate / 100.0))
                    }
                };

                table.push(
                    Row::new()
                        .cell(
                            Cell::new(font, 7.0, label)
                                .padding(pad())
                                .valign(VAlign::Middle),
                        )
                        .cell(figure(font, 7.0, amount(base)))
                        .cell(figure(font, 7.0, percent(*deducted)))
                        .cell(figure(font, 7.0, share(*deducted)))
                        .cell(figure(font, 7.0, percent(*charged)))
                        .cell(figure(font, 7.0, share(*charged)))
                        .min_height(11.5),
                )
            }
        };
    }

    contribution_totals(&mut table, font, words, payroll);

    Ok(table)
}

/// Closes the contributions table off: the two columns of shares added up under
/// their own heads, then the net pay and the cost of the month.
fn contribution_totals<'a>(
    table: &mut Table<'a>,
    font: &'a FontHandle,
    words: &'static Words,
    payroll: &Payroll,
) {
    table.push(
        Row::new()
            .cell(
                Cell::new(font, 8.0, words.total_contributions)
                    .span(3)
                    .align(Align::Right)
                    .padding(pad())
                    .valign(VAlign::Middle),
            )
            .cell(figure(font, 8.0, amount(payroll.employee)))
            .cell(Cell::new(font, 8.0, "").padding(pad()))
            .cell(figure(font, 8.0, amount(payroll.employer)))
            .min_height(15.0),
    );

    // The last two lines are boxed off the grid so that they read as totals
    // rather than as more lines of it: the label carries the box's left edge
    // and the figure its right, so the two trace one box between them.
    let stroke = Stroke::new(0.8, ACCENT);
    let box_margin = Margin::symmetric(0.0, 2.0);
    let label_border = Border::none().top(&stroke).bottom(&stroke).left(&stroke);
    let value_border = Border::none().top(&stroke).bottom(&stroke).right(&stroke);

    table.push(
        Row::new()
            .cell(
                Cell::new(font, 8.0, words.net_before_tax)
                    .span(3)
                    .align(Align::Right)
                    .padding(pad())
                    .margin(box_margin)
                    .border(label_border.clone())
                    .valign(VAlign::Middle),
            )
            .cell(
                Cell::new(font, 8.0, amount(payroll.net_before_tax()))
                    .align(Align::Right)
                    .padding(pad())
                    .margin(box_margin)
                    .border(value_border.clone())
                    .valign(VAlign::Middle),
            )
            .cell(Cell::new(font, 8.0, "").span(2).padding(pad()))
            .min_height(15.0),
    );

    table.push(
        Row::new()
            .cell(
                Cell::new(font, 7.5, words.total_cost)
                    .span(5)
                    .align(Align::Right)
                    .padding(pad())
                    .margin(box_margin)
                    .border(label_border)
                    .valign(VAlign::Middle),
            )
            .cell(
                Cell::new(font, 7.5, amount(round2(payroll.gross + payroll.employer)))
                    .align(Align::Right)
                    .padding(pad())
                    .margin(box_margin)
                    .border(value_border)
                    .valign(VAlign::Middle),
            )
            .min_height(14.0),
    );
}

/// The cumulative table: what the month came to beside what the year has come
/// to, the income tax withheld, and the net that is paid over.
fn cumulative_table<'a>(
    font: &'a FontHandle,
    words: &'static Words,
    payroll: &Payroll,
) -> Result<Table<'a>, hqf_pdf::Error> {
    let columns = Columns::new(
        vec![
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(96.0),
            ColumnWidth::Points(96.0),
        ],
        TABLE_WIDTH,
    )?;

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

    table.push(
        Row::new()
            .cell(heading(font, words.summary))
            .cell(heading(font, words.this_month).align(Align::Right))
            .cell(heading(font, words.year_to_date).align(Align::Right))
            .min_height(15.0),
    );

    let values = [
        payroll.gross,
        payroll.employee,
        payroll.employer,
        payroll.taxable(),
        payroll.tax(),
    ];

    for (index, (label, value)) in words.summary_lines.into_iter().zip(values).enumerate() {
        let mut row = Row::new()
            .cell(
                Cell::new(font, 7.5, label)
                    .padding(pad())
                    .valign(VAlign::Middle),
            )
            .cell(figure(font, 7.5, amount(value)))
            .cell(figure(font, 7.5, amount(round2(value * MONTHS))))
            .min_height(13.0);

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

    table.push(
        Row::new()
            .cell(
                Cell::new(font, 8.5, words.net_paid_row)
                    .padding(pad())
                    .color(ACCENT)
                    .valign(VAlign::Middle),
            )
            .cell(figure(font, 8.5, amount(payroll.net_paid())).color(ACCENT))
            .cell(figure(
                font,
                8.5,
                amount(round2(payroll.net_paid() * MONTHS)),
            ))
            .min_height(17.0),
    );

    Ok(table)
}

/// Opens a run marked under `tag`, numbered from the page's counter, and hands
/// back the element the tree points at it with. `Content::end_marked` closes
/// the run.
fn begin(content: &mut Content, marks: &mut Marks, tag: &str) -> StructElement {
    let id = marks.next_id();
    content.begin_tagged(&Name::new(tag), id);
    StructElement::new(tag).content(0, id)
}

/// Draws the letterhead: the mark, the employer, the word the page is, and the
/// month it covers, closed off by a rule. Hands back the elements standing for
/// what it drew, in the order they are read: the title and the month first.
fn letterhead(
    content: &mut Content,
    font: &FontHandle,
    logo: &ImageHandle,
    words: &Words,
    marks: &mut Marks,
) -> Result<Vec<StructElement>, hqf_pdf::Error> {
    let (logo_w, logo_h) = logo.fit_within(62.25, 62.25)?;
    let mark = begin(content, marks, "Figure").alt(words.logo_alt);
    content.draw_image(logo, LEFT, 826.5 - logo_h, logo_w, logo_h)?;
    content.end_marked();

    let address = begin(content, marks, "P");
    text(
        content,
        font,
        8.5,
        LEFT,
        782.0,
        MUTED,
        "42 lot les Genêts, 13480 Calas, France",
    );
    text(
        content,
        font,
        8.5,
        LEFT,
        771.0,
        MUTED,
        "SIRET 752 492 777 00012 · APE 6202A · contact@hqf-pdf.com",
    );
    content.end_marked();

    let title = begin(content, marks, "H1");
    text_right(content, font, 26.0, RIGHT, 802.0, ACCENT, words.heading);
    content.end_marked();

    let period = begin(content, marks, "P");
    text_right(
        content,
        font,
        9.0,
        RIGHT,
        783.0,
        INK,
        &format!("{} {}", words.period_label, words.period),
    );
    text_right(
        content,
        font,
        9.0,
        RIGHT,
        771.0,
        MUTED,
        &format!("{} {}", words.paid_label, words.pay_date),
    );
    content.end_marked();

    rule(content, 758.0, 1.2, ACCENT)?;
    Ok(vec![title, period, mark, address])
}

/// Draws who is being paid and — set apart on the right — what they are paid.
/// Hands back the elements standing for what it drew: a heading and a paragraph
/// for each side.
fn employee(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    payroll: &Payroll,
    marks: &mut Marks,
) -> Vec<StructElement> {
    let who = begin(content, marks, "H2");
    text(content, font, 7.5, LEFT, 742.0, MUTED, words.employee);
    content.end_marked();

    let named = begin(content, marks, "P");
    text(content, font, 11.0, LEFT, 728.0, INK, EMPLOYEE_NAME);
    text(content, font, 8.0, LEFT, 715.0, MUTED, words.role);
    text(
        content,
        font,
        8.0,
        LEFT,
        704.0,
        MUTED,
        &format!(
            "{} {EMPLOYEE_ID} · {} {}",
            words.staff_label, words.joined_label, words.joined_date
        ),
    );
    content.end_marked();

    let paid = begin(content, marks, "H2");
    text_right(content, font, 7.5, RIGHT, 742.0, MUTED, words.net_paid);
    content.end_marked();

    let figure = begin(content, marks, "P");
    text_right(
        content,
        font,
        18.0,
        RIGHT,
        724.0,
        ACCENT,
        &format!("{} EUR", amount(payroll.net_paid())),
    );
    text_right(content, font, 8.0, RIGHT, 708.0, MUTED, words.transferred);
    content.end_marked();

    vec![who, named, paid, figure]
}

/// Draws the leave the employee stands at, and the small print the foot of the
/// page carries. Hands back the elements standing for what it drew.
fn footer(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    top: f64,
    marks: &mut Marks,
) -> Result<Vec<StructElement>, hqf_pdf::Error> {
    let leave = begin(content, marks, "H2");
    text(content, font, 7.5, LEFT, top, ACCENT, words.leave);
    content.end_marked();

    let day = words.day;
    let counted = format!(
        "{} {LEAVE_EARNED:.2} {day} · {} {LEAVE_TAKEN:.2} {day} · {} {:.2} {day}",
        words.leave_earned,
        words.leave_taken,
        words.leave_remaining,
        LEAVE_EARNED - LEAVE_TAKEN
    );
    let counts = begin(content, marks, "P");
    text(content, font, 8.0, LEFT, top - 13.0, INK, &counted);
    content.end_marked();

    let hours = begin(content, marks, "P");
    text_right(
        content,
        font,
        8.0,
        RIGHT,
        top - 13.0,
        MUTED,
        words.working_time,
    );
    content.end_marked();

    rule(content, 74.0, 0.5, Rgb::gray(0.8))?;
    let mentions_x = LEFT + (TABLE_WIDTH - font.measure(words.mentions, 6.5)) / 2.0;
    let mentions = begin(content, marks, "P");
    text(content, font, 6.5, mentions_x, 62.0, MUTED, words.mentions);
    content.end_marked();

    Ok(vec![leave, counts, hours, mentions])
}

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

/// Builds the whole payslip in the words given, set in the font at `font_path`,
/// and the tree that says what every part of it is.
fn build(words: &'static Words, font_path: &Path) -> Result<Document, Box<dyn std::error::Error>> {
    let title = format!("{} — {}", words.payslip, words.month);
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    // The accessibility claim, which is what a buyer's validator is pointed at:
    // it is judged against the tree, the artifacts, the embedded font and the
    // title all at once.
    doc.set_ua_conformance(PdfUa::One);
    doc.set_info(Name::new("Title"), &title);
    let mut facts = Metadata::default();
    facts.title = Some(title);
    facts.producer = Some("hqf-pdf".to_owned());
    facts.created = Some(DRAWN_UP.to_owned());
    doc.set_metadata(facts);

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

    let payroll = Payroll::compute();

    let mut content = Content::new();
    let mut marks = Marks::new();
    let mut body = StructElement::new("Document");
    for element in letterhead(&mut content, &font, &logo, words, &mut marks)? {
        body = body.child(element);
    }
    for element in employee(&mut content, &font, words, &payroll, &mut marks) {
        body = body.child(element);
    }

    // The three tables are stacked down the page, each one starting a fixed gap
    // below where the one above it stopped. Each names its headings under a
    // name of its own, so no two tables share one.
    let mut top = 686.0;
    for (name, table) in [
        ("earnings", earnings_table(&font, words, &payroll)?),
        (
            "contributions",
            contributions_table(&font, words, &payroll)?,
        ),
        ("summary", cumulative_table(&font, words, &payroll)?),
    ] {
        let placed = table.fit(TableFrame::new(LEFT, top, top - 80.0), 0)?;
        let mut described = TaggedTable::new(name);
        described.add(&placed, &mut content, 0, &mut marks)?;
        body = body.child(described.finish());
        top -= placed.height() + 18.0;
    }

    for element in footer(&mut content, &font, words, top - 4.0, &mut marks)? {
        body = body.child(element);
    }

    let mut page = Page::new(PAGE_WIDTH, PAGE_HEIGHT);
    page.content = content.into_bytes();
    doc.add_page(page)?;
    doc.set_structure(StructureTree::new().lang(words.lang).child(body));
    Ok(doc)
}

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("payslip")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

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

    let payroll = Payroll::compute();
    println!(
        "wrote {path}: {} bytes, {} gross, {} net",
        bytes.len(),
        amount(payroll.gross),
        amount(payroll.net_paid())
    );
    Ok(())
}

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

    /// The lines two languages are allowed to write the same way, each with
    /// what makes the two the same word.
    const SPARED: [&str; 5] = [
        // An hour is written `h` after a quantity in French as in English.
        r#"hour: "h""#,
        // A contribution is headed by the base it is worked out from, and the
        // word is the same in both.
        r#"base: "Base""#,
        // Written the same way in Spanish.
        r#"day: "d""#,
        // Written the same way in Italian.
        r#"period_label: "Periodo""#,
        // Written the same way in Dutch.
        r#"month: "Juli 2026""#,
    ];

    /// The operator line starting each of the two rules drawn across the page,
    /// under the letterhead and above the mentions.
    const RULES: [&str; 2] = ["56 758 m", "56 74 m"];

    /// The operator line opening the innermost marked run the one line of `pdf`
    /// equal to `line` is drawn in, or `None` when that line is drawn outside
    /// every run.
    ///
    /// # Panics
    ///
    /// When `pdf` holds `line` other than exactly once.
    fn innermost_mark(pdf: &str, line: &str) -> Option<String> {
        assert_eq!(
            pdf.lines().filter(|each| *each == line).count(),
            1,
            "{line:?} is not drawn exactly once"
        );
        let mut open: Vec<&str> = Vec::new();
        for each in pdf.lines() {
            if each == line {
                break;
            }
            if each.ends_with(" BDC") || each.ends_with(" BMC") {
                open.push(each);
            } else if each == "EMC" {
                open.pop();
            }
        }
        open.last().map(|mark| (*mark).to_owned())
    }

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

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

    /// The point of the page: it says what it is made of. The three tables are
    /// tables with their headings named, the mark carries the words the file
    /// gives in its place, each of the two rules drawn across the page is drawn
    /// inside a run marked as layout, and the document claims the accessibility
    /// standard a validator is pointed at.
    #[test]
    fn the_payslip_says_it_is_three_tables_with_their_headings() {
        for (named, words) in WORDS {
            let mut doc = build(words, &default_font()).expect("the document builds");
            doc.set_compression(false);
            let pdf =
                String::from_utf8_lossy(&doc.to_bytes().expect("the document writes")).into_owned();
            let code = named.code();

            assert!(pdf.contains("/StructTreeRoot"), "{code}: no tree");
            assert!(
                pdf.contains(&format!("/Lang ({})", words.lang)),
                "{code}: the language is not stated"
            );
            assert_eq!(pdf.matches("/S /Table").count(), 3, "{code}: three tables");
            assert!(pdf.contains("/S /TH"), "{code}: no heading cell");
            assert!(pdf.contains("/Scope /Column"), "{code}: no column heading");
            assert!(pdf.contains("/Scope /Row"), "{code}: no row heading");
            assert!(
                pdf.contains("/Headers ["),
                "{code}: a figure names no heading"
            );
            assert!(pdf.contains("/S /H1"), "{code}: no title heading");
            assert!(
                pdf.contains("/S /Figure"),
                "{code}: the mark is not a figure"
            );
            assert!(
                pdf.contains(&format!("/Alt ({})", words.logo_alt)),
                "{code}: the mark says nothing"
            );
            for stroke in RULES {
                assert_eq!(
                    innermost_mark(&pdf, stroke).as_deref(),
                    Some("/Artifact << /Type /Layout >> BDC"),
                    "{code}: the rule {stroke:?} is not marked as layout"
                );
            }
            assert!(
                pdf.contains("pdfuaid:part"),
                "{code}: no accessibility claim"
            );
        }
    }
}