datasynth-output 5.6.0

Output sinks for CSV, Parquet, JSON, and streaming formats
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
//! SAP S/4HANA format export.
//!
//! Exports data in SAP-compatible table formats:
//! - BKPF (Document Header)
//! - BSEG (Document Segments/Line Items)
//! - ACDOCA (Universal Journal)

use chrono::NaiveDate;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

use datasynth_core::error::SynthResult;
use datasynth_core::models::{AcdocaFactory, JournalEntry};

/// SAP table types for export.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SapTableType {
    /// Document header table
    Bkpf,
    /// Document segment (line item) table
    Bseg,
    /// Universal journal (S/4HANA)
    Acdoca,
    /// Vendor master
    Lfa1,
    /// Customer master
    Kna1,
    /// Material master
    Mara,
    /// Cost center master
    Csks,
    /// Profit center master
    Cepc,
}

impl SapTableType {
    /// Get the SAP table name.
    pub fn table_name(&self) -> &'static str {
        match self {
            SapTableType::Bkpf => "BKPF",
            SapTableType::Bseg => "BSEG",
            SapTableType::Acdoca => "ACDOCA",
            SapTableType::Lfa1 => "LFA1",
            SapTableType::Kna1 => "KNA1",
            SapTableType::Mara => "MARA",
            SapTableType::Csks => "CSKS",
            SapTableType::Cepc => "CEPC",
        }
    }
}

/// SAP BKPF (Document Header) record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BkpfEntry {
    /// Client
    pub mandt: String,
    /// Company Code
    pub bukrs: String,
    /// Document Number
    pub belnr: String,
    /// Fiscal Year
    pub gjahr: u16,
    /// Document Type
    pub blart: String,
    /// Document Date
    pub bldat: NaiveDate,
    /// Posting Date
    pub budat: NaiveDate,
    /// Fiscal Period
    pub monat: u8,
    /// Entry Date
    pub cpudt: NaiveDate,
    /// Entry Time
    pub cputm: String,
    /// User Name
    pub usnam: String,
    /// Transaction Code
    pub tcode: String,
    /// Reference Number
    pub xblnr: Option<String>,
    /// Document Header Text
    pub bktxt: Option<String>,
    /// Transaction Currency
    pub waers: String,
    /// Exchange Rate
    pub kursf: Decimal,
    /// Cross-Company Code
    pub bvorg: Option<String>,
    /// Reversal Document Number
    pub stblg: Option<String>,
    /// Reversal Reason
    pub stgrd: Option<String>,
}

impl Default for BkpfEntry {
    fn default() -> Self {
        Self {
            mandt: "100".to_string(),
            bukrs: String::new(),
            belnr: String::new(),
            gjahr: 0,
            blart: "SA".to_string(),
            bldat: NaiveDate::from_ymd_opt(2000, 1, 1).expect("valid default date"),
            budat: NaiveDate::from_ymd_opt(2000, 1, 1).expect("valid default date"),
            monat: 1,
            cpudt: NaiveDate::from_ymd_opt(2000, 1, 1).expect("valid default date"),
            cputm: "000000".to_string(),
            usnam: String::new(),
            tcode: "FB01".to_string(),
            xblnr: None,
            bktxt: None,
            waers: "USD".to_string(),
            kursf: Decimal::ONE,
            bvorg: None,
            stblg: None,
            stgrd: None,
        }
    }
}

/// SAP export dialect — controls delimiter, decimal separator, date
/// format, and text-encoding hints applied to every generated table.
///
/// - `Classic` — ASCII-CSV as expected by SAP BODS / Data Services
///   imports and by tools that read the legacy R/3 CSV dumps: comma
///   delimiter, `YYYYMMDD` dates, dot decimal, no BOM.
/// - `Hana` — semicolon delimiter, UTF-8 BOM, decimal comma,
///   `YYYY-MM-DD` dates, and CDS-ingestion-friendly quoting. Matches
///   what HANA `IMPORT FROM CSV FILE` expects with German-locale
///   regional settings (the default for most EU S/4HANA customers).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SapDialect {
    /// Legacy R/3 / BODS-compatible CSV. ASCII, comma, YYYYMMDD, dot decimal.
    #[default]
    Classic,
    /// S/4HANA CDS-ingestion dialect. UTF-8 BOM, semicolon, ISO dates, comma decimal.
    Hana,
}

