en16931-formats 0.2.0

European e-invoicing formats on top of the EN 16931 semantic model: UBL 2.1 and UN/CEFACT CII in both directions, the XRechnung CIUS, and ZUGFeRD / Factur-X hybrid PDFs. Every business rule is delegated to `en16931`.
Documentation
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
//! Writing the semantic model as UN/CEFACT CII D16B.
//!
//! Ordering and the prohibitions are the shared serialiser's job, so this module is
//! purely the *mapping*: which of CII's three document parts each business term
//! lives in. That is the part no amount of cleverness derives — it was read off
//! 170 published instances into [`super::order`], and this file places terms
//! into the structure that table describes.

use en16931::invoice::*;
use en16931::{Date, DocumentReference, Identifier, InvoiceAmount};

use super::{ns, order, prohibitions};
use crate::xml::{Xml, base64};

/// How the serialiser answers CII's two questions.
static RULES: crate::xml::Rules = crate::xml::Rules {
    order: order::children_of,
    forbidden_path: prohibitions::forbidden_path,
    forbidden_attribute: prohibitions::forbidden_attribute,
};

/// The only `udt:DateTimeString` format EN 16931 permits: `CCYYMMDD`.
pub(super) const DATE_FORMAT: &str = "102";

/// What writing produced.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Written {
    /// The document.
    pub xml: String,
    /// Terms CII has no place for, as `Parent/child`. Normally empty.
    pub dropped: Vec<String>,
}

/// An amount, as CII writes it.
fn amt(a: InvoiceAmount) -> String {
    a.to_string()
}

/// `<ram:Foo><udt:DateTimeString format="102">20260115</udt:DateTimeString></ram:Foo>`
///
/// CII never writes a bare date. Every one is wrapped and formatted, and the
/// format attribute is not optional — a `udt:DateTimeString` without it is
/// ambiguous between `CCYYMMDD` and half a dozen UN/EDIFACT 2379 codes.
fn date(x: &mut Xml, wrapper: &str, d: Date) {
    x.group(wrapper, |x| {
        x.leaf(
            "udt:DateTimeString",
            &[("format", DATE_FORMAT)],
            &format!("{:04}{:02}{:02}", d.year(), d.month(), d.day()),
        );
    });
}

/// The `ram:ChargeIndicator` wrapper, which is how CII tells an allowance from
/// a charge — the same job UBL's `cbc:ChargeIndicator` does one level up.
fn charge_indicator(x: &mut Xml, is_charge: bool) {
    x.group("ram:ChargeIndicator", |x| {
        x.leaf(
            "udt:Indicator",
            &[],
            if is_charge { "true" } else { "false" },
        );
    });
}

/// An `Identifier`, with `@schemeID` when present.
fn ident(x: &mut Xml, name: &str, i: &Identifier) {
    let mut attrs: Vec<(&str, &str)> = Vec::new();
    if let Some(s) = i.scheme() {
        attrs.push(("schemeID", s));
    }
    x.leaf(name, &attrs, i.content());
}

