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
//! Export internal controls master data to CSV files.
//!
//! Exports control definitions, mappings, and SoD conflict pairs
//! as separate CSV files for use in BI/analytics systems.

use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};

use datasynth_core::error::SynthResult;
use datasynth_core::models::{
    ControlAccountMapping, ControlDocTypeMapping, ControlMappingRegistry, ControlProcessMapping,
    ControlThresholdMapping, InternalControl, SodConflictPair, SodRule,
};

/// Exporter for internal controls master data.
pub struct ControlExporter {
    output_dir: PathBuf,
}

impl ControlExporter {
    /// Create a new control exporter.
    pub fn new(output_dir: impl AsRef<Path>) -> Self {
        Self {
            output_dir: output_dir.as_ref().to_path_buf(),
        }
    }

    /// Export all control master data.
    ///
    /// Creates the following CSV files:
    /// - internal_controls.csv
    /// - control_account_mappings.csv
    /// - control_process_mappings.csv
    /// - control_threshold_mappings.csv
    /// - control_doctype_mappings.csv
    /// - sod_conflict_pairs.csv
    /// - sod_rules.csv
    /// - coso_control_mapping.csv
    pub fn export_all(
        &self,
        controls: &[InternalControl],
        registry: &ControlMappingRegistry,
        sod_conflicts: &[SodConflictPair],
        sod_rules: &[SodRule],
    ) -> SynthResult<ExportSummary> {
        std::fs::create_dir_all(&self.output_dir)?;

        let summary = ExportSummary {
            controls_count: self.export_controls(controls)?,
            account_mappings_count: self.export_account_mappings(&registry.account_mappings)?,
            process_mappings_count: self.export_process_mappings(&registry.process_mappings)?,
            threshold_mappings_count: self
                .export_threshold_mappings(&registry.threshold_mappings)?,
            doctype_mappings_count: self.export_doctype_mappings(&registry.doc_type_mappings)?,
            sod_conflicts_count: self.export_sod_conflicts(sod_conflicts)?,
            sod_rules_count: self.export_sod_rules(sod_rules)?,
            coso_mappings_count: self.export_coso_mapping(controls)?,
        };

        Ok(summary)
    }

