fiscal-core 0.7.1

Core types, tax calculations, and XML builder for Brazilian fiscal documents
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
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
//! Typestate invoice builder for NF-e / NFC-e XML generation.
//!
//! ```text
//! InvoiceBuilder::new(issuer, env, model)   // Draft
//!     .series(1)
//!     .invoice_number(42)
//!     .add_item(item)
//!     .recipient(recipient)
//!     .payments(vec![payment])
//!     .build()?                              // Built
//!     .sign_with(|xml| sign(xml))?           // Signed
//!     .signed_xml()                          // &str
//! ```
//!
//! The typestate pattern ensures at compile time that `xml()` / `access_key()`
//! are only available after a successful `build()`, and `signed_xml()` is only
//! available after a successful `sign_with()`.

use std::marker::PhantomData;

use chrono::{DateTime, FixedOffset};

use crate::FiscalError;
use crate::newtypes::Cents;
use crate::types::*;

// ── Typestate markers ────────────────────────────────────────────────────────

/// Marker: invoice is being assembled (setters available, no XML yet).
pub struct Draft;

/// Marker: invoice has been built (XML and access key available, no setters).
pub struct Built;

/// Marker: invoice has been signed (signed XML available).
pub struct Signed;

// ── Builder ──────────────────────────────────────────────────────────────────

/// Typestate builder for NF-e / NFC-e XML documents.
///
/// In the [`Draft`] state all setters are available.
/// Calling [`build()`](InvoiceBuilder::build) validates the data and
/// transitions to [`Built`], which exposes [`xml()`](InvoiceBuilder::xml)
/// and [`access_key()`](InvoiceBuilder::access_key).
/// Calling [`sign_with()`](InvoiceBuilder::sign_with) on `Built` transitions
/// to [`Signed`], which exposes [`signed_xml()`](InvoiceBuilder::signed_xml).
pub struct InvoiceBuilder<State = Draft> {
    // Required from construction
    issuer: IssuerData,
    environment: SefazEnvironment,
    model: InvoiceModel,
    schema_version: SchemaVersion,

    // Defaults provided, overridable
    series: u32,
    invoice_number: u32,
    emission_type: EmissionType,
    issued_at: DateTime<FixedOffset>,
    operation_nature: String,

    // Accumulated during Draft
    items: Vec<InvoiceItemData>,
    recipient: Option<RecipientData>,
    payments: Vec<PaymentData>,
    change_amount: Option<Cents>,
    payment_card_details: Option<Vec<PaymentCardDetail>>,
    contingency: Option<ContingencyData>,
    exit_at: Option<DateTime<FixedOffset>>,

    // IDE overrides
    operation_type: Option<u8>,
    purpose_code: Option<u8>,
    destination_indicator: Option<String>,
    intermediary_indicator: Option<String>,
    emission_process: Option<String>,
    consumer_type: Option<String>,
    buyer_presence: Option<String>,
    print_format: Option<String>,
    ver_proc: Option<String>,
    references: Option<Vec<ReferenceDoc>>,

    // Optional groups
    transport: Option<TransportData>,
    billing: Option<BillingData>,
    withdrawal: Option<LocationData>,
    delivery: Option<LocationData>,
    authorized_xml: Option<Vec<AuthorizedXml>>,
    additional_info: Option<AdditionalInfo>,
    intermediary: Option<IntermediaryData>,
    ret_trib: Option<RetTribData>,
    tech_responsible: Option<TechResponsibleData>,
    purchase: Option<PurchaseData>,
    export: Option<ExportData>,
    issqn_tot: Option<IssqnTotData>,
    cana: Option<CanaData>,
    agropecuario: Option<AgropecuarioData>,
    compra_gov: Option<CompraGovData>,
    pag_antecipado: Option<PagAntecipadoData>,
    is_tot: Option<crate::tax_ibs_cbs::IsTotData>,
    ibs_cbs_tot: Option<crate::tax_ibs_cbs::IbsCbsTotData>,
    v_nf_tot_override: Option<Cents>,

    // ASCII sanitization
    only_ascii: bool,
    calculation_method: crate::types::CalculationMethod,