impl SapDialect {
    /// Field delimiter for this dialect.
    pub fn delimiter(&self) -> char {
        match self {
            Self::Classic => ',',
            Self::Hana => ';',
        }
    }

    /// Decimal separator for monetary / quantity fields.
    pub fn decimal_separator(&self) -> char {
        match self {
            Self::Classic => '.',
            Self::Hana => ',',
        }
    }

    /// Leading BOM bytes to write at the start of each file (empty for Classic).
    pub fn bom(&self) -> &'static [u8] {
        match self {
            Self::Classic => &[],
            // UTF-8 BOM — required by HANA CSV imports when the file contains
            // German/Scandinavian characters and the client locale is non-UTF-8.
            Self::Hana => &[0xEF, 0xBB, 0xBF],
        }
    }

    /// Format a `NaiveDate` per this dialect.
    pub fn format_date(&self, date: NaiveDate) -> String {
        match self {
            Self::Classic => date.format("%Y%m%d").to_string(),
            Self::Hana => date.format("%Y-%m-%d").to_string(),
        }
    }

    /// Format a `Decimal` per this dialect's decimal convention.
    pub fn format_decimal(&self, value: &Decimal) -> String {
        match self {
            Self::Classic => value.to_string(),
            Self::Hana => value.to_string().replace('.', ","),
        }
    }
}

/// Configuration for SAP export.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SapExportConfig {
    /// SAP client number (MANDT column on every table).
    pub client: String,
    /// Ledger for ACDOCA (0L = leading, 1L/2L = non-leading parallel ledgers).
    pub ledger: String,
    /// Source system identifier — becomes AWSYS on ACDOCA rows so consumers
    /// can distinguish synthetic rows from production ones after merge.
    pub source_system: String,
    /// Local currency (RWCUR on ACDOCA, WAERS on BKPF/BSEG).
    pub local_currency: String,
    /// Group / consolidation currency — emits the RHCUR / HSL pair when set.
    pub group_currency: Option<String>,
    /// Tables to export. Unknown types are silently skipped by the writer
    /// so future SAP table additions can land behind a schema-only flag
    /// without breaking existing configs.
    pub tables: Vec<SapTableType>,
    /// Include the ZSIM_* extension columns on ACDOCA rows so downstream
    /// ML consumers can read fraud / SOX / SoD labels directly from the
    /// SAP table rather than joining back to the label files.
    pub include_extension_fields: bool,
    /// Dialect — controls delimiter / decimal / date format / BOM.
    /// Prefer the dedicated `dialect` field; `use_sap_date_format` is kept
    /// for backward compatibility but is overridden by `dialect` when set
    /// to anything other than `Classic`.
    pub dialect: SapDialect,
    /// DEPRECATED as of v4.3.0 — set via `dialect` instead. Kept for
    /// backward compatibility: when true (the default), Classic dialect
    /// emits YYYYMMDD dates. When false, Classic dialect emits ISO
    /// `YYYY-MM-DD` dates. Has no effect on Hana dialect (always ISO).
    pub use_sap_date_format: bool,
}

impl Default for SapExportConfig {
    fn default() -> Self {
        Self {
            client: "100".to_string(),
            ledger: "0L".to_string(),
            source_system: "SYNTH".to_string(),
            local_currency: "USD".to_string(),
            group_currency: None,
            tables: vec![SapTableType::Bkpf, SapTableType::Bseg, SapTableType::Acdoca],
            include_extension_fields: true,
            dialect: SapDialect::Classic,
            use_sap_date_format: true,
        }
    }
}

impl SapExportConfig {
    /// Render a date using the configured dialect, honouring the legacy
    /// `use_sap_date_format` flag for Classic dialect only.
    pub fn format_date(&self, date: NaiveDate) -> String {
        match self.dialect {
            SapDialect::Classic if self.use_sap_date_format => date.format("%Y%m%d").to_string(),
            SapDialect::Classic => date.format("%Y-%m-%d").to_string(),
            SapDialect::Hana => date.format("%Y-%m-%d").to_string(),
        }
    }

    /// Render a decimal using the configured dialect.
    pub fn format_decimal(&self, value: &Decimal) -> String {
        self.dialect.format_decimal(value)
    }

    /// Delimiter character for CSV writers.
    pub fn delimiter(&self) -> char {
        self.dialect.delimiter()
    }
}

