fiscal-core 0.7.3

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
//! PIS, COFINS, IPI, and II (import tax) XML generation for NF-e items.
//!
//! Public entry points:
//! - [`build_pis_xml`] / [`build_pis_st_xml`] — `<PIS>` / `<PISST>` elements
//! - [`build_cofins_xml`] / [`build_cofins_st_xml`] — `<COFINS>` / `<COFINSST>` elements
//! - [`build_ipi_xml`] — `<IPI>` element (IPITrib or IPINT)
//! - [`build_ii_xml`] — `<II>` import-tax element
//!
//! Internally PIS and COFINS share a single generic engine parameterised by
//! [`ContributionTaxConfig`]; their public APIs accept separate typed structs
//! ([`PisData`] / [`CofinsData`]) so callers remain independent.

use serde::{Deserialize, Serialize};

use crate::format_utils::{format_cents_or_zero, format_rate_4, format_rate4_or_zero};
use crate::newtypes::{Cents, Rate, Rate4};
use crate::tax_element::{TaxElement, TaxField, serialize_tax_element};

// ── CST classification sets ─────────────────────────────────────────────────

/// PIS/COFINS CSTs that use percentage-based calculation (Aliq variant).
const ALIQ_CSTS: &[&str] = &["01", "02"];

/// PIS/COFINS CSTs that use quantity-based calculation (Qtde variant).
const QTDE_CSTS: &[&str] = &["03"];

/// PIS/COFINS CSTs that are not taxed (NT variant).
const NT_CSTS: &[&str] = &["04", "05", "06", "07", "08", "09"];

/// PIS/COFINS CSTs that use "other operations" (Outr variant).
const OUTR_CSTS: &[&str] = &[
    "49", "50", "51", "52", "53", "54", "55", "56", "60", "61", "62", "63", "64", "65", "66", "67",
    "70", "71", "72", "73", "74", "75", "98", "99",
];

/// IPI CSTs that are taxed (Trib variant): 00, 49, 50, 99.
const IPI_TRIB_CSTS: &[&str] = &["00", "49", "50", "99"];

// ── Types ───────────────────────────────────────────────────────────────────

/// PIS tax input data. Monetary fields use [`Cents`], rates use [`Rate4`].
///
/// Build with [`PisData::new`] and chain the optional setters.
/// Pass to [`build_pis_xml`] to generate the `<PIS>` XML fragment.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
#[non_exhaustive]
pub struct PisData {
    /// PIS CST code (`CST`), e.g. `"01"`, `"07"`.
    pub cst: String,
    /// Calculation base value (`vBC`). Required for CST 01/02.
    pub v_bc: Option<Cents>,
    /// PIS rate (`pPIS`). Required for CST 01/02.
    pub p_pis: Option<Rate4>,
    /// PIS value (`vPIS`). Required for CST 01/02/49+.
    pub v_pis: Option<Cents>,
    /// Quantity base for unit-rate calculation (`qBCProd`). Required for CST 03.
    pub q_bc_prod: Option<i64>,
    /// Unit aliquot in tenths of reais (`vAliqProd`). Required for CST 03.
    pub v_aliq_prod: Option<i64>,
}

impl PisData {
    /// Create a new `PisData` with the required CST.
    pub fn new(cst: impl Into<String>) -> Self {
        Self {
            cst: cst.into(),
            ..Default::default()
        }
    }
    /// Set the base value.
    pub fn v_bc(mut self, v: Cents) -> Self {
        self.v_bc = Some(v);
        self
    }
    /// Set the PIS rate.
    pub fn p_pis(mut self, v: Rate4) -> Self {
        self.p_pis = Some(v);
        self
    }
    /// Set the PIS value.
    pub fn v_pis(mut self, v: Cents) -> Self {
        self.v_pis = Some(v);
        self
    }
    /// Set the quantity base.
    pub fn q_bc_prod(mut self, v: i64) -> Self {
        self.q_bc_prod = Some(v);
        self
    }
    /// Set the quantity rate.
    pub fn v_aliq_prod(mut self, v: i64) -> Self {
        self.v_aliq_prod = Some(v);
        self
    }
}