/// Write an invoice as CII D16B, reporting anything the syntax could not carry.
///
/// There is one document element for both invoices and credit notes: CII
/// distinguishes them by BT-3 alone, so unlike [`fn@crate::ubl::write`] this
/// function never branches on [`en16931::DocumentKind`].
#[must_use]
pub fn write(inv: &Invoice) -> Written {
    let ccy = inv.currency.as_ref().map_or("", Code::as_str);

    let mut x = Xml::new(
        "rsm:CrossIndustryInvoice",
        vec![
            ("xmlns:rsm".to_owned(), ns::RSM.to_owned()),
            ("xmlns:ram".to_owned(), ns::RAM.to_owned()),
            ("xmlns:udt".to_owned(), ns::UDT.to_owned()),
            ("xmlns:qdt".to_owned(), ns::QDT.to_owned()),
        ],
        &RULES,
    );

    // ---- 1. context: what specification this document claims ------------
    x.group_required("rsm:ExchangedDocumentContext", |x| {
        if let Some(p) = &inv.business_process {
            x.group(
                "ram:BusinessProcessSpecifiedDocumentContextParameter",
                |x| {
                    x.leaf("ram:ID", &[], p);
                },
            );
        }
        if let Some(s) = &inv.specification_id {
            x.group("ram:GuidelineSpecifiedDocumentContextParameter", |x| {
                x.leaf("ram:ID", &[], s);
            });
        }
    });

    // ---- 2. the document itself -----------------------------------------
    x.group_required("rsm:ExchangedDocument", |x| {
        if let Some(n) = &inv.number {
            x.leaf("ram:ID", &[], n);
        }
        if let Some(c) = &inv.type_code {
            x.leaf("ram:TypeCode", &[], c.as_str());
        }
        if let Some(d) = inv.issue_date {
            date(x, "ram:IssueDateTime", d);
        }
        for n in &inv.notes {
            x.group("ram:IncludedNote", |x| {
                x.leaf("ram:Content", &[], n.note.as_deref().unwrap_or_default());
                // BT-21 has an element of its own here, where UBL splices it
                // into the note text as `#AAI#`. CII is the tidier of the two.
                if let Some(c) = &n.subject_code {
                    x.leaf("ram:SubjectCode", &[], c.as_str());
                }
            });
        }
    });

    // ---- 3. the transaction ---------------------------------------------
    x.group_required("rsm:SupplyChainTradeTransaction", |x| {
        for l in &inv.lines {
            line(x, l, ccy);
        }
        agreement(x, inv);
        delivery(x, inv);
        settlement(x, inv, ccy);
    });

    let (xml, dropped) = x.finish();
    Written { xml, dropped }
}

// ---------------------------------------------------------------------------
// header: agreement — who, and against which references
// ---------------------------------------------------------------------------

fn agreement(x: &mut Xml, inv: &Invoice) {
    x.group_required("ram:ApplicableHeaderTradeAgreement", |x| {
        if let Some(b) = &inv.buyer_reference {
            x.leaf("ram:BuyerReference", &[], b);
        }
        party(x, "ram:SellerTradeParty", &inv.seller, true);
        party(x, "ram:BuyerTradeParty", &inv.buyer, false);
        if let Some(t) = &inv.tax_representative {
            x.group("ram:SellerTaxRepresentativeTradeParty", |x| {
                if let Some(n) = &t.name {
                    x.leaf("ram:Name", &[], n);
                }
                address(x, &t.address);
                if let Some(v) = &t.vat_identifier {
                    x.group("ram:SpecifiedTaxRegistration", |x| {
                        x.leaf("ram:ID", &[("schemeID", "VA")], v);
                    });
                }
            });
        }
        doc_ref(
            x,
            "ram:SellerOrderReferencedDocument",
            inv.sales_order_reference.as_ref(),
        );
        doc_ref(
            x,
            "ram:BuyerOrderReferencedDocument",
            inv.purchase_order_reference.as_ref(),
        );
        doc_ref(
            x,
            "ram:ContractReferencedDocument",
            inv.contract_reference.as_ref(),
        );
        for a in &inv.attachments {
            attachment(x, a);
        }
        // BT-17 and BT-18 ride on `AdditionalReferencedDocument` with a type
        // code, exactly as they ride on UBL's `AdditionalDocumentReference`.
        if let Some(t) = &inv.tender_reference {
            x.group("ram:AdditionalReferencedDocument", |x| {
                x.leaf("ram:IssuerAssignedID", &[], t.as_str());
                x.leaf("ram:TypeCode", &[], "50");
            });
        }
        if let Some(o) = &inv.object_identifier {
            x.group("ram:AdditionalReferencedDocument", |x| {
                x.leaf("ram:IssuerAssignedID", &[], o.content());
                x.leaf("ram:TypeCode", &[], "130");
                if let Some(s) = o.scheme() {
                    x.leaf("ram:ReferenceTypeCode", &[], s);
                }
            });
        }
        if let Some(p) = &inv.project_reference {
            x.group("ram:SpecifiedProcuringProject", |x| {
                x.leaf("ram:ID", &[], p.as_str());
                // `ram:Name` is mandatory inside this aggregate and EN 16931
                // has no term for it. CEN's own examples carry the reference
                // again rather than inventing a title.
                x.leaf("ram:Name", &[], p.as_str());
            });
        }
    });
}

