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
use chrono::{NaiveDate, NaiveTime};
use log::{debug, info};
use serde::{Deserialize, Serialize, Serializer};
use thousands::Separable;

const FORMAT: &'static str = "%H:%M";

pub fn hh_mm_format<S>(time: &Option<NaiveTime>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    match time {
        Some(t) => {
            let s = format!("{}", t.format(FORMAT));
            serializer.serialize_str(&s)
        }
        None => serializer.serialize_str(""),
    }
}

pub trait Currency {
    fn pretty_dollars_cents(&self) -> String;
}

impl Currency for u32 {
    fn pretty_dollars_cents(&self) -> String {
        return format!("{:.2}", *self as f32 / 100.0).separate_with_commas();
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NachaFile {
    pub file_header: FileHeader,
    pub batches: Vec<Batch>,
    pub file_control: FileControl,
    #[serde(skip_serializing)]
    #[allow(dead_code)]
    raw: String,
}

impl NachaFile {
    pub fn new(content: String) -> NachaFile {
        let _content = content.clone();
        let mut file = NachaFile {
            file_header: FileHeader::new(),
            batches: Vec::new(),
            file_control: FileControl::new(),
            raw: _content,
        };

        for linestr in content.lines() {
            let line = linestr.to_string();
            let record_type = &line[0..1];
            match record_type {
                "1" => {
                    debug!("file header found");
                    file.file_header.parse(line);
                }
                "5" => {
                    debug!("batch header found");
                    let batch = Batch {
                        batch_header: BatchHeader::parse(line),
                        detail_entries: Vec::new(),
                        batch_control: BatchControl::new(),
                    };
                    file.batches.push(batch);
                }
                "6" => {
                    debug!("detail entry found");
                    file.last_batch().new_entry(line);
                }
                "7" => {
                    debug!("addendum entry found");
                    file.last_batch().last_entry().add_addenda(line);
                }
                "8" => {
                    debug!("batch control found");
                    file.last_batch().batch_control.parse(line);
                }
                "9" => {
                    debug!("file control found");
                    file.file_control.parse(line);
                    break;
                }
                _ => debug!("unknown record found"),
            }
        }
        info!("Done parsing file");
        return file;
    }

    pub fn last_batch(&mut self) -> &mut Batch {
        return self.batches.last_mut().unwrap();
    }
    pub fn as_json(&self) -> String {
        serde_json::to_string_pretty(self).unwrap()
    }
    pub fn as_yaml(&self) -> String {
        serde_yaml::to_string(self).unwrap()
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FileHeader {
    pub record_type_code: String,
    pub priority_code: String,
    pub immediate_destination: String,
    pub immediate_origin: String,
    pub file_creation_date: Option<NaiveDate>,
    #[serde(serialize_with = "hh_mm_format")]
    pub file_creation_time: Option<NaiveTime>,
    pub file_id_modifier: String,
    pub record_size: String,
    pub blocking_factor: String,
    pub format_code: String,
    pub immediate_destination_name: String,
    pub immediate_origin_name: String,
    pub reference_code: String,
}

impl FileHeader {
    pub fn new() -> FileHeader {
        FileHeader {
            record_type_code: "".to_string(),
            priority_code: "".to_string(),
            immediate_destination: "".to_string(),
            immediate_origin: "".to_string(),
            file_creation_date: None,
            file_creation_time: None,
            file_id_modifier: "".to_string(),
            record_size: "".to_string(),
            blocking_factor: "".to_string(),
            format_code: "".to_string(),
            immediate_destination_name: "".to_string(),
            immediate_origin_name: "".to_string(),
            reference_code: "".to_string(),
        }
    }
    pub fn parse(&mut self, line: String) {
        let maybe_date = NaiveDate::parse_from_str(line[23..29].trim(), "%y%m%d");
        let date = match maybe_date {
            Ok(d) => Some(d),
            Err(_) => None,
        };
        let maybe_time = NaiveTime::parse_from_str(line[29..33].trim(), "%H%M");
        let time = match maybe_time {
            Ok(t) => Some(t),
            Err(_) => None,
        };

        self.record_type_code = line[0..1].trim().to_string();
        self.priority_code = line[1..3].trim().to_string();
        self.immediate_destination = line[3..13].trim().to_string();
        self.immediate_origin = line[13..23].trim().to_string();
        self.file_creation_date = date;
        self.file_creation_time = time;
        self.file_id_modifier = line[33..34].trim().to_string();
        self.record_size = line[34..37].trim().to_string();
        self.blocking_factor = line[37..39].trim().to_string();
        self.format_code = line[39..40].trim().to_string();
        self.immediate_destination_name = line[40..63].trim().to_string();
        self.immediate_origin_name = line[63..86].trim().to_string();
        self.reference_code = line[86..94].trim().to_string();
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Batch {
    pub batch_header: BatchHeader,
    pub detail_entries: Vec<DetailEntry>,
    batch_control: BatchControl,
}

impl Batch {
    pub fn new_entry(&mut self, line: String) {
        let detail = DetailEntry::parse(line);
        self.detail_entries.push(detail);
    }

    pub fn last_entry(&mut self) -> &mut DetailEntry {
        return self.detail_entries.last_mut().unwrap();
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BatchHeader {
    pub record_type_code: String,
    pub service_class_code: String,
    pub company_name: String,
    pub company_discretionary_data: String,
    pub company_id: String,
    pub standard_entry_class_code: String,
    pub company_entry_description: String,
    pub company_descriptive_date: String,
    pub effective_entry_date: Option<NaiveDate>,
    pub settlement_date: Option<NaiveDate>,
    pub originator_status_code: String,
    pub originating_dfi_id: String,
    pub batch_number: String,
}

impl BatchHeader {
    pub fn parse(line: String) -> BatchHeader {
        let maybe_effective_date = NaiveDate::parse_from_str(line[69..75].trim(), "%y%m%d");
        let edate = match maybe_effective_date {
            Ok(d) => Some(d),
            Err(_) => None,
        };
        let maybe_settlement_date = NaiveDate::parse_from_str(line[75..78].trim(), "%y%m%d");
        let sdate = match maybe_settlement_date {
            Ok(d) => Some(d),
            Err(_) => None,
        };

        let bh = BatchHeader {
            record_type_code: line[0..1].trim().to_string(),
            service_class_code: line[1..4].trim().to_string(),
            company_name: line[4..20].trim().to_string(),
            company_discretionary_data: line[20..40].trim().to_string(),
            company_id: line[40..50].trim().to_string(),
            standard_entry_class_code: line[50..53].trim().to_string(),
            company_entry_description: line[53..63].trim().to_string(),
            company_descriptive_date: line[63..69].trim().to_string(),
            effective_entry_date: edate,
            settlement_date: sdate,
            originator_status_code: line[78..79].trim().to_string(),
            originating_dfi_id: line[79..87].trim().to_string(),
            batch_number: line[87..94].trim().to_string(),
        };
        return bh;
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BatchControl {
    pub record_type_code: String,
    pub service_class_code: String,
    pub entry_addenda_count: String,
    pub entry_hash: String,
    pub total_debit: u32,
    pub total_credit: u32,
    pub company_id: String,
    pub message_authentication_code: String,
    pub reserved: String,
    pub originating_dfi_id: String,
    pub batch_number: String,
}

impl BatchControl {
    pub fn new() -> BatchControl {
        BatchControl {
            record_type_code: "".to_string(),
            service_class_code: "".to_string(),
            entry_addenda_count: "".to_string(),
            entry_hash: "".to_string(),
            total_debit: 0,
            total_credit: 0,
            company_id: "".to_string(),
            message_authentication_code: "".to_string(),
            reserved: "".to_string(),
            originating_dfi_id: "".to_string(),
            batch_number: "".to_string(),
        }
    }
    pub fn parse(&mut self, line: String) {
        self.record_type_code = line[0..1].trim().to_string();
        self.service_class_code = line[1..4].trim().to_string();
        self.entry_addenda_count = line[4..10].trim().to_string();
        self.entry_hash = line[10..20].trim().to_string();
        self.total_debit = line[20..32].trim().parse().unwrap();
        self.total_credit = line[32..43].trim().parse().unwrap();
        self.company_id = line[43..54].trim().to_string();
        self.message_authentication_code = line[54..73].trim().to_string();
        self.reserved = line[73..79].trim().to_string();
        self.originating_dfi_id = line[79..87].trim().to_string();
        self.batch_number = line[87..94].trim().to_string();
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DetailEntry {
    pub record_type_code: String,
    pub transaction_code: String,
    pub receiving_dfi_id: String,
    pub check_digit: String,
    pub dfi_account_number: String,
    pub amount: u32,
    pub individual_id_number: String,
    pub individual_name: String,
    pub discretionary_data: String,
    pub addenda_record_indicator: String,
    pub trace_number: String,
    pub addenda: Vec<Addendum>,
}

impl DetailEntry {
    pub fn parse(line: String) -> DetailEntry {
        let entry = DetailEntry {
            record_type_code: line[0..1].trim().to_string(),
            transaction_code: line[1..3].trim().to_string(),
            receiving_dfi_id: line[3..11].trim().to_string(),
            check_digit: line[11..12].trim().to_string(),
            dfi_account_number: line[12..29].trim().to_string(),
            amount: line[29..39].trim().parse().unwrap(),
            individual_id_number: line[39..54].trim().to_string(),
            individual_name: line[54..76].trim().to_string(),
            discretionary_data: line[76..78].trim().to_string(),
            addenda_record_indicator: line[78..79].trim().to_string(),
            trace_number: line[79..94].trim().to_string(),
            addenda: Vec::new(),
        };
        return entry;
    }

    pub fn add_addenda(&mut self, line: String) {
        let new_addendum = Addendum::parse(line);
        self.addenda.push(new_addendum);
    }

    pub fn has_addenda(&self) -> bool {
        self.addenda.len() > 0
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Addendum {
    pub record_type_code: String,
    pub addenda_type_code: String,
    pub payment_related_info: String,
    pub addenda_sequence_number: String,
    pub entry_detail_sequence_number: String,
}

impl Addendum {
    pub fn parse(line: String) -> Addendum {
        let a = Addendum {
            record_type_code: line[0..1].trim().to_string(),
            addenda_type_code: line[1..3].trim().to_string(),
            payment_related_info: line[3..83].trim().to_string(),
            addenda_sequence_number: line[83..87].trim().to_string(),
            entry_detail_sequence_number: line[87..94].trim().to_string(),
        };
        return a;
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FileControl {
    pub record_type_code: String,
    pub batch_count: u32,
    pub block_count: u32,
    pub entry_and_addenda_count: u32,
    pub entry_hash: String,
    pub total_debit: u32,
    pub total_credit: u32,
    pub reserved: String,
}

impl FileControl {
    pub fn new() -> FileControl {
        FileControl {
            record_type_code: "".to_string(),
            batch_count: 0,
            block_count: 0,
            entry_and_addenda_count: 0,
            entry_hash: "".to_string(),
            total_debit: 0,
            total_credit: 0,
            reserved: "".to_string(),
        }
    }
    pub fn parse(&mut self, line: String) {
        self.record_type_code = line[0..1].trim().to_string();
        self.batch_count = line[1..7].trim().parse().unwrap();
        self.block_count = line[7..13].trim().parse().unwrap();
        self.entry_and_addenda_count = line[13..21].trim().parse().unwrap();
        self.entry_hash = line[21..31].trim().to_string();
        self.total_debit = line[31..43].trim().parse().unwrap();
        self.total_credit = line[43..55].trim().parse().unwrap();
        self.reserved = line[55..94].trim().to_string();
    }
}