/// SAP format exporter.
pub struct SapExporter {
    config: SapExportConfig,
    acdoca_factory: AcdocaFactory,
    document_counter: HashMap<String, u64>, // Company code -> counter
}

impl SapExporter {
    /// Create a new SAP exporter.
    pub fn new(config: SapExportConfig) -> Self {
        let mut acdoca_factory = AcdocaFactory::new(&config.ledger, &config.source_system)
            .with_local_currency(&config.local_currency)
            .with_client(&config.client);

        if let Some(ref group_currency) = config.group_currency {
            acdoca_factory = acdoca_factory.with_group_currency(group_currency);
        }

        Self {
            config,
            acdoca_factory,
            document_counter: HashMap::new(),
        }
    }

    /// Generate next document number for a company code.
    fn next_document_number(&mut self, company_code: &str) -> String {
        let counter = self
            .document_counter
            .entry(company_code.to_string())
            .or_insert(0);
        *counter += 1;
        format!("{:010}", *counter)
    }

    /// Convert JournalEntry to BKPF record.
    pub fn to_bkpf(&self, je: &JournalEntry, document_number: &str) -> BkpfEntry {
        BkpfEntry {
            mandt: self.config.client.clone(),
            bukrs: je.header.company_code.clone(),
            belnr: document_number.to_string(),
            gjahr: je.header.fiscal_year,
            blart: je.header.document_type.clone(),
            bldat: je.header.document_date,
            budat: je.header.posting_date,
            monat: je.header.fiscal_period,
            cpudt: je.header.created_at.date_naive(),
            cputm: je.header.created_at.format("%H%M%S").to_string(),
            usnam: je.header.created_by.clone(),
            tcode: self.get_transaction_code(je),
            xblnr: je.header.reference.clone(),
            bktxt: je.header.header_text.clone(),
            waers: je.header.currency.clone(),
            kursf: je.header.exchange_rate,
            bvorg: None,
            stblg: None,
            stgrd: None,
        }
    }

    /// Get appropriate transaction code based on document type.
    fn get_transaction_code(&self, je: &JournalEntry) -> String {
        match je.header.document_type.as_str() {
            "SA" => "FB01".to_string(),  // GL posting
            "RE" => "MIRO".to_string(),  // Vendor invoice
            "RV" => "VF01".to_string(),  // Customer invoice
            "KZ" => "F110".to_string(),  // Vendor payment
            "DZ" => "F28".to_string(),   // Customer payment
            "AB" => "ABZON".to_string(), // Depreciation
            "AA" => "ABSO1".to_string(), // Asset acquisition
            _ => "FB01".to_string(),
        }
    }

    /// Export journal entries to SAP format files.
    pub fn export_to_files(
        &mut self,
        entries: &[JournalEntry],
        output_dir: &Path,
    ) -> SynthResult<HashMap<SapTableType, String>> {
        let mut output_files = HashMap::new();

        // Create output directory if needed
        std::fs::create_dir_all(output_dir)?;

        // Clone tables to avoid borrow checker issues
        let tables = self.config.tables.clone();
        for table_type in tables {
            let filename = format!("{}.csv", table_type.table_name().to_lowercase());
            let filepath = output_dir.join(&filename);

            match table_type {
                SapTableType::Bkpf => self.export_bkpf(entries, &filepath)?,
                SapTableType::Bseg => self.export_bseg(entries, &filepath)?,
                SapTableType::Acdoca => self.export_acdoca(entries, &filepath)?,
                _ => {
                    // Master data tables are handled separately
                    continue;
                }
            }

            output_files.insert(table_type, filepath.to_string_lossy().to_string());
        }

        Ok(output_files)
    }