fn doc_ref(x: &mut Xml, name: &str, r: Option<&DocumentReference>) {
    if let Some(r) = r {
        x.group(name, |x| x.leaf("ram:IssuerAssignedID", &[], r.as_str()));
    }
}

fn attachment(x: &mut Xml, a: &SupportingDocument) {
    x.group("ram:AdditionalReferencedDocument", |x| {
        x.leaf("ram:IssuerAssignedID", &[], a.reference.as_str());
        if let Some(u) = &a.uri {
            x.leaf("ram:URIID", &[], u);
        }
        x.leaf("ram:TypeCode", &[], "916");
        if let Some(d) = &a.description {
            x.leaf("ram:Name", &[], d);
        }
        if let Some(f) = &a.attachment {
            x.leaf(
                "ram:AttachmentBinaryObject",
                &[("mimeCode", f.mime_code()), ("filename", f.filename())],
                &base64(f.content()),
            );
        }
    });
}

/// A trade party.
///
/// `seller` selects the terms that exist only on the seller: BT-33 (additional
/// legal information) has no buyer counterpart, and writing one would be the
/// CII equivalent of the `UBL-CR-244` bug.
fn party(x: &mut Xml, wrapper: &str, p: &Party, seller: bool) {
    x.group(wrapper, |x| {
        for i in &p.identifiers {
            // A scheme-qualified identifier is `ram:GlobalID` with `@schemeID`;
            // an unqualified one is `ram:ID`. Two elements for one business
            // term, which is why the reader has to merge them back.
            if i.scheme().is_some() {
                ident(x, "ram:GlobalID", i);
            } else {
                x.leaf("ram:ID", &[], i.content());
            }
        }
        if let Some(n) = &p.name {
            x.leaf("ram:Name", &[], n);
        }
        if seller && let Some(a) = &p.additional_legal_information {
            x.leaf("ram:Description", &[], a);
        }
        if p.legal_registration.is_some() || p.trading_name.is_some() {
            x.group("ram:SpecifiedLegalOrganization", |x| {
                if let Some(l) = &p.legal_registration {
                    ident(x, "ram:ID", l);
                }
                if let Some(t) = &p.trading_name {
                    x.leaf("ram:TradingBusinessName", &[], t);
                }
            });
        }
        let c = &p.contact;
        if c.name.is_some() || c.phone.is_some() || c.email.is_some() {
            x.group("ram:DefinedTradeContact", |x| {
                if let Some(n) = &c.name {
                    x.leaf("ram:PersonName", &[], n);
                }
                if let Some(t) = &c.phone {
                    x.group("ram:TelephoneUniversalCommunication", |x| {
                        x.leaf("ram:CompleteNumber", &[], t);
                    });
                }
                if let Some(e) = &c.email {
                    x.group("ram:EmailURIUniversalCommunication", |x| {
                        x.leaf("ram:URIID", &[], e);
                    });
                }
            });
        }
        address(x, &p.address);
        if let Some(e) = &p.electronic_address {
            x.group("ram:URIUniversalCommunication", |x| {
                ident(x, "ram:URIID", e);
            });
        }
        if let Some(v) = &p.vat_identifier {
            x.group("ram:SpecifiedTaxRegistration", |x| {
                x.leaf("ram:ID", &[("schemeID", "VA")], v);
            });
        }
        if let Some(t) = &p.tax_registration {
            // `FC` rather than `VA`: a non-VAT registration, which is what
            // BT-32 is and what the reader tells apart by the same code.
            x.group("ram:SpecifiedTaxRegistration", |x| {
                x.leaf("ram:ID", &[("schemeID", "FC")], t);
            });
        }
    });
}