    // Present only after build
    result_xml: Option<String>,
    result_access_key: Option<String>,

    // Present only after sign
    result_signed_xml: Option<String>,

    _state: PhantomData<State>,
}

// ── Draft methods (setters + build) ──────────────────────────────────────────

impl InvoiceBuilder<Draft> {
    /// Create a new builder in the [`Draft`] state.
    ///
    /// The three arguments are required; everything else has sensible defaults
    /// or is optional.
    pub fn new(issuer: IssuerData, environment: SefazEnvironment, model: InvoiceModel) -> Self {
        let now = chrono::Utc::now()
            .with_timezone(&FixedOffset::west_opt(3 * 3600).expect("valid offset"));

        Self {
            issuer,
            environment,
            model,
            schema_version: SchemaVersion::default(),
            series: 1,
            invoice_number: 1,
            emission_type: EmissionType::Normal,
            issued_at: now,
            operation_nature: "VENDA".to_string(),
            items: Vec::new(),
            recipient: None,
            payments: Vec::new(),
            change_amount: None,
            payment_card_details: None,
            contingency: None,
            exit_at: None,
            operation_type: None,
            purpose_code: None,
            destination_indicator: None,
            intermediary_indicator: None,
            emission_process: None,
            consumer_type: None,
            buyer_presence: None,
            print_format: None,
            ver_proc: None,
            references: None,
            transport: None,
            billing: None,
            withdrawal: None,
            delivery: None,
            authorized_xml: None,
            additional_info: None,
            intermediary: None,
            ret_trib: None,
            tech_responsible: None,
            purchase: None,
            export: None,
            issqn_tot: None,
            cana: None,
            agropecuario: None,
            compra_gov: None,
            pag_antecipado: None,
            is_tot: None,
            ibs_cbs_tot: None,
            v_nf_tot_override: None,
            only_ascii: false,
            calculation_method: crate::types::CalculationMethod::V2,
            result_xml: None,
            result_access_key: None,
            result_signed_xml: None,
            _state: PhantomData,
        }
    }

    // ── Chainable setters ────────────────────────────────────────────────

    /// Set the invoice series (default: 1).
    pub fn series(mut self, s: u32) -> Self {
        self.series = s;
        self
    }

    /// Set the invoice number (default: 1).
    pub fn invoice_number(mut self, n: u32) -> Self {
        self.invoice_number = n;
        self
    }

    /// Set the emission type (default: [`EmissionType::Normal`]).
    pub fn emission_type(mut self, et: EmissionType) -> Self {
        self.emission_type = et;
        self
    }

    /// Set the schema version (default: [`SchemaVersion::PL009`]).
    ///
    /// When [`PL009`](SchemaVersion::PL009), PL_010-exclusive tags (IBS/CBS, IS,
    /// `gCompraGov`, `gPagAntecipado`, `agropecuario`) are silently omitted
    /// even if data is provided.
    ///
    /// When [`PL010`](SchemaVersion::PL010), all reform-related tags are emitted
    /// normally.
    pub fn schema_version(mut self, sv: SchemaVersion) -> Self {
        self.schema_version = sv;
        self
    }

    /// Set the emission date/time (default: now in UTC-3).
    pub fn issued_at(mut self, dt: DateTime<FixedOffset>) -> Self {
        self.issued_at = dt;
        self
    }

    /// Set the operation nature (default: `"VENDA"`).
    pub fn operation_nature(mut self, n: impl Into<String>) -> Self {
        self.operation_nature = n.into();
        self
    }

    /// Add one item to the invoice.
    pub fn add_item(mut self, item: InvoiceItemData) -> Self {
        self.items.push(item);
        self
    }

    /// Set all items at once (replaces any previously added items).
    pub fn items(mut self, items: Vec<InvoiceItemData>) -> Self {
        self.items = items;
        self
    }

    /// Set the recipient (optional for NFC-e under R$200).
    pub fn recipient(mut self, r: RecipientData) -> Self {
        self.recipient = Some(r);
        self
    }