/// PIS-ST (substituição tributária) input data.
///
/// Pass to [`build_pis_st_xml`] to generate the `<PISST>` XML fragment.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
#[non_exhaustive]
pub struct PisStData {
    /// ST calculation base value (`vBC`). Optional for quantity-based mode.
    pub v_bc: Option<Cents>,
    /// PIS rate for ST (`pPIS`). Optional.
    pub p_pis: Option<Rate4>,
    /// Quantity base for unit-rate calculation (`qBCProd`). Optional.
    pub q_bc_prod: Option<i64>,
    /// Unit aliquot (`vAliqProd`). Optional.
    pub v_aliq_prod: Option<i64>,
    /// PIS ST value (`vPIS`).
    pub v_pis: Cents,
    /// Indicates whether ST value should be summed (`indSomaPISST`). Optional.
    pub ind_soma_pis_st: Option<i64>,
}

impl PisStData {
    /// Create a new `PisStData` with the required PIS value.
    pub fn new(v_pis: Cents) -> Self {
        Self {
            v_pis,
            ..Default::default()
        }
    }
    /// Set the base value.
    pub fn v_bc(mut self, v: Cents) -> Self {
        self.v_bc = Some(v);
        self
    }
    /// Set the PIS rate.
    pub fn p_pis(mut self, v: Rate4) -> Self {
        self.p_pis = Some(v);
        self
    }
    /// Set the quantity base.
    pub fn q_bc_prod(mut self, v: i64) -> Self {
        self.q_bc_prod = Some(v);
        self
    }
    /// Set the quantity rate.
    pub fn v_aliq_prod(mut self, v: i64) -> Self {
        self.v_aliq_prod = Some(v);
        self
    }
    /// Set the ST indicator.
    pub fn ind_soma_pis_st(mut self, v: i64) -> Self {
        self.ind_soma_pis_st = Some(v);
        self
    }
}

/// COFINS tax input data. Monetary fields use [`Cents`], rates use [`Rate4`].
///
/// Build with [`CofinsData::new`] and chain the optional setters.
/// Pass to [`build_cofins_xml`] to generate the `<COFINS>` XML fragment.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
#[non_exhaustive]
pub struct CofinsData {
    /// COFINS CST code (`CST`), e.g. `"01"`, `"07"`.
    pub cst: String,
    /// Calculation base value (`vBC`). Required for CST 01/02.
    pub v_bc: Option<Cents>,
    /// COFINS rate (`pCOFINS`). Required for CST 01/02.
    pub p_cofins: Option<Rate4>,
    /// COFINS value (`vCOFINS`). Required for CST 01/02/49+.
    pub v_cofins: Option<Cents>,
    /// Quantity base for unit-rate calculation (`qBCProd`). Required for CST 03.
    pub q_bc_prod: Option<i64>,
    /// Unit aliquot in tenths of reais (`vAliqProd`). Required for CST 03.
    pub v_aliq_prod: Option<i64>,
}

impl CofinsData {
    /// Create a new `CofinsData` with the required CST.
    pub fn new(cst: impl Into<String>) -> Self {
        Self {
            cst: cst.into(),
            ..Default::default()
        }
    }
    /// Set the base value.
    pub fn v_bc(mut self, v: Cents) -> Self {
        self.v_bc = Some(v);
        self
    }
    /// Set the COFINS rate.
    pub fn p_cofins(mut self, v: Rate4) -> Self {
        self.p_cofins = Some(v);
        self
    }
    /// Set the COFINS value.
    pub fn v_cofins(mut self, v: Cents) -> Self {
        self.v_cofins = Some(v);
        self
    }
    /// Set the quantity base.
    pub fn q_bc_prod(mut self, v: i64) -> Self {
        self.q_bc_prod = Some(v);
        self
    }
    /// Set the quantity rate.
    pub fn v_aliq_prod(mut self, v: i64) -> Self {
        self.v_aliq_prod = Some(v);
        self
    }
}