fn address(x: &mut Xml, a: &PostalAddress) {
    // `group` drops an aggregate whose body writes nothing, so a blank address
    // needs no separate emptiness check — one rule, not two that can disagree.
    x.group("ram:PostalTradeAddress", |x| {
        if let Some(p) = &a.post_code {
            x.leaf("ram:PostcodeCode", &[], p);
        }
        if let Some(l) = &a.line1 {
            x.leaf("ram:LineOne", &[], l);
        }
        if let Some(l) = &a.line2 {
            x.leaf("ram:LineTwo", &[], l);
        }
        if let Some(l) = &a.line3 {
            x.leaf("ram:LineThree", &[], l);
        }
        if let Some(c) = &a.city {
            x.leaf("ram:CityName", &[], c);
        }
        if let Some(c) = &a.country {
            x.leaf("ram:CountryID", &[], c.as_str());
        }
        if let Some(s) = &a.subdivision {
            x.leaf("ram:CountrySubDivisionName", &[], s);
        }
    });
}

// ---------------------------------------------------------------------------
// header: delivery
// ---------------------------------------------------------------------------

fn delivery(x: &mut Xml, inv: &Invoice) {
    // `ram:ApplicableHeaderTradeDelivery` is mandatory in the D16B sequence
    // and may legitimately be empty — a minimal invoice delivers nothing.
    x.group_required("ram:ApplicableHeaderTradeDelivery", |x| {
        if let Some(d) = &inv.delivery {
            if d.party_name.is_some() || d.location.is_some() || d.address.is_some() {
                x.group("ram:ShipToTradeParty", |x| {
                    if let Some(l) = &d.location {
                        if l.scheme().is_some() {
                            ident(x, "ram:GlobalID", l);
                        } else {
                            x.leaf("ram:ID", &[], l.content());
                        }
                    }
                    if let Some(n) = &d.party_name {
                        x.leaf("ram:Name", &[], n);
                    }
                    if let Some(a) = &d.address {
                        address(x, a);
                    }
                });
            }
            if let Some(date_) = d.date {
                x.group("ram:ActualDeliverySupplyChainEvent", |x| {
                    date(x, "ram:OccurrenceDateTime", date_);
                });
            }
        }
        doc_ref(
            x,
            "ram:DespatchAdviceReferencedDocument",
            inv.despatch_advice_reference.as_ref(),
        );
        doc_ref(
            x,
            "ram:ReceivingAdviceReferencedDocument",
            inv.receiving_advice_reference.as_ref(),
        );
    });
}

// ---------------------------------------------------------------------------
// header: settlement — money, tax, totals
// ---------------------------------------------------------------------------