    /// Set the payment list.
    pub fn payments(mut self, p: Vec<PaymentData>) -> Self {
        self.payments = p;
        self
    }

    /// Set the change amount (vTroco).
    pub fn change_amount(mut self, c: Cents) -> Self {
        self.change_amount = Some(c);
        self
    }

    /// Set card payment details.
    pub fn payment_card_details(mut self, d: Vec<PaymentCardDetail>) -> Self {
        self.payment_card_details = Some(d);
        self
    }

    /// Set contingency data.
    pub fn contingency(mut self, c: ContingencyData) -> Self {
        self.contingency = Some(c);
        self
    }

    /// Set the exit/departure date/time (dhSaiEnt, model 55 only).
    pub fn exit_at(mut self, dt: DateTime<FixedOffset>) -> Self {
        self.exit_at = Some(dt);
        self
    }

    /// Override the operation type (tpNF, default: 1).
    pub fn operation_type(mut self, v: u8) -> Self {
        self.operation_type = Some(v);
        self
    }

    /// Override the invoice purpose code (finNFe, default: 1).
    pub fn purpose_code(mut self, v: u8) -> Self {
        self.purpose_code = Some(v);
        self
    }

    /// Set the intermediary indicator (indIntermed).
    pub fn intermediary_indicator(mut self, v: impl Into<String>) -> Self {
        self.intermediary_indicator = Some(v.into());
        self
    }

    /// Set the emission process (procEmi).
    pub fn emission_process(mut self, v: impl Into<String>) -> Self {
        self.emission_process = Some(v.into());
        self
    }

    /// Set the consumer type (indFinal).
    pub fn consumer_type(mut self, v: impl Into<String>) -> Self {
        self.consumer_type = Some(v.into());
        self
    }

    /// Set the buyer presence indicator (indPres).
    pub fn buyer_presence(mut self, v: impl Into<String>) -> Self {
        self.buyer_presence = Some(v.into());
        self
    }

    /// Set the DANFE print format (tpImp).
    pub fn print_format(mut self, v: impl Into<String>) -> Self {
        self.print_format = Some(v.into());
        self
    }

    /// Set the destination indicator (idDest): "1" internal, "2" interstate, "3" export.
    pub fn destination_indicator(mut self, v: impl Into<String>) -> Self {
        self.destination_indicator = Some(v.into());
        self
    }

    /// Set the application version (verProc).
    pub fn ver_proc(mut self, v: impl Into<String>) -> Self {
        self.ver_proc = Some(v.into());
        self
    }

    /// Set referenced documents (NFref).
    pub fn references(mut self, refs: Vec<ReferenceDoc>) -> Self {
        self.references = Some(refs);
        self
    }

    /// Set transport data.
    pub fn transport(mut self, t: TransportData) -> Self {
        self.transport = Some(t);
        self
    }

    /// Set billing data (cobr).
    pub fn billing(mut self, b: BillingData) -> Self {
        self.billing = Some(b);
        self
    }

    /// Set the withdrawal/pickup location (retirada).
    pub fn withdrawal(mut self, w: LocationData) -> Self {
        self.withdrawal = Some(w);
        self
    }

    /// Set the delivery location (entrega).
    pub fn delivery(mut self, d: LocationData) -> Self {
        self.delivery = Some(d);
        self
    }

    /// Set authorized XML downloaders (autXML).
    pub fn authorized_xml(mut self, a: Vec<AuthorizedXml>) -> Self {
        self.authorized_xml = Some(a);
        self
    }

    /// Set additional info (infAdic).
    pub fn additional_info(mut self, a: AdditionalInfo) -> Self {
        self.additional_info = Some(a);
        self
    }

    /// Set intermediary data (infIntermed).
    pub fn intermediary(mut self, i: IntermediaryData) -> Self {
        self.intermediary = Some(i);
        self
    }

    /// Set retained taxes (retTrib).
    pub fn ret_trib(mut self, r: RetTribData) -> Self {
        self.ret_trib = Some(r);
        self
    }

    /// Set tech responsible (infRespTec).
    pub fn tech_responsible(mut self, t: TechResponsibleData) -> Self {
        self.tech_responsible = Some(t);
        self
    }