/// COFINS-ST (substituição tributária) input data.
///
/// Pass to [`build_cofins_st_xml`] to generate the `<COFINSST>` XML fragment.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
#[non_exhaustive]
pub struct CofinsStData {
    /// ST calculation base value (`vBC`). Optional for quantity-based mode.
    pub v_bc: Option<Cents>,
    /// COFINS rate for ST (`pCOFINS`). Optional.
    pub p_cofins: Option<Rate4>,
    /// Quantity base for unit-rate calculation (`qBCProd`). Optional.
    pub q_bc_prod: Option<i64>,
    /// Unit aliquot (`vAliqProd`). Optional.
    pub v_aliq_prod: Option<i64>,
    /// COFINS ST value (`vCOFINS`).
    pub v_cofins: Cents,
    /// Indicates whether ST value should be summed (`indSomaCOFINSST`). Optional.
    pub ind_soma_cofins_st: Option<i64>,
}

impl CofinsStData {
    /// Create a new `CofinsStData` with the required COFINS value.
    pub fn new(v_cofins: Cents) -> Self {
        Self {
            v_cofins,
            ..Default::default()
        }
    }
    /// Set the base value.
    pub fn v_bc(mut self, v: Cents) -> Self {
        self.v_bc = Some(v);
        self
    }
    /// Set the COFINS rate.
    pub fn p_cofins(mut self, v: Rate4) -> Self {
        self.p_cofins = Some(v);
        self
    }
    /// Set the quantity base.
    pub fn q_bc_prod(mut self, v: i64) -> Self {
        self.q_bc_prod = Some(v);
        self
    }
    /// Set the quantity rate.
    pub fn v_aliq_prod(mut self, v: i64) -> Self {
        self.v_aliq_prod = Some(v);
        self
    }
    /// Set the ST indicator.
    pub fn ind_soma_cofins_st(mut self, v: i64) -> Self {
        self.ind_soma_cofins_st = Some(v);
        self
    }
}

/// IPI (Imposto sobre Produtos Industrializados) input data.
///
/// Build with [`IpiData::new`] and chain the optional setters.
/// Pass to [`build_ipi_xml`] to generate the `<IPI>` XML fragment.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
#[non_exhaustive]
pub struct IpiData {
    /// IPI CST code (`CST`), e.g. `"00"`, `"53"`.
    pub cst: String,
    /// Enquadramento IPI code (`cEnq`), e.g. `"999"`.
    pub c_enq: String,
    /// Producer CNPJ (`CNPJProd`). Optional.
    pub cnpj_prod: Option<String>,
    /// Seal control code (`cSelo`). Optional.
    pub c_selo: Option<String>,
    /// Seal quantity (`qSelo`). Optional.
    pub q_selo: Option<i64>,
    /// Calculation base value (`vBC`). Required when `p_ipi` is set.
    pub v_bc: Option<Cents>,
    /// IPI rate (`pIPI`). Required for percentage-based taxed CSTs.
    pub p_ipi: Option<Rate>,
    /// Quantity of units (`qUnid`). Required for unit-rate taxed CSTs.
    pub q_unid: Option<i64>,
    /// Unit value (`vUnid`). Required for unit-rate taxed CSTs.
    pub v_unid: Option<i64>,
    /// IPI value (`vIPI`). Required for taxed CSTs.
    pub v_ipi: Option<Cents>,
}