    /// Create the configured file, write the dialect-specific BOM (if any),
    /// and return the buffered writer.
    fn open_sap_file(&self, filepath: &Path) -> SynthResult<BufWriter<File>> {
        let file = File::create(filepath)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);
        let bom = self.config.dialect.bom();
        if !bom.is_empty() {
            writer.write_all(bom)?;
        }
        Ok(writer)
    }

    /// Export BKPF (document headers).
    fn export_bkpf(&mut self, entries: &[JournalEntry], filepath: &Path) -> SynthResult<()> {
        let mut writer = self.open_sap_file(filepath)?;
        let delim = self.config.delimiter();

        // Header row.
        write_header(
            &mut writer,
            delim,
            &[
                "MANDT", "BUKRS", "BELNR", "GJAHR", "BLART", "BLDAT", "BUDAT", "MONAT", "CPUDT",
                "CPUTM", "USNAM", "TCODE", "XBLNR", "BKTXT", "WAERS", "KURSF",
            ],
        )?;

        for je in entries {
            let doc_num = self.next_document_number(&je.header.company_code);
            let bkpf = self.to_bkpf(je, &doc_num);

            let fields: Vec<String> = vec![
                bkpf.mandt,
                bkpf.bukrs,
                bkpf.belnr,
                bkpf.gjahr.to_string(),
                bkpf.blart,
                self.config.format_date(bkpf.bldat),
                self.config.format_date(bkpf.budat),
                bkpf.monat.to_string(),
                self.config.format_date(bkpf.cpudt),
                bkpf.cputm,
                bkpf.usnam,
                bkpf.tcode,
                bkpf.xblnr.unwrap_or_default(),
                escape_csv_field(bkpf.bktxt.as_deref().unwrap_or("")),
                bkpf.waers,
                self.config.format_decimal(&bkpf.kursf),
            ];
            write_row(&mut writer, delim, &fields)?;
        }

        writer.flush()?;
        Ok(())
    }

    /// Export BSEG (document segments).
    fn export_bseg(&mut self, entries: &[JournalEntry], filepath: &Path) -> SynthResult<()> {
        let mut writer = self.open_sap_file(filepath)?;
        let delim = self.config.delimiter();

        write_header(
            &mut writer,
            delim,
            &[
                "MANDT", "BUKRS", "BELNR", "GJAHR", "BUZEI", "BSCHL", "HKONT", "WRBTR", "SHKZG",
                "DMBTR", "WAERS", "KOSTL", "PRCTR", "SGTXT", "ZUONR", "MWSKZ",
            ],
        )?;

        // Reset document counter for BSEG to match BKPF
        self.document_counter.clear();

        for je in entries {
            let doc_num = self.next_document_number(&je.header.company_code);
            let bseg_entries = self.acdoca_factory.to_bseg_entries(je, &doc_num);

            for bseg in bseg_entries {
                let fields: Vec<String> = vec![
                    bseg.mandt,
                    bseg.bukrs,
                    bseg.belnr,
                    bseg.gjahr.to_string(),
                    bseg.buzei.to_string(),
                    bseg.bschl,
                    bseg.hkont,
                    self.config.format_decimal(&bseg.wrbtr),
                    bseg.shkzg,
                    self.config.format_decimal(&bseg.dmbtr),
                    bseg.waers,
                    bseg.kostl.unwrap_or_default(),
                    bseg.prctr.unwrap_or_default(),
                    escape_csv_field(bseg.sgtxt.as_deref().unwrap_or("")),
                    bseg.zuonr.unwrap_or_default(),
                    bseg.mwskz.unwrap_or_default(),
                ];
                write_row(&mut writer, delim, &fields)?;
            }
        }

        writer.flush()?;
        Ok(())
    }

    /// Export ACDOCA (Universal Journal).
    fn export_acdoca(&mut self, entries: &[JournalEntry], filepath: &Path) -> SynthResult<()> {
        let mut writer = self.open_sap_file(filepath)?;
        let delim = self.config.delimiter();

        // Header row (extension columns appended when configured).
        let mut header_cols: Vec<&'static str> = vec![
            "RLDNR", "RBUKRS", "GJAHR", "BELNR", "DOCLN", "BLART", "BUDAT", "BLDAT", "CPUDT",
            "CPUTM", "USNAM", "POPER", "RACCT", "RCNTR", "PRCTR", "WSL", "RWCUR", "HSL", "RHCUR",
            "DRCRK", "BSCHL", "SGTXT", "ZUONR", "AWSYS", "AWTYP", "AWKEY",
        ];
        if self.config.include_extension_fields {
            header_cols.extend_from_slice(&[
                "ZSIM_BATCH_ID",
                "ZSIM_IS_FRAUD",
                "ZSIM_FRAUD_TYPE",
                "ZSIM_BUSINESS_PROCESS",
                "ZSIM_CONTROL_IDS",
                "ZSIM_SOX_RELEVANT",
                "ZSIM_SOD_VIOLATION",
            ]);
        }
        write_header(&mut writer, delim, &header_cols)?;

        // Reset document counter for ACDOCA
        self.document_counter.clear();

        for je in entries {
            let doc_num = self.next_document_number(&je.header.company_code);
            let acdoca_entries = self.acdoca_factory.from_journal_entry(je, &doc_num);

            for entry in acdoca_entries {
                let mut fields: Vec<String> = vec![
                    entry.rldnr,
                    entry.rbukrs,
                    entry.gjahr.to_string(),
                    entry.belnr,
                    entry.docln.to_string(),
                    entry.blart,
                    self.config.format_date(entry.budat),
                    self.config.format_date(entry.bldat),
                    self.config.format_date(entry.cpudt),
                    entry.cputm,
                    entry.usnam,
                    entry.poper.to_string(),
                    entry.racct,
                    entry.rcntr.unwrap_or_default(),
                    entry.prctr.unwrap_or_default(),
                    self.config.format_decimal(&entry.wsl),
                    entry.rwcur,
                    self.config.format_decimal(&entry.hsl),
                    entry.rhcur,
                    entry.drcrk,
                    entry.bschl,
                    escape_csv_field(entry.sgtxt.as_deref().unwrap_or("")),
                    entry.zuonr.unwrap_or_default(),
                    entry.awsys,
                    entry.awtyp,
                    entry.awkey,
                ];
                if self.config.include_extension_fields {
                    fields.push(
                        entry
                            .sim_batch_id
                            .map(|u| u.to_string())
                            .unwrap_or_default(),
                    );
                    fields.push(entry.sim_is_fraud.to_string());
                    fields.push(entry.sim_fraud_type.unwrap_or_default());
                    fields.push(entry.sim_business_process.unwrap_or_default());
                    fields.push(entry.sim_control_ids.unwrap_or_default());
                    fields.push(entry.sim_sox_relevant.to_string());
                    fields.push(entry.sim_sod_violation.to_string());
                }
                write_row(&mut writer, delim, &fields)?;
            }
        }

        writer.flush()?;
        Ok(())
    }

    /// Export vendor master data (LFA1 format).
    pub fn export_vendor_master<V: SapVendorExportable>(
        &self,
        vendors: &[V],
        filepath: &Path,
    ) -> SynthResult<()> {
        let mut writer = self.open_sap_file(filepath)?;
        let delim = self.config.delimiter();

        write_header(
            &mut writer,
            delim,
            &[
                "MANDT", "LIFNR", "LAND1", "NAME1", "NAME2", "ORT01", "PSTLZ", "STRAS", "REGIO",
                "SPRAS", "STCD1", "KTOKK",
            ],
        )?;

        for vendor in vendors {
            let v = vendor.to_sap_vendor(&self.config.client);
            let fields: Vec<String> = vec![
                v.mandt,
                v.lifnr,
                v.land1,
                escape_csv_field(&v.name1),
                escape_csv_field(&v.name2.unwrap_or_default()),
                escape_csv_field(&v.ort01.unwrap_or_default()),
                v.pstlz.unwrap_or_default(),
                escape_csv_field(&v.stras.unwrap_or_default()),
                v.regio.unwrap_or_default(),
                v.spras,
                v.stcd1.unwrap_or_default(),
                v.ktokk,
            ];
            write_row(&mut writer, delim, &fields)?;
        }

        writer.flush()?;
        Ok(())
    }

    /// Export customer master data (KNA1 format).
    pub fn export_customer_master<C: SapCustomerExportable>(
        &self,
        customers: &[C],
        filepath: &Path,
    ) -> SynthResult<()> {
        let mut writer = self.open_sap_file(filepath)?;
        let delim = self.config.delimiter();

        write_header(
            &mut writer,
            delim,
            &[
                "MANDT", "KUNNR", "LAND1", "NAME1", "NAME2", "ORT01", "PSTLZ", "STRAS", "REGIO",
                "SPRAS", "STCD1", "KTOKD",
            ],
        )?;

        for customer in customers {
            let c = customer.to_sap_customer(&self.config.client);
            let fields: Vec<String> = vec![
                c.mandt,
                c.kunnr,
                c.land1,
                escape_csv_field(&c.name1),
                escape_csv_field(&c.name2.unwrap_or_default()),
                escape_csv_field(&c.ort01.unwrap_or_default()),
                c.pstlz.unwrap_or_default(),
                escape_csv_field(&c.stras.unwrap_or_default()),
                c.regio.unwrap_or_default(),
                c.spras,
                c.stcd1.unwrap_or_default(),
                c.ktokd,
            ];
            write_row(&mut writer, delim, &fields)?;
        }

        writer.flush()?;
        Ok(())
    }
}