    /// Set purchase data (compra).
    pub fn purchase(mut self, p: PurchaseData) -> Self {
        self.purchase = Some(p);
        self
    }

    /// Set export data (exporta).
    pub fn export(mut self, e: ExportData) -> Self {
        self.export = Some(e);
        self
    }

    /// Set ISSQN total data (ISSQNtot).
    pub fn issqn_tot(mut self, t: IssqnTotData) -> Self {
        self.issqn_tot = Some(t);
        self
    }

    /// Set sugarcane supply data (cana).
    pub fn cana(mut self, c: CanaData) -> Self {
        self.cana = Some(c);
        self
    }

    /// Set agropecuário data (guia de trânsito or defensivos).
    pub fn agropecuario(mut self, a: AgropecuarioData) -> Self {
        self.agropecuario = Some(a);
        self
    }

    /// Set compra governamental data (gCompraGov, PL_010+).
    pub fn compra_gov(mut self, c: CompraGovData) -> Self {
        self.compra_gov = Some(c);
        self
    }

    /// Set pagamento antecipado data (gPagAntecipado, PL_010+).
    pub fn pag_antecipado(mut self, p: PagAntecipadoData) -> Self {
        self.pag_antecipado = Some(p);
        self
    }

    /// Set IS (Imposto Seletivo) total data.
    pub fn is_tot(mut self, t: crate::tax_ibs_cbs::IsTotData) -> Self {
        self.is_tot = Some(t);
        self
    }

    /// Set IBS/CBS total data.
    pub fn ibs_cbs_tot(mut self, t: crate::tax_ibs_cbs::IbsCbsTotData) -> Self {
        self.ibs_cbs_tot = Some(t);
        self
    }

    /// Enable or disable ASCII-only mode.
    ///
    /// When enabled, accented characters (common in Brazilian Portuguese) are
    /// replaced by their closest ASCII equivalents in the generated XML.
    /// For example, "São Paulo" becomes "Sao Paulo".
    ///
    /// This mirrors the PHP `Make::setOnlyAscii()` method.
    pub fn only_ascii(mut self, enabled: bool) -> Self {
        self.only_ascii = enabled;
        self
    }

    /// Set the calculation method for automatic totals (`vNF` and `vItem`).
    ///
    /// - [`V1`](CalculationMethod::V1) — from accumulated struct values.
    /// - [`V2`](CalculationMethod::V2) — from built XML tags (default).
    ///
    /// Matches the PHP `setCalculationMethod()` API.
    pub fn calculation_method(mut self, m: crate::types::CalculationMethod) -> Self {
        self.calculation_method = m;
        self
    }

    /// Override the `vNFTot` value (PL_010 only).
    ///
    /// When set, this value is used instead of the auto-calculated
    /// `vNF + vIBS + vCBS + vIS`.  Matches the PHP `tagTotal(vNFTot)` API.
    ///
    /// Only emitted when schema is [`PL010`](SchemaVersion::PL010) and
    /// `IBSCBSTot` is present.
    pub fn v_nf_tot_override(mut self, v: Cents) -> Self {
        self.v_nf_tot_override = Some(v);
        self
    }