impl IpiData {
    /// Create a new `IpiData` with required CST and enquadramento code.
    pub fn new(cst: impl Into<String>, c_enq: impl Into<String>) -> Self {
        Self {
            cst: cst.into(),
            c_enq: c_enq.into(),
            ..Default::default()
        }
    }
    /// Set the CNPJ of the producer.
    pub fn cnpj_prod(mut self, v: impl Into<String>) -> Self {
        self.cnpj_prod = Some(v.into());
        self
    }
    /// Set the seal code.
    pub fn c_selo(mut self, v: impl Into<String>) -> Self {
        self.c_selo = Some(v.into());
        self
    }
    /// Set the seal quantity.
    pub fn q_selo(mut self, v: i64) -> Self {
        self.q_selo = Some(v);
        self
    }
    /// Set the base value.
    pub fn v_bc(mut self, v: Cents) -> Self {
        self.v_bc = Some(v);
        self
    }
    /// Set the IPI rate.
    pub fn p_ipi(mut self, v: Rate) -> Self {
        self.p_ipi = Some(v);
        self
    }
    /// Set the unit quantity.
    pub fn q_unid(mut self, v: i64) -> Self {
        self.q_unid = Some(v);
        self
    }
    /// Set the unit value.
    pub fn v_unid(mut self, v: i64) -> Self {
        self.v_unid = Some(v);
        self
    }
    /// Set the IPI value.
    pub fn v_ipi(mut self, v: Cents) -> Self {
        self.v_ipi = Some(v);
        self
    }
}

/// II (Imposto de Importação — import tax) input data.
///
/// All four fields are required. Pass to [`build_ii_xml`] to generate the
/// `<II>` XML fragment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts", ts(export))]
#[non_exhaustive]
pub struct IiData {
    /// Import tax calculation base (`vBC`).
    pub v_bc: Cents,
    /// Customs clearance expenses (`vDespAdu`).
    pub v_desp_adu: Cents,
    /// Import tax value (`vII`).
    pub v_ii: Cents,
    /// IOF (tax on financial operations) value (`vIOF`).
    pub v_iof: Cents,
}

impl IiData {
    /// Create a new `IiData` with all required fields.
    pub fn new(v_bc: Cents, v_desp_adu: Cents, v_ii: Cents, v_iof: Cents) -> Self {
        Self {
            v_bc,
            v_desp_adu,
            v_ii,
            v_iof,
        }
    }
}

// ── Contribution tax (PIS / COFINS) generic engine ─────────────────────────
//
// PIS and COFINS are two variants of the same "contribuicao social" domain
// concept. They share identical calculation logic -- only the XML tag names
// and field names differ. A ContributionTaxConfig captures those differences
// so a single set of private functions handles both taxes.

/// Configuration that captures the naming differences between PIS and COFINS.
struct ContributionTaxConfig {
    /// Tax name used as outer tag and variant prefix ("PIS" or "COFINS")
    tax_name: &'static str,
    /// Rate field name ("pPIS" or "pCOFINS")
    rate_field: &'static str,
    /// Value field name ("vPIS" or "vCOFINS")
    value_field: &'static str,
    /// ST variant tag ("PISST" or "COFINSST")
    st_tag: &'static str,
    /// ST indicator field name ("indSomaPISST" or "indSomaCOFINSST")
    st_indicator: &'static str,
}

const PIS_CONFIG: ContributionTaxConfig = ContributionTaxConfig {
    tax_name: "PIS",
    rate_field: "pPIS",
    value_field: "vPIS",
    st_tag: "PISST",
    st_indicator: "indSomaPISST",
};

const COFINS_CONFIG: ContributionTaxConfig = ContributionTaxConfig {
    tax_name: "COFINS",
    rate_field: "pCOFINS",
    value_field: "vCOFINS",
    st_tag: "COFINSST",
    st_indicator: "indSomaCOFINSST",
};

/// Normalized input for the contribution tax engine.
struct ContributionTaxInput<'a> {
    cst: &'a str,
    v_bc: Option<Cents>,
    rate: Option<Rate4>,
    value: Option<Cents>,
    q_bc_prod: Option<i64>,
    v_aliq_prod: Option<i64>,
}