fn settlement(x: &mut Xml, inv: &Invoice, ccy: &str) {
    x.group_required("ram:ApplicableHeaderTradeSettlement", |x| {
        if let Some(p) = &inv.payment
            && let Some(PaymentMeans::DirectDebit(d)) = &p.means
            && let Some(c) = &d.creditor_identifier
        {
            x.leaf("ram:CreditorReferenceID", &[], c);
        }
        if let Some(p) = &inv.payment
            && let Some(r) = &p.remittance_information
        {
            x.leaf("ram:PaymentReference", &[], r);
        }
        if let Some(c) = &inv.vat_accounting_currency {
            x.leaf("ram:TaxCurrencyCode", &[], c.as_str());
        }
        if !ccy.is_empty() {
            x.leaf("ram:InvoiceCurrencyCode", &[], ccy);
        }
        if let Some(p) = &inv.payee {
            x.group("ram:PayeeTradeParty", |x| {
                if let Some(i) = &p.identifier {
                    if i.scheme().is_some() {
                        ident(x, "ram:GlobalID", i);
                    } else {
                        x.leaf("ram:ID", &[], i.content());
                    }
                }
                if let Some(n) = &p.name {
                    x.leaf("ram:Name", &[], n);
                }
                if let Some(l) = &p.legal_registration {
                    x.group("ram:SpecifiedLegalOrganization", |x| ident(x, "ram:ID", l));
                }
            });
        }
        if let Some(p) = &inv.payment {
            payment_means(x, p);
        }
        for b in &inv.vat_breakdown {
            x.group("ram:ApplicableTradeTax", |x| {
                x.leaf("ram:CalculatedAmount", &[], &amt(b.tax_amount));
                x.leaf("ram:TypeCode", &[], "VAT");
                if let Some(r) = &b.exemption_reason {
                    x.leaf("ram:ExemptionReason", &[], r);
                }
                x.leaf("ram:BasisAmount", &[], &amt(b.taxable_amount));
                x.leaf("ram:CategoryCode", &[], b.category.as_str());
                if let Some(c) = &b.exemption_reason_code {
                    x.leaf("ram:ExemptionReasonCode", &[], c.as_str());
                }
                // BT-7 and BT-8 sit on the *tax breakdown* in CII, not on the
                // document as they do in UBL. Repeated on each entry, which is
                // what the standard says and what the reader collapses.
                if let Some(c) = &inv.vat_point_date_code {
                    x.leaf("ram:DueDateTypeCode", &[], c.as_str());
                }
                if let Some(d) = inv.vat_point_date {
                    date(x, "ram:TaxPointDate", d);
                }
                if let Some(r) = b.rate {
                    x.leaf("ram:RateApplicablePercent", &[], &r.to_string());
                }
            });
        }
        if let Some(p) = &inv.invoicing_period {
            period(x, "ram:BillingSpecifiedPeriod", p);
        }
        for (a, is_charge) in inv
            .allowances
            .iter()
            .map(|a| (a, false))
            .chain(inv.charges.iter().map(|c| (c, true)))
        {
            x.group("ram:SpecifiedTradeAllowanceCharge", |x| {
                charge_indicator(x, is_charge);
                if let Some(p) = a.percentage {
                    x.leaf("ram:CalculationPercent", &[], &p.to_string());
                }
                if let Some(b) = a.base_amount {
                    x.leaf("ram:BasisAmount", &[], &amt(b));
                }
                x.leaf("ram:ActualAmount", &[], &amt(a.amount));
                if let Some(c) = &a.reason_code {
                    x.leaf("ram:ReasonCode", &[], c.as_str());
                }
                if let Some(r) = &a.reason {
                    x.leaf("ram:Reason", &[], r);
                }
                x.group("ram:CategoryTradeTax", |x| {
                    x.leaf("ram:TypeCode", &[], "VAT");
                    x.leaf("ram:CategoryCode", &[], a.vat.category.as_str());
                    if let Some(r) = a.vat.rate {
                        x.leaf("ram:RateApplicablePercent", &[], &r.to_string());
                    }
                });
            });
        }
        if inv.payment_terms.is_some() || inv.due_date.is_some() {
            x.group("ram:SpecifiedTradePaymentTerms", |x| {
                if let Some(t) = &inv.payment_terms {
                    x.leaf("ram:Description", &[], t);
                }
                if let Some(d) = inv.due_date {
                    date(x, "ram:DueDateDateTime", d);
                }
                if let Some(p) = &inv.payment
                    && let Some(PaymentMeans::DirectDebit(dd)) = &p.means
                    && let Some(m) = &dd.mandate_reference
                {
                    x.leaf("ram:DirectDebitMandateID", &[], m);
                }
            });
        }
        let t = &inv.totals;
        x.group("ram:SpecifiedTradeSettlementHeaderMonetarySummation", |x| {
            x.leaf("ram:LineTotalAmount", &[], &amt(t.line_total));
            if let Some(c) = t.charge_total {
                x.leaf("ram:ChargeTotalAmount", &[], &amt(c));
            }
            if let Some(a) = t.allowance_total {
                x.leaf("ram:AllowanceTotalAmount", &[], &amt(a));
            }
            x.leaf("ram:TaxBasisTotalAmount", &[], &amt(t.taxable_total));
            // The one amount CII requires a currency on, and the reason is
            // BT-111: the VAT total may be stated in the accounting currency
            // as well, and the two are told apart by `@currencyID` alone.
            if let Some(v) = t.vat_total {
                x.leaf("ram:TaxTotalAmount", &[("currencyID", ccy)], &amt(v));
            }
            if let (Some(v), Some(c)) =
                (t.vat_total_accounting, inv.vat_accounting_currency.as_ref())
            {
                x.leaf("ram:TaxTotalAmount", &[("currencyID", c.as_str())], &amt(v));
            }
            if let Some(r) = t.rounding {
                x.leaf("ram:RoundingAmount", &[], &amt(r));
            }
            x.leaf("ram:GrandTotalAmount", &[], &amt(t.gross_total));
            if let Some(p) = t.paid {
                x.leaf("ram:TotalPrepaidAmount", &[], &amt(p));
            }
            x.leaf("ram:DuePayableAmount", &[], &amt(t.due));
        });
        for p in &inv.preceding_invoices {
            x.group("ram:InvoiceReferencedDocument", |x| {
                x.leaf("ram:IssuerAssignedID", &[], p.reference.as_str());
                if let Some(d) = p.issue_date {
                    date(x, "ram:FormattedIssueDateTime", d);
                }
            });
        }
        if let Some(a) = &inv.accounting_reference {
            x.group("ram:ReceivableSpecifiedTradeAccountingAccount", |x| {
                x.leaf("ram:ID", &[], a);
            });
        }
    });
}