    /// Validate and build the XML, transitioning to [`Built`].
    ///
    /// # Errors
    ///
    /// Returns [`FiscalError`] if:
    /// - The issuer state code is unknown
    /// - Tax data is invalid
    pub fn build(self) -> Result<InvoiceBuilder<Built>, FiscalError> {
        let data = InvoiceBuildData {
            schema_version: self.schema_version,
            model: self.model,
            series: self.series,
            number: self.invoice_number,
            emission_type: self.emission_type,
            environment: self.environment,
            issued_at: self.issued_at,
            operation_nature: self.operation_nature,
            issuer: self.issuer,
            recipient: self.recipient,
            items: self.items,
            payments: self.payments,
            change_amount: self.change_amount,
            payment_card_details: self.payment_card_details,
            contingency: self.contingency,
            exit_at: self.exit_at,
            operation_type: self.operation_type,
            purpose_code: self.purpose_code,
            destination_indicator: self.destination_indicator,
            intermediary_indicator: self.intermediary_indicator,
            emission_process: self.emission_process,
            consumer_type: self.consumer_type,
            buyer_presence: self.buyer_presence,
            print_format: self.print_format,
            ver_proc: self.ver_proc,
            references: self.references,
            transport: self.transport,
            billing: self.billing,
            withdrawal: self.withdrawal,
            delivery: self.delivery,
            authorized_xml: self.authorized_xml,
            additional_info: self.additional_info,
            intermediary: self.intermediary,
            ret_trib: self.ret_trib,
            tech_responsible: self.tech_responsible,
            purchase: self.purchase,
            export: self.export,
            issqn_tot: self.issqn_tot,
            cana: self.cana,
            agropecuario: self.agropecuario,
            compra_gov: self.compra_gov,
            pag_antecipado: self.pag_antecipado,
            is_tot: self.is_tot,
            ibs_cbs_tot: self.ibs_cbs_tot,
            v_nf_tot_override: self.v_nf_tot_override,
            only_ascii: self.only_ascii,
            calculation_method: self.calculation_method,
        };

        let result = super::generate_xml(&data)?;

        Ok(InvoiceBuilder {
            issuer: data.issuer,
            environment: data.environment,
            model: data.model,
            schema_version: data.schema_version,
            series: data.series,
            invoice_number: data.number,
            emission_type: data.emission_type,
            issued_at: data.issued_at,
            operation_nature: data.operation_nature,
            items: data.items,
            recipient: data.recipient,
            payments: data.payments,
            change_amount: data.change_amount,
            payment_card_details: data.payment_card_details,
            contingency: data.contingency,
            exit_at: data.exit_at,
            operation_type: data.operation_type,
            purpose_code: data.purpose_code,
            destination_indicator: data.destination_indicator,
            intermediary_indicator: data.intermediary_indicator,
            emission_process: data.emission_process,
            consumer_type: data.consumer_type,
            buyer_presence: data.buyer_presence,
            print_format: data.print_format,
            ver_proc: data.ver_proc,
            references: data.references,
            transport: data.transport,
            billing: data.billing,
            withdrawal: data.withdrawal,
            delivery: data.delivery,
            authorized_xml: data.authorized_xml,
            additional_info: data.additional_info,
            intermediary: data.intermediary,
            ret_trib: data.ret_trib,
            tech_responsible: data.tech_responsible,
            purchase: data.purchase,
            export: data.export,
            issqn_tot: data.issqn_tot,
            cana: data.cana,
            agropecuario: data.agropecuario,
            compra_gov: data.compra_gov,
            pag_antecipado: data.pag_antecipado,
            is_tot: data.is_tot,
            ibs_cbs_tot: data.ibs_cbs_tot,
            v_nf_tot_override: data.v_nf_tot_override,
            only_ascii: data.only_ascii,
            calculation_method: data.calculation_method,
            result_xml: Some(result.xml),
            result_access_key: Some(result.access_key),
            result_signed_xml: None,
            _state: PhantomData,
        })
    }
}

// ── Built methods (accessors) ────────────────────────────────────────────────

impl InvoiceBuilder<Built> {
    /// The unsigned XML string.
    pub fn xml(&self) -> &str {
        self.result_xml
            .as_deref()
            .expect("Built state always has XML")
    }

    /// The 44-digit access key.
    pub fn access_key(&self) -> &str {
        self.result_access_key
            .as_deref()
            .expect("Built state always has access key")
    }