/// Normalized input for the contribution tax ST engine.
struct ContributionTaxStInput {
    v_bc: Option<Cents>,
    rate: Option<Rate4>,
    q_bc_prod: Option<i64>,
    v_aliq_prod: Option<i64>,
    value: Cents,
    st_indicator: Option<i64>,
}

/// Build the "Outr" variant fields for PIS/COFINS.
fn build_contribution_outr_fields(
    d: &ContributionTaxInput,
    cfg: &ContributionTaxConfig,
) -> Vec<TaxField> {
    let mut fields = vec![TaxField::new("CST", d.cst)];

    if d.q_bc_prod.is_some() {
        fields.push(TaxField::new("qBCProd", format_rate4_or_zero(d.q_bc_prod)));
        fields.push(TaxField::new(
            "vAliqProd",
            format_rate4_or_zero(d.v_aliq_prod),
        ));
    } else {
        fields.push(TaxField::new(
            "vBC",
            format_cents_or_zero(d.v_bc.map(|c| c.0), 2),
        ));
        fields.push(TaxField::new(
            cfg.rate_field,
            format_rate4_or_zero(d.rate.map(|r| r.0)),
        ));
    }

    fields.push(TaxField::new(
        cfg.value_field,
        format_cents_or_zero(d.value.map(|c| c.0), 2),
    ));
    fields
}

/// Calculate a contribution tax (PIS or COFINS) element.
fn calculate_contribution_tax(d: &ContributionTaxInput, cfg: &ContributionTaxConfig) -> TaxElement {
    let cst = d.cst;

    let (variant_tag, fields) = if ALIQ_CSTS.contains(&cst) {
        let tag = format!("{}Aliq", cfg.tax_name);
        let fields = vec![
            TaxField::new("CST", cst),
            TaxField::new("vBC", format_cents_or_zero(d.v_bc.map(|c| c.0), 2)),
            TaxField::new(cfg.rate_field, format_rate4_or_zero(d.rate.map(|r| r.0))),
            TaxField::new(
                cfg.value_field,
                format_cents_or_zero(d.value.map(|c| c.0), 2),
            ),
        ];
        (tag, fields)
    } else if QTDE_CSTS.contains(&cst) {
        let tag = format!("{}Qtde", cfg.tax_name);
        let fields = vec![
            TaxField::new("CST", cst),
            TaxField::new("qBCProd", format_rate4_or_zero(d.q_bc_prod)),
            TaxField::new("vAliqProd", format_rate4_or_zero(d.v_aliq_prod)),
            TaxField::new(
                cfg.value_field,
                format_cents_or_zero(d.value.map(|c| c.0), 2),
            ),
        ];
        (tag, fields)
    } else if NT_CSTS.contains(&cst) {
        let tag = format!("{}NT", cfg.tax_name);
        let fields = vec![TaxField::new("CST", cst)];
        (tag, fields)
    } else if OUTR_CSTS.contains(&cst) {
        let tag = format!("{}Outr", cfg.tax_name);
        let fields = build_contribution_outr_fields(d, cfg);
        (tag, fields)
    } else {
        // Fallback: treat unknown CSTs as NT
        let tag = format!("{}NT", cfg.tax_name);
        let fields = vec![TaxField::new("CST", cst)];
        (tag, fields)
    };

    TaxElement {
        outer_tag: Some(cfg.tax_name.to_string()),
        outer_fields: vec![],
        variant_tag,
        fields,
    }
}