fn period(x: &mut Xml, wrapper: &str, p: &Period) {
    x.group(wrapper, |x| {
        if let Some(s) = p.start {
            date(x, "ram:StartDateTime", s);
        }
        if let Some(e) = p.end {
            date(x, "ram:EndDateTime", e);
        }
    });
}

fn payment_means(x: &mut Xml, p: &PaymentInstructions) {
    x.group("ram:SpecifiedTradeSettlementPaymentMeans", |x| {
        if let Some(c) = &p.means_code {
            x.leaf("ram:TypeCode", &[], c.as_str());
        }
        if let Some(t) = &p.means_text {
            x.leaf("ram:Information", &[], t);
        }
        match &p.means {
            Some(PaymentMeans::Card(c)) => {
                x.group("ram:ApplicableTradeSettlementFinancialCard", |x| {
                    if let Some(n) = &c.primary_account_number {
                        x.leaf("ram:ID", &[], n);
                    }
                    if let Some(h) = &c.holder_name {
                        x.leaf("ram:CardholderName", &[], h);
                    }
                });
            }
            Some(PaymentMeans::DirectDebit(d)) => {
                if let Some(a) = &d.debited_account {
                    x.group("ram:PayerPartyDebtorFinancialAccount", |x| {
                        x.leaf("ram:IBANID", &[], a);
                    });
                }
            }
            Some(PaymentMeans::CreditTransfer(ts)) => {
                for t in ts {
                    if let Some(a) = &t.account_identifier {
                        x.group("ram:PayeePartyCreditorFinancialAccount", |x| {
                            x.leaf("ram:IBANID", &[], a);
                            if let Some(n) = &t.account_name {
                                x.leaf("ram:AccountName", &[], n);
                            }
                        });
                    }
                    if let Some(p) = &t.provider_identifier {
                        x.group("ram:PayeeSpecifiedCreditorFinancialInstitution", |x| {
                            x.leaf("ram:BICID", &[], p);
                        });
                    }
                }
            }
            None => {}
        }
    });
}