/// Write a CSV header row (alias of `write_row` — the function expects
/// identifier strings and does not apply field escaping, since SAP DDIC
/// column names are always plain ASCII).
fn write_row_plain<W: Write>(writer: &mut W, delim: char, fields: &[&str]) -> std::io::Result<()> {
    for (i, f) in fields.iter().enumerate() {
        if i > 0 {
            write!(writer, "{delim}")?;
        }
        write!(writer, "{f}")?;
    }
    writeln!(writer)
}

fn write_header<W: Write>(writer: &mut W, delim: char, cols: &[&str]) -> std::io::Result<()> {
    write_row_plain(writer, delim, cols)
}

fn write_row<W: Write>(writer: &mut W, delim: char, fields: &[String]) -> std::io::Result<()> {
    for (i, f) in fields.iter().enumerate() {
        if i > 0 {
            write!(writer, "{delim}")?;
        }
        write!(writer, "{f}")?;
    }
    writeln!(writer)
}

/// SAP vendor record (LFA1).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SapVendor {
    pub mandt: String,
    pub lifnr: String,
    pub land1: String,
    pub name1: String,
    pub name2: Option<String>,
    pub ort01: Option<String>,
    pub pstlz: Option<String>,
    pub stras: Option<String>,
    pub regio: Option<String>,
    pub spras: String,
    pub stcd1: Option<String>,
    pub ktokk: String,
}