/// Calculate a contribution tax ST (PIS-ST or COFINS-ST) element.
fn calculate_contribution_tax_st(
    d: &ContributionTaxStInput,
    cfg: &ContributionTaxConfig,
) -> TaxElement {
    let mut fields = Vec::new();

    if d.q_bc_prod.is_some() {
        fields.push(TaxField::new("qBCProd", format_rate4_or_zero(d.q_bc_prod)));
        fields.push(TaxField::new(
            "vAliqProd",
            format_rate4_or_zero(d.v_aliq_prod),
        ));
    } else {
        fields.push(TaxField::new(
            "vBC",
            format_cents_or_zero(d.v_bc.map(|c| c.0), 2),
        ));
        fields.push(TaxField::new(
            cfg.rate_field,
            format_rate4_or_zero(d.rate.map(|r| r.0)),
        ));
    }

    fields.push(TaxField::new(
        cfg.value_field,
        format_cents_or_zero(Some(d.value.0), 2),
    ));

    if let Some(indicator) = d.st_indicator {
        fields.push(TaxField::new(cfg.st_indicator, indicator.to_string()));
    }

    TaxElement {
        outer_tag: None,
        outer_fields: vec![],
        variant_tag: cfg.st_tag.to_string(),
        fields,
    }
}

// ── PIS (public API) ───────────────────────────────────────────────────────

/// Build PIS XML string.
///
/// Generates the `<PIS>` element with the appropriate variant tag based on CST:
/// - CST 01, 02: `<PISAliq>` (percentage-based)
/// - CST 03: `<PISQtde>` (quantity-based)
/// - CST 04-09: `<PISNT>` (not taxed)
/// - CST 49, 50-75, 98, 99: `<PISOutr>` (other operations)
pub fn build_pis_xml(data: &PisData) -> String {
    let input = ContributionTaxInput {
        cst: &data.cst,
        v_bc: data.v_bc,
        rate: data.p_pis,
        value: data.v_pis,
        q_bc_prod: data.q_bc_prod,
        v_aliq_prod: data.v_aliq_prod,
    };
    let element = calculate_contribution_tax(&input, &PIS_CONFIG);
    serialize_tax_element(&element)
}

/// Build PIS-ST XML string.
///
/// Generates the `<PISST>` element for PIS substituicao tributaria.
/// Supports both percentage-based (vBC/pPIS) and quantity-based (qBCProd/vAliqProd) modes.
pub fn build_pis_st_xml(data: &PisStData) -> String {
    let input = ContributionTaxStInput {
        v_bc: data.v_bc,
        rate: data.p_pis,
        q_bc_prod: data.q_bc_prod,
        v_aliq_prod: data.v_aliq_prod,
        value: data.v_pis,
        st_indicator: data.ind_soma_pis_st,
    };
    let element = calculate_contribution_tax_st(&input, &PIS_CONFIG);
    serialize_tax_element(&element)
}

// ── COFINS (public API) ────────────────────────────────────────────────────

/// Build COFINS XML string.
///
/// Generates the `<COFINS>` element with the appropriate variant tag based on CST:
/// - CST 01, 02: `<COFINSAliq>` (percentage-based)
/// - CST 03: `<COFINSQtde>` (quantity-based)
/// - CST 04-09: `<COFINSNT>` (not taxed)
/// - CST 49, 50-75, 98, 99: `<COFINSOutr>` (other operations)
pub fn build_cofins_xml(data: &CofinsData) -> String {
    let input = ContributionTaxInput {
        cst: &data.cst,
        v_bc: data.v_bc,
        rate: data.p_cofins,
        value: data.v_cofins,
        q_bc_prod: data.q_bc_prod,
        v_aliq_prod: data.v_aliq_prod,
    };
    let element = calculate_contribution_tax(&input, &COFINS_CONFIG);
    serialize_tax_element(&element)
}

/// Build COFINS-ST XML string.
///
/// Generates the `<COFINSST>` element for COFINS substituicao tributaria.
/// Supports both percentage-based (vBC/pCOFINS) and quantity-based (qBCProd/vAliqProd) modes.
pub fn build_cofins_st_xml(data: &CofinsStData) -> String {
    let input = ContributionTaxStInput {
        v_bc: data.v_bc,
        rate: data.p_cofins,
        q_bc_prod: data.q_bc_prod,
        v_aliq_prod: data.v_aliq_prod,
        value: data.v_cofins,
        st_indicator: data.ind_soma_cofins_st,
    };
    let element = calculate_contribution_tax_st(&input, &COFINS_CONFIG);
    serialize_tax_element(&element)
}