    /// Sign the XML using the provided signing function.
    ///
    /// The signing function receives the unsigned XML and must return
    /// the signed XML or an error. This keeps `fiscal-core` independent
    /// of the crypto implementation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use fiscal_core::xml_builder::{InvoiceBuilder, Draft, Built, Signed};
    /// # use fiscal_core::FiscalError;
    /// // Assuming `builder` is an InvoiceBuilder<Built>:
    /// # fn example(builder: InvoiceBuilder<Built>) -> Result<(), FiscalError> {
    /// let signed = builder.sign_with(|xml| {
    ///     // In real code, call fiscal_crypto::certificate::sign_xml() here.
    ///     Ok(format!("{xml}<Signature/>"))
    /// })?;
    /// assert!(signed.signed_xml().contains("<Signature/>"));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`FiscalError`] if the signing function returns an error.
    pub fn sign_with<F>(self, signer: F) -> Result<InvoiceBuilder<Signed>, FiscalError>
    where
        F: FnOnce(&str) -> Result<String, FiscalError>,
    {
        let unsigned_xml = self
            .result_xml
            .as_deref()
            .expect("Built state always has XML");

        let signed_xml = signer(unsigned_xml)?;

        Ok(InvoiceBuilder {
            issuer: self.issuer,
            environment: self.environment,
            model: self.model,
            schema_version: self.schema_version,
            series: self.series,
            invoice_number: self.invoice_number,
            emission_type: self.emission_type,
            issued_at: self.issued_at,
            operation_nature: self.operation_nature,
            items: self.items,
            recipient: self.recipient,
            payments: self.payments,
            change_amount: self.change_amount,
            payment_card_details: self.payment_card_details,
            contingency: self.contingency,
            exit_at: self.exit_at,
            operation_type: self.operation_type,
            purpose_code: self.purpose_code,
            destination_indicator: self.destination_indicator,
            intermediary_indicator: self.intermediary_indicator,
            emission_process: self.emission_process,
            consumer_type: self.consumer_type,
            buyer_presence: self.buyer_presence,
            print_format: self.print_format,
            ver_proc: self.ver_proc,
            references: self.references,
            transport: self.transport,
            billing: self.billing,
            withdrawal: self.withdrawal,
            delivery: self.delivery,
            authorized_xml: self.authorized_xml,
            additional_info: self.additional_info,
            intermediary: self.intermediary,
            ret_trib: self.ret_trib,
            tech_responsible: self.tech_responsible,
            purchase: self.purchase,
            export: self.export,
            issqn_tot: self.issqn_tot,
            cana: self.cana,
            agropecuario: self.agropecuario,
            compra_gov: self.compra_gov,
            pag_antecipado: self.pag_antecipado,
            is_tot: self.is_tot,
            ibs_cbs_tot: self.ibs_cbs_tot,
            v_nf_tot_override: self.v_nf_tot_override,
            only_ascii: self.only_ascii,
            calculation_method: self.calculation_method,
            result_xml: self.result_xml,
            result_access_key: self.result_access_key,
            result_signed_xml: Some(signed_xml),
            _state: PhantomData,
        })
    }
}

// ── Signed methods (accessors) ──────────────────────────────────────────────

impl InvoiceBuilder<Signed> {
    /// The signed XML string (includes `<Signature>` element).
    pub fn signed_xml(&self) -> &str {
        self.result_signed_xml
            .as_deref()
            .expect("Signed state always has signed XML")
    }

    /// The 44-digit access key.
    pub fn access_key(&self) -> &str {
        self.result_access_key
            .as_deref()
            .expect("Signed state always has access key")
    }