/// SAP customer record (KNA1).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SapCustomer {
    pub mandt: String,
    pub kunnr: String,
    pub land1: String,
    pub name1: String,
    pub name2: Option<String>,
    pub ort01: Option<String>,
    pub pstlz: Option<String>,
    pub stras: Option<String>,
    pub regio: Option<String>,
    pub spras: String,
    pub stcd1: Option<String>,
    pub ktokd: String,
}

/// Trait for exporting entities as SAP vendors.
pub trait SapVendorExportable {
    fn to_sap_vendor(&self, client: &str) -> SapVendor;
}

/// Trait for exporting entities as SAP customers.
pub trait SapCustomerExportable {
    fn to_sap_customer(&self, client: &str) -> SapCustomer;
}

/// Escape a field for CSV output.
///
/// Delimiter-agnostic: quotes the field if it contains a comma, semicolon,
/// double quote, or newline. Classic dialect uses commas and Hana dialect
/// uses semicolons, so escaping on both means a field like
/// `"Müller, GmbH; München"` emerges quoted in either dialect.
fn escape_csv_field(field: &str) -> String {
    if field.contains(',') || field.contains(';') || field.contains('"') || field.contains('\n') {
        format!("\"{}\"", field.replace('"', "\"\""))
    } else {
        field.to_string()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::test_helpers::create_test_je;
    use tempfile::TempDir;

    #[test]
    fn test_sap_exporter_creates_files() {
        let temp_dir = TempDir::new().unwrap();
        let config = SapExportConfig::default();
        let mut exporter = SapExporter::new(config);

        let entries = vec![create_test_je()];
        let result = exporter.export_to_files(&entries, temp_dir.path());

        assert!(result.is_ok());
        let files = result.unwrap();
        assert!(files.contains_key(&SapTableType::Bkpf));
        assert!(files.contains_key(&SapTableType::Bseg));
        assert!(files.contains_key(&SapTableType::Acdoca));

        // Verify files exist
        assert!(temp_dir.path().join("bkpf.csv").exists());
        assert!(temp_dir.path().join("bseg.csv").exists());
        assert!(temp_dir.path().join("acdoca.csv").exists());
    }

    #[test]
    fn test_bkpf_conversion() {
        let config = SapExportConfig::default();
        let exporter = SapExporter::new(config);
        let je = create_test_je();

        let bkpf = exporter.to_bkpf(&je, "0000000001");

        assert_eq!(bkpf.bukrs, "1000");
        assert_eq!(bkpf.belnr, "0000000001");
        assert_eq!(bkpf.gjahr, je.header.fiscal_year);
    }

    #[test]
    fn test_document_number_generation() {
        let config = SapExportConfig::default();
        let mut exporter = SapExporter::new(config);

        let num1 = exporter.next_document_number("1000");
        let num2 = exporter.next_document_number("1000");
        let num3 = exporter.next_document_number("2000");

        assert_eq!(num1, "0000000001");
        assert_eq!(num2, "0000000002");
        assert_eq!(num3, "0000000001"); // Different company code
    }

    // ========================================================================
    // v4.3.0a — Dialect smoke tests
    // ========================================================================

    #[test]
    fn classic_dialect_uses_comma_no_bom_yyyymmdd_dot_decimal() {
        let temp_dir = TempDir::new().unwrap();
        let config = SapExportConfig {
            dialect: SapDialect::Classic,
            use_sap_date_format: true,
            ..SapExportConfig::default()
        };
        let mut exporter = SapExporter::new(config);
        exporter
            .export_to_files(&[create_test_je()], temp_dir.path())
            .unwrap();
        let bkpf = std::fs::read(temp_dir.path().join("bkpf.csv")).unwrap();
        // No UTF-8 BOM at file start.
        assert_ne!(&bkpf[..3], [0xEF, 0xBB, 0xBF]);
        // Header uses comma delimiter.
        let head = std::str::from_utf8(&bkpf).unwrap().lines().next().unwrap();
        assert!(head.contains(','), "Classic header must use comma: {head}");
        assert!(!head.contains(';'), "Classic header must not use semicolon");
        // Body: YYYYMMDD date (8-digit, no dash) somewhere in the second line.
        let body = std::str::from_utf8(&bkpf).unwrap().lines().nth(1).unwrap();
        let has_yyyymmdd = body
            .split(',')
            .any(|f| f.len() == 8 && f.chars().all(|c| c.is_ascii_digit()));
        assert!(
            has_yyyymmdd,
            "Classic body must contain YYYYMMDD date: {body}"
        );
    }

    #[test]
    fn hana_dialect_uses_semicolon_utf8_bom_iso_date_comma_decimal() {
        let temp_dir = TempDir::new().unwrap();
        let config = SapExportConfig {
            dialect: SapDialect::Hana,
            ..SapExportConfig::default()
        };
        let mut exporter = SapExporter::new(config);
        exporter
            .export_to_files(&[create_test_je()], temp_dir.path())
            .unwrap();

        let bkpf = std::fs::read(temp_dir.path().join("bkpf.csv")).unwrap();
        // UTF-8 BOM at file start.
        assert_eq!(
            &bkpf[..3],
            [0xEF, 0xBB, 0xBF],
            "Hana dialect must prefix files with a UTF-8 BOM"
        );
        // Header uses semicolon delimiter (after stripping BOM).
        let text = std::str::from_utf8(&bkpf[3..]).unwrap();
        let head = text.lines().next().unwrap();
        assert!(head.contains(';'), "Hana header must use semicolon: {head}");
        assert!(!head.contains(','), "Hana header must not use comma");
        // Body: ISO-dashed date appears somewhere in the second line.
        let body = text.lines().nth(1).unwrap();
        assert!(
            body.split(';')
                .any(|f| { f.len() == 10 && f.chars().filter(|c| *c == '-').count() == 2 }),
            "Hana body must contain a YYYY-MM-DD date: {body}"
        );
    }

    #[test]
    fn dialect_format_decimal_uses_comma_for_hana_dot_for_classic() {
        let d = Decimal::new(12345, 2); // 123.45
        assert_eq!(SapDialect::Classic.format_decimal(&d), "123.45");
        assert_eq!(SapDialect::Hana.format_decimal(&d), "123,45");
    }

    #[test]
    fn escape_csv_field_quotes_fields_containing_either_delimiter() {
        // Classic (comma) consumers + Hana (semicolon) consumers both
        // break on their delimiter inside a field, so we always quote
        // when either is present.
        assert_eq!(escape_csv_field("Müller, GmbH"), "\"Müller, GmbH\"");
        assert_eq!(escape_csv_field("Müller; GmbH"), "\"Müller; GmbH\"");
        assert_eq!(escape_csv_field("Straight"), "Straight");
    }
}