    /// Export internal control definitions.
    pub fn export_controls(&self, controls: &[InternalControl]) -> SynthResult<usize> {
        let path = self.output_dir.join("internal_controls.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(
            writer,
            "control_id,control_name,control_type,objective,frequency,owner_role,\
             risk_level,is_key_control,sox_assertion,coso_component,coso_principles,control_scope,maturity_level"
        )?;

        for control in controls {
            // Format COSO principles as semicolon-separated list
            let principles: Vec<String> = control
                .coso_principles
                .iter()
                .map(|p| format!("{p}"))
                .collect();

            writeln!(
                writer,
                "{},{},{:?},{},{:?},{:?},{:?},{},{:?},{},{},{},{}",
                escape_csv(&control.control_id),
                escape_csv(&control.control_name),
                control.control_type,
                escape_csv(&control.objective),
                control.frequency,
                control.owner_role,
                control.risk_level,
                control.is_key_control,
                control.sox_assertion,
                escape_csv(&control.coso_component.to_string()),
                escape_csv(&principles.join(";")),
                escape_csv(&control.control_scope.to_string()),
                escape_csv(&control.maturity_level.to_string()),
            )?;
        }

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

    /// Export control-to-account mappings.
    pub fn export_account_mappings(
        &self,
        mappings: &[ControlAccountMapping],
    ) -> SynthResult<usize> {
        let path = self.output_dir.join("control_account_mappings.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(writer, "control_id,account_numbers,account_sub_types")?;

        for mapping in mappings {
            let account_numbers = mapping.account_numbers.join(";");
            let sub_types: Vec<String> = mapping
                .account_sub_types
                .iter()
                .map(|st| format!("{st:?}"))
                .collect();

            writeln!(
                writer,
                "{},{},{}",
                escape_csv(&mapping.control_id),
                escape_csv(&account_numbers),
                escape_csv(&sub_types.join(";"))
            )?;
        }

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

    /// Export control-to-process mappings.
    pub fn export_process_mappings(
        &self,
        mappings: &[ControlProcessMapping],
    ) -> SynthResult<usize> {
        let path = self.output_dir.join("control_process_mappings.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(writer, "control_id,business_processes")?;

        for mapping in mappings {
            let processes: Vec<String> = mapping
                .business_processes
                .iter()
                .map(|bp| format!("{bp:?}"))
                .collect();

            writeln!(
                writer,
                "{},{}",
                escape_csv(&mapping.control_id),
                escape_csv(&processes.join(";"))
            )?;
        }

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

    /// Export control-to-threshold mappings.
    pub fn export_threshold_mappings(
        &self,
        mappings: &[ControlThresholdMapping],
    ) -> SynthResult<usize> {
        let path = self.output_dir.join("control_threshold_mappings.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(
            writer,
            "control_id,amount_threshold,upper_threshold,comparison"
        )?;

        for mapping in mappings {
            writeln!(
                writer,
                "{},{},{},{:?}",
                escape_csv(&mapping.control_id),
                mapping.amount_threshold,
                mapping
                    .upper_threshold
                    .map(|t| t.to_string())
                    .unwrap_or_default(),
                mapping.comparison
            )?;
        }

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

    /// Export control-to-document type mappings.
    pub fn export_doctype_mappings(
        &self,
        mappings: &[ControlDocTypeMapping],
    ) -> SynthResult<usize> {
        let path = self.output_dir.join("control_doctype_mappings.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(writer, "control_id,document_types")?;

        for mapping in mappings {
            writeln!(
                writer,
                "{},{}",
                escape_csv(&mapping.control_id),
                escape_csv(&mapping.document_types.join(";"))
            )?;
        }

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

    /// Export SoD conflict pairs.
    pub fn export_sod_conflicts(&self, conflicts: &[SodConflictPair]) -> SynthResult<usize> {
        let path = self.output_dir.join("sod_conflict_pairs.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(writer, "conflict_type,role_a,role_b,description,severity")?;

        for conflict in conflicts {
            writeln!(
                writer,
                "{:?},{:?},{:?},{},{:?}",
                conflict.conflict_type,
                conflict.role_a,
                conflict.role_b,
                escape_csv(&conflict.description),
                conflict.severity
            )?;
        }

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

    /// Export SoD rules.
    pub fn export_sod_rules(&self, rules: &[SodRule]) -> SynthResult<usize> {
        let path = self.output_dir.join("sod_rules.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(
            writer,
            "rule_id,name,conflict_type,description,is_active,risk_level"
        )?;

        for rule in rules {
            writeln!(
                writer,
                "{},{},{:?},{},{},{:?}",
                escape_csv(&rule.rule_id),
                escape_csv(&rule.name),
                rule.conflict_type,
                escape_csv(&rule.description),
                rule.is_active,
                rule.risk_level
            )?;
        }

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

    /// Export COSO control mapping.
    ///
    /// Creates a detailed mapping of controls to COSO components and principles.
    /// Each row represents one principle mapped to a control.
    pub fn export_coso_mapping(&self, controls: &[InternalControl]) -> SynthResult<usize> {
        let path = self.output_dir.join("coso_control_mapping.csv");
        let file = File::create(&path)?;
        let mut writer = BufWriter::with_capacity(256 * 1024, file);

        // Header
        writeln!(
            writer,
            "control_id,coso_component,principle_number,principle_name,control_scope"
        )?;

        let mut row_count = 0;
        for control in controls {
            for principle in &control.coso_principles {
                writeln!(
                    writer,
                    "{},{},{},{},{}",
                    escape_csv(&control.control_id),
                    escape_csv(&control.coso_component.to_string()),
                    principle.principle_number(),
                    escape_csv(&principle.to_string()),
                    escape_csv(&control.control_scope.to_string()),
                )?;
                row_count += 1;
            }
        }

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

    /// Export standard control master data.
    ///
    /// This is a convenience method that exports standard controls,
    /// mappings, and SoD definitions.
    pub fn export_standard(&self) -> SynthResult<ExportSummary> {
        let controls = InternalControl::standard_controls();
        let registry = ControlMappingRegistry::standard();
        let sod_conflicts = SodConflictPair::standard_conflicts();
        let sod_rules = SodRule::standard_rules();

        self.export_all(&controls, &registry, &sod_conflicts, &sod_rules)
    }
}

/// Summary of exported control data.
#[derive(Debug, Default)]
pub struct ExportSummary {
    /// Number of control definitions exported.
    pub controls_count: usize,
    /// Number of account mappings exported.
    pub account_mappings_count: usize,
    /// Number of process mappings exported.
    pub process_mappings_count: usize,
    /// Number of threshold mappings exported.
    pub threshold_mappings_count: usize,
    /// Number of document type mappings exported.
    pub doctype_mappings_count: usize,
    /// Number of SoD conflict pairs exported.
    pub sod_conflicts_count: usize,
    /// Number of SoD rules exported.
    pub sod_rules_count: usize,
    /// Number of COSO control-principle mappings exported.
    pub coso_mappings_count: usize,
}

impl ExportSummary {
    /// Get the total number of records exported.
    pub fn total(&self) -> usize {
        self.controls_count
            + self.account_mappings_count
            + self.process_mappings_count
            + self.threshold_mappings_count
            + self.doctype_mappings_count
            + self.sod_conflicts_count
            + self.sod_rules_count
            + self.coso_mappings_count
    }
}

/// Escape a string for CSV output.
fn escape_csv(s: &str) -> String {
    if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

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

    #[test]
    fn test_export_standard() {
        let temp_dir = TempDir::new().unwrap();
        let exporter = ControlExporter::new(temp_dir.path());

        let summary = exporter.export_standard().unwrap();

        assert!(summary.controls_count > 0);
        assert!(summary.account_mappings_count > 0);
        assert!(summary.process_mappings_count > 0);
        assert!(summary.sod_conflicts_count > 0);
        assert!(summary.sod_rules_count > 0);
        assert!(summary.coso_mappings_count > 0);

        // Verify files were created
        assert!(temp_dir.path().join("internal_controls.csv").exists());
        assert!(temp_dir
            .path()
            .join("control_account_mappings.csv")
            .exists());
        assert!(temp_dir
            .path()
            .join("control_process_mappings.csv")
            .exists());
        assert!(temp_dir.path().join("sod_conflict_pairs.csv").exists());
        assert!(temp_dir.path().join("sod_rules.csv").exists());
        assert!(temp_dir.path().join("coso_control_mapping.csv").exists());
    }

    #[test]
    fn test_escape_csv() {
        assert_eq!(escape_csv("hello"), "hello");
        assert_eq!(escape_csv("hello,world"), "\"hello,world\"");
        assert_eq!(escape_csv("hello\"world"), "\"hello\"\"world\"");
        assert_eq!(escape_csv("hello\nworld"), "\"hello\nworld\"");
    }

    #[test]
    fn test_export_controls() {
        let temp_dir = TempDir::new().unwrap();
        let exporter = ControlExporter::new(temp_dir.path());

        let controls = InternalControl::standard_controls();
        let count = exporter.export_controls(&controls).unwrap();

        assert_eq!(count, controls.len());

        // Read the file and verify content
        let content =
            std::fs::read_to_string(temp_dir.path().join("internal_controls.csv")).unwrap();
        assert!(content.contains("control_id"));
        assert!(content.contains("C001")); // Cash control
    }

    #[test]
    fn test_export_sod_conflicts() {
        let temp_dir = TempDir::new().unwrap();
        let exporter = ControlExporter::new(temp_dir.path());

        let conflicts = SodConflictPair::standard_conflicts();
        let count = exporter.export_sod_conflicts(&conflicts).unwrap();

        assert_eq!(count, conflicts.len());

        let content =
            std::fs::read_to_string(temp_dir.path().join("sod_conflict_pairs.csv")).unwrap();
        assert!(content.contains("PreparerApprover"));
    }
}