    /// The unsigned XML (before signing).
    pub fn unsigned_xml(&self) -> &str {
        self.result_xml
            .as_deref()
            .expect("Signed state always has unsigned XML")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::newtypes::{Cents, IbgeCode, Rate};
    use crate::types::{
        InvoiceItemData, InvoiceModel, IssuerData, PaymentData, SefazEnvironment, TaxRegime,
    };

    /// Standard Brazilian timezone offset (UTC-3).
    fn br_offset() -> chrono::FixedOffset {
        chrono::FixedOffset::west_opt(3 * 3600).unwrap()
    }

    /// Build a minimal InvoiceBuilder in Draft state.
    fn sample_builder() -> InvoiceBuilder<Draft> {
        let issuer = IssuerData::new(
            "12345678000199",
            "123456789",
            "Test Company",
            TaxRegime::SimplesNacional,
            "SP",
            IbgeCode("3550308".to_string()),
            "Sao Paulo",
            "Av Paulista",
            "1000",
            "Bela Vista",
            "01310100",
        )
        .trade_name("Test");

        let item = InvoiceItemData::new(
            1,
            "1",
            "Product A",
            "84715010",
            "5102",
            "UN",
            2.0,
            Cents(1000),
            Cents(2000),
            "102",
            Rate(0),
            Cents(0),
            "99",
            "99",
        );

        let payment = PaymentData::new("01", Cents(2000));

        let offset = br_offset();
        let issued_at = chrono::NaiveDate::from_ymd_opt(2026, 1, 15)
            .unwrap()
            .and_hms_opt(10, 30, 0)
            .unwrap()
            .and_local_timezone(offset)
            .unwrap();

        InvoiceBuilder::new(issuer, SefazEnvironment::Homologation, InvoiceModel::Nfce)
            .series(1)
            .invoice_number(1)
            .issued_at(issued_at)
            .add_item(item)
            .payments(vec![payment])
    }

    /// Build a minimal InvoiceBuilder<Built>.
    fn built_builder() -> InvoiceBuilder<Built> {
        sample_builder().build().expect("build should succeed")
    }

    #[test]
    fn sign_with_identity_fn() {
        let built = built_builder();
        let original_xml = built.xml().to_string();

        let signed = built
            .sign_with(|xml| Ok(xml.to_string()))
            .expect("identity signer should not fail");

        assert_eq!(signed.signed_xml(), original_xml);
    }

    #[test]
    fn sign_with_failing_fn() {
        let built = built_builder();

        let result =
            built.sign_with(|_xml| Err(FiscalError::Certificate("test signing failure".into())));

        let err = match result {
            Err(e) => e,
            Ok(_) => panic!("expected sign_with to return Err"),
        };
        assert_eq!(err, FiscalError::Certificate("test signing failure".into()),);
    }

    #[test]
    fn signed_accessors() {
        let built = built_builder();
        let original_xml = built.xml().to_string();
        let original_key = built.access_key().to_string();

        let signed = built
            .sign_with(|xml| Ok(format!("{xml}<Signature/>")))
            .expect("signer should succeed");

        assert_eq!(signed.signed_xml(), format!("{original_xml}<Signature/>"),);
        assert_eq!(signed.access_key(), original_key);
        assert_eq!(signed.unsigned_xml(), original_xml);
    }

    #[test]
    fn built_still_works() {
        let built = built_builder();

        // Verify Built accessors are available and correct.
        let xml = built.xml();
        assert!(xml.contains("<NFe"));
        assert!(xml.contains("</NFe>"));
        assert!(xml.contains("<infNFe"));

        let key = built.access_key();
        assert_eq!(key.len(), 44);
        assert!(key.chars().all(|c| c.is_ascii_digit()));
    }

    /// Build an NF-e (model 55) builder for testing dhSaiEnt.
    fn nfe_builder() -> InvoiceBuilder<Draft> {
        let issuer = IssuerData::new(
            "12345678000199",
            "123456789",
            "Test Company",
            TaxRegime::SimplesNacional,
            "SP",
            IbgeCode("3550308".to_string()),
            "Sao Paulo",
            "Av Paulista",
            "1000",
            "Bela Vista",
            "01310100",
        )
        .trade_name("Test");

        let item = InvoiceItemData::new(
            1,
            "1",
            "Product A",
            "84715010",
            "5102",
            "UN",
            2.0,
            Cents(1000),
            Cents(2000),
            "102",
            Rate(0),
            Cents(0),
            "99",
            "99",
        );

        let payment = PaymentData::new("01", Cents(2000));

        let offset = br_offset();
        let issued_at = chrono::NaiveDate::from_ymd_opt(2026, 1, 15)
            .unwrap()
            .and_hms_opt(10, 30, 0)
            .unwrap()
            .and_local_timezone(offset)
            .unwrap();

        InvoiceBuilder::new(issuer, SefazEnvironment::Homologation, InvoiceModel::Nfe)
            .series(1)
            .invoice_number(1)
            .issued_at(issued_at)
            .add_item(item)
            .payments(vec![payment])
    }

    #[test]
    fn dh_sai_ent_emitted_for_model_55() {
        let offset = br_offset();
        let exit = chrono::NaiveDate::from_ymd_opt(2026, 1, 15)
            .unwrap()
            .and_hms_opt(14, 0, 0)
            .unwrap()
            .and_local_timezone(offset)
            .unwrap();

        let built = nfe_builder()
            .exit_at(exit)
            .build()
            .expect("build should succeed");

        let xml = built.xml();
        assert!(
            xml.contains("<dhSaiEnt>2026-01-15T14:00:00-03:00</dhSaiEnt>"),
            "NF-e (model 55) with exit_at must emit <dhSaiEnt>, got:\n{xml}"
        );
        // Verify ordering: dhSaiEnt must come after dhEmi and before tpNF
        let emi_pos = xml.find("<dhEmi>").expect("dhEmi must be present");
        let sai_pos = xml.find("<dhSaiEnt>").expect("dhSaiEnt must be present");
        let tp_nf_pos = xml.find("<tpNF>").expect("tpNF must be present");
        assert!(
            emi_pos < sai_pos && sai_pos < tp_nf_pos,
            "dhSaiEnt must come after dhEmi and before tpNF"
        );
    }

    #[test]
    fn dh_sai_ent_omitted_for_model_65() {
        let offset = br_offset();
        let exit = chrono::NaiveDate::from_ymd_opt(2026, 1, 15)
            .unwrap()
            .and_hms_opt(14, 0, 0)
            .unwrap()
            .and_local_timezone(offset)
            .unwrap();

        let built = sample_builder()
            .exit_at(exit)
            .build()
            .expect("build should succeed");

        let xml = built.xml();
        assert!(
            !xml.contains("<dhSaiEnt>"),
            "NFC-e (model 65) must NOT emit <dhSaiEnt>, got:\n{xml}"
        );
    }

    #[test]
    fn dh_sai_ent_omitted_when_not_set() {
        let built = nfe_builder().build().expect("build should succeed");

        let xml = built.xml();
        assert!(
            !xml.contains("<dhSaiEnt>"),
            "NF-e without exit_at must NOT emit <dhSaiEnt>"
        );
    }

    #[test]
    fn dh_cont_and_x_just_emitted_in_contingency() {
        use crate::types::{ContingencyData, ContingencyType};

        let offset = br_offset();
        let cont_at = chrono::NaiveDate::from_ymd_opt(2026, 1, 15)
            .unwrap()
            .and_hms_opt(9, 0, 0)
            .unwrap()
            .and_local_timezone(offset)
            .unwrap();

        let contingency = ContingencyData::new(
            ContingencyType::SvcAn,
            "SEFAZ fora do ar para manutencao programada",
            cont_at,
        );

        let built = nfe_builder()
            .contingency(contingency)
            .build()
            .expect("build should succeed");

        let xml = built.xml();
        assert!(
            xml.contains("<dhCont>2026-01-15T09:00:00-03:00</dhCont>"),
            "Contingency must emit <dhCont>, got:\n{xml}"
        );
        assert!(
            xml.contains("<xJust>SEFAZ fora do ar para manutencao programada</xJust>"),
            "Contingency must emit <xJust>, got:\n{xml}"
        );
        // Verify ordering: dhCont/xJust must come after verProc
        let ver_proc_pos = xml.find("<verProc>").expect("verProc must be present");
        let dh_cont_pos = xml.find("<dhCont>").expect("dhCont must be present");
        let x_just_pos = xml.find("<xJust>").expect("xJust must be present");
        assert!(
            ver_proc_pos < dh_cont_pos && dh_cont_pos < x_just_pos,
            "dhCont must come after verProc, xJust must come after dhCont"
        );
    }

    #[test]
    fn dh_cont_omitted_without_contingency() {
        let built = nfe_builder().build().expect("build should succeed");

        let xml = built.xml();
        assert!(
            !xml.contains("<dhCont>"),
            "Without contingency, <dhCont> must NOT be present"
        );
        assert!(
            !xml.contains("<xJust>"),
            "Without contingency, <xJust> must NOT be present"
        );
    }
}