// ── IPI ─────────────────────────────────────────────────────────────────────

/// Build IPI XML string.
///
/// Generates the `<IPI>` element with outer fields (CNPJProd, cSelo, qSelo, cEnq)
/// and the appropriate variant tag:
/// - CST 00, 49, 50, 99: `<IPITrib>` (taxed) with vBC/pIPI or qUnid/vUnid
/// - All other CSTs: `<IPINT>` (not taxed)
pub fn build_ipi_xml(data: &IpiData) -> String {
    let mut outer_fields = Vec::new();

    if let Some(ref cnpj) = data.cnpj_prod {
        outer_fields.push(TaxField::new("CNPJProd", cnpj.as_str()));
    }
    if let Some(ref selo) = data.c_selo {
        outer_fields.push(TaxField::new("cSelo", selo.as_str()));
    }
    if let Some(q) = data.q_selo {
        outer_fields.push(TaxField::new("qSelo", q.to_string()));
    }
    outer_fields.push(TaxField::new("cEnq", &data.c_enq));

    let (variant_tag, fields) = if IPI_TRIB_CSTS.contains(&data.cst.as_str()) {
        let mut fields = vec![TaxField::new("CST", &data.cst)];

        if data.v_bc.is_some() && data.p_ipi.is_some() {
            fields.push(TaxField::new(
                "vBC",
                format_cents_or_zero(data.v_bc.map(|c| c.0), 2),
            ));
            fields.push(TaxField::new(
                "pIPI",
                format_rate_4(data.p_ipi.map(|r| r.0).unwrap_or(0)),
            ));
        } else {
            fields.push(TaxField::new("qUnid", format_rate4_or_zero(data.q_unid)));
            fields.push(TaxField::new("vUnid", format_rate4_or_zero(data.v_unid)));
        }

        fields.push(TaxField::new(
            "vIPI",
            format_cents_or_zero(data.v_ipi.map(|c| c.0), 2),
        ));
        ("IPITrib".to_string(), fields)
    } else {
        let fields = vec![TaxField::new("CST", &data.cst)];
        ("IPINT".to_string(), fields)
    };

    let element = TaxElement {
        outer_tag: Some("IPI".to_string()),
        outer_fields,
        variant_tag,
        fields,
    };
    serialize_tax_element(&element)
}

// ── II (Imposto de Importacao) ──────────────────────────────────────────────

/// Build II (import tax) XML string.
///
/// Generates the `<II>` element with four required fields:
/// vBC, vDespAdu, vII, and vIOF -- all formatted as cents to 2 decimal places.
pub fn build_ii_xml(data: &IiData) -> String {
    let element = TaxElement {
        outer_tag: None,
        outer_fields: vec![],
        variant_tag: "II".to_string(),
        fields: vec![
            TaxField::new("vBC", format_cents_or_zero(Some(data.v_bc.0), 2)),
            TaxField::new("vDespAdu", format_cents_or_zero(Some(data.v_desp_adu.0), 2)),
            TaxField::new("vII", format_cents_or_zero(Some(data.v_ii.0), 2)),
            TaxField::new("vIOF", format_cents_or_zero(Some(data.v_iof.0), 2)),
        ],
    };
    serialize_tax_element(&element)
}

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

    #[test]
    fn build_pis_xml_unknown_cst_fallback_to_nt() {
        // CST "88" is not in any of the known sets, should fall back to NT
        let data = PisData::new("88");
        let xml = build_pis_xml(&data);
        assert!(xml.contains("<PISNT>"));
        assert!(xml.contains("<CST>88</CST>"));
    }

    #[test]
    fn build_cofins_xml_unknown_cst_fallback_to_nt() {
        let data = CofinsData::new("88");
        let xml = build_cofins_xml(&data);
        assert!(xml.contains("<COFINSNT>"));
        assert!(xml.contains("<CST>88</CST>"));
    }
}