// ---------------------------------------------------------------------------
// lines
// ---------------------------------------------------------------------------

fn line(x: &mut Xml, l: &InvoiceLine, ccy: &str) {
    let _ = ccy;
    x.group("ram:IncludedSupplyChainTradeLineItem", |x| {
        x.group("ram:AssociatedDocumentLineDocument", |x| {
            x.leaf("ram:LineID", &[], &l.id);
            if let Some(n) = &l.note {
                x.group("ram:IncludedNote", |x| x.leaf("ram:Content", &[], n));
            }
        });
        x.group("ram:SpecifiedTradeProduct", |x| {
            let i = &l.item;
            if let Some(s) = &i.standard_identifier {
                ident(x, "ram:GlobalID", s);
            }
            if let Some(s) = &i.seller_identifier {
                x.leaf("ram:SellerAssignedID", &[], s);
            }
            if let Some(b) = &i.buyer_identifier {
                x.leaf("ram:BuyerAssignedID", &[], b);
            }
            if let Some(n) = &i.name {
                x.leaf("ram:Name", &[], n);
            }
            if let Some(d) = &i.description {
                x.leaf("ram:Description", &[], d);
            }
            for a in &i.attributes {
                x.group("ram:ApplicableProductCharacteristic", |x| {
                    x.leaf(
                        "ram:Description",
                        &[],
                        a.name.as_deref().unwrap_or_default(),
                    );
                    x.leaf("ram:Value", &[], a.value.as_deref().unwrap_or_default());
                });
            }
            for c in &i.classification_identifiers {
                x.group("ram:DesignatedProductClassification", |x| {
                    let mut attrs: Vec<(&str, &str)> = Vec::new();
                    if let Some(s) = c.scheme() {
                        attrs.push(("listID", s));
                    }
                    x.leaf("ram:ClassCode", &attrs, c.content());
                });
            }
            if let Some(c) = &i.origin_country {
                x.group("ram:OriginTradeCountry", |x| {
                    x.leaf("ram:ID", &[], c.as_str());
                });
            }
        });
        x.group("ram:SpecifiedLineTradeAgreement", |x| {
            if let Some(o) = &l.order_line_reference {
                x.group("ram:BuyerOrderReferencedDocument", |x| {
                    x.leaf("ram:LineID", &[], o.as_str());
                });
            }
            // BT-148's gross price and BT-147's discount are one aggregate:
            // the discount is an *applied allowance* on the gross price, and
            // the net price BT-146 is a sibling. Same shape as UBL's
            // price-level `cac:AllowanceCharge`, differently named.
            if let Some(g) = l.price.gross_price {
                x.group("ram:GrossPriceProductTradePrice", |x| {
                    x.leaf("ram:ChargeAmount", &[], &g.to_string());
                    if let Some(q) = l.price.base_quantity {
                        let unit = l.price.base_quantity_code.as_ref().map_or("", Code::as_str);
                        x.leaf("ram:BasisQuantity", &[("unitCode", unit)], &q.to_string());
                    }
                    if let Some(d) = l.price.price_discount {
                        x.group("ram:AppliedTradeAllowanceCharge", |x| {
                            charge_indicator(x, false);
                            x.leaf("ram:ActualAmount", &[], &d.to_string());
                        });
                    }
                });
            }
            x.group("ram:NetPriceProductTradePrice", |x| {
                x.leaf("ram:ChargeAmount", &[], &l.price.net_price.to_string());
                if let Some(q) = l.price.base_quantity {
                    let unit = l.price.base_quantity_code.as_ref().map_or("", Code::as_str);
                    x.leaf("ram:BasisQuantity", &[("unitCode", unit)], &q.to_string());
                }
            });
        });
        x.group("ram:SpecifiedLineTradeDelivery", |x| {
            x.leaf(
                "ram:BilledQuantity",
                &[("unitCode", l.unit_code.as_str())],
                &l.quantity.to_string(),
            );
        });
        x.group("ram:SpecifiedLineTradeSettlement", |x| {
            x.group("ram:ApplicableTradeTax", |x| {
                x.leaf("ram:TypeCode", &[], "VAT");
                x.leaf("ram:CategoryCode", &[], l.vat.category.as_str());
                if let Some(r) = l.vat.rate {
                    x.leaf("ram:RateApplicablePercent", &[], &r.to_string());
                }
            });
            if let Some(p) = &l.period {
                period(x, "ram:BillingSpecifiedPeriod", p);
            }
            for (a, is_charge) in l
                .allowances
                .iter()
                .map(|a| (a, false))
                .chain(l.charges.iter().map(|c| (c, true)))
            {
                x.group("ram:SpecifiedTradeAllowanceCharge", |x| {
                    charge_indicator(x, is_charge);
                    if let Some(p) = a.percentage {
                        x.leaf("ram:CalculationPercent", &[], &p.to_string());
                    }
                    if let Some(b) = a.base_amount {
                        x.leaf("ram:BasisAmount", &[], &amt(b));
                    }
                    x.leaf("ram:ActualAmount", &[], &amt(a.amount));
                    if let Some(c) = &a.reason_code {
                        x.leaf("ram:ReasonCode", &[], c.as_str());
                    }
                    if let Some(r) = &a.reason {
                        x.leaf("ram:Reason", &[], r);
                    }
                });
            }
            x.group("ram:SpecifiedTradeSettlementLineMonetarySummation", |x| {
                x.leaf("ram:LineTotalAmount", &[], &amt(l.net_amount));
            });
            if let Some(o) = &l.object_identifier {
                x.group("ram:AdditionalReferencedDocument", |x| {
                    x.leaf("ram:IssuerAssignedID", &[], o.content());
                    x.leaf("ram:TypeCode", &[], "130");
                    if let Some(s) = o.scheme() {
                        x.leaf("ram:ReferenceTypeCode", &[], s);
                    }
                });
            }
            if let Some(a) = &l.accounting_reference {
                x.group("ram:ReceivableSpecifiedTradeAccountingAccount", |x| {
                    x.leaf("ram:ID", &[], a);
                });
            }
        });
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dates_are_wrapped_and_formatted() {
        let mut inv = Invoice::default();
        inv.issue_date = Some(Date::parse("2026-01-15").expect("date"));
        let out = write(&inv);
        assert!(
            out.xml
                .contains("<udt:DateTimeString format=\"102\">20260115</udt:DateTimeString>"),
            "{}",
            out.xml
        );
    }

    /// One document element for both kinds — CII tells them apart by BT-3.
    #[test]
    fn a_credit_note_uses_the_same_root() {
        let mut inv = Invoice::default();
        inv.kind = en16931::DocumentKind::CreditNote;
        inv.type_code = Some(Code::new("381"));
        let out = write(&inv);
        assert!(out.xml.contains("<rsm:CrossIndustryInvoice"), "{}", out.xml);
        assert!(out.xml.contains("<ram:TypeCode>381</ram:TypeCode>"));
    }

    /// The delivery section is mandatory in the D16B sequence even when there
    /// is nothing to say, so it must survive `group`'s empty-aggregate pruning.
    #[test]
    fn the_mandatory_delivery_section_is_always_present() {
        let out = write(&Invoice::default());
        assert!(
            out.xml.contains("ram:ApplicableHeaderTradeDelivery"),
            "{}",
            out.xml
        );
    }

    #[test]
    fn an_empty_invoice_writes_the_three_parts() {
        let out = write(&Invoice::default());
        for part in [
            "rsm:ExchangedDocumentContext",
            "rsm:ExchangedDocument",
            "rsm:SupplyChainTradeTransaction",
        ] {
            assert!(out.xml.contains(part), "missing {part}\n{}", out.xml);
        }
        assert!(out.dropped.is_empty(), "{:?}", out.dropped);
    }
}