tackler_core/kernel/
settings.rs

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
/*
 * Copyright 2023-2024 E257.FI
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
use crate::config;
use crate::config::{AccountSelectors, Config, Export, Kernel, Report, ReportType, TimezoneType};
use crate::kernel::hash::Hash;
use crate::model::TxnAccount;
use crate::model::{AccountTreeNode, Commodity};
use crate::parser::GitInputSelector;
use std::collections::HashMap;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tackler_api::txn_header::Tag;
use time::{Date, OffsetDateTime, PrimitiveDateTime};
use time_tz::{OffsetResult, PrimitiveDateTimeExt};

pub struct GitInput {
    pub repo: PathBuf,
    pub dir: String,
    pub git_ref: GitInputSelector,
    pub ext: String,
}

pub struct FileInput {
    pub path: PathBuf,
}

pub struct FsInput {
    pub dir: PathBuf,
    pub suffix: String,
}

pub enum InputSettings {
    File(FileInput),
    Fs(FsInput),
    Git(GitInput),
}

#[derive(Debug, Default)]
struct Commodities {
    names: HashMap<String, Arc<Commodity>>,
    permit_empty_commodity: bool,
}

impl Commodities {
    fn default_empty_ok() -> Self {
        Commodities {
            names: HashMap::new(),
            permit_empty_commodity: true,
        }
    }
}

pub struct Settings {
    pub audit_mode: bool,
    pub report: Report,
    pub export: Export,
    kernel: Kernel,
    global_acc_sel: Option<AccountSelectors>,
    targets: Vec<ReportType>,
    accounts: HashMap<String, Arc<AccountTreeNode>>,
    commodities: Commodities,
    tags: HashMap<String, Arc<Tag>>,
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            audit_mode: false,
            report: Report::default(),
            export: Export::default(),
            kernel: Kernel::default(),
            global_acc_sel: None,
            targets: Vec::new(),
            accounts: HashMap::new(),
            commodities: Commodities::default_empty_ok(),
            tags: HashMap::new(),
        }
    }
}

impl Settings {
    pub fn default_audit() -> Self {
        Settings {
            audit_mode: true,
            report: Report::default(),
            export: Export::default(),

            kernel: Kernel::default(),
            global_acc_sel: None,
            targets: Vec::new(),
            accounts: HashMap::new(),
            commodities: Commodities::default_empty_ok(),
            tags: HashMap::new(),
        }
    }
}

impl Settings {
    pub fn from(
        cfg_opt: Option<Config>,
        audit_mode: Option<bool>,
        report_accounts: Option<Vec<String>>,
    ) -> Result<Settings, Box<dyn Error>> {
        let cfg = match cfg_opt {
            Some(c) => c,
            None => {
                return match (audit_mode, report_accounts) {
                    (Some(h), Some(ra)) => {
                        let mut s = match h {
                            true => Self::default_audit(),
                            false => Self::default(),
                        };
                        s.global_acc_sel = Some(ra);
                        Ok(s)
                    }
                    (Some(h), None) => {
                        return Ok(match h {
                            true => Self::default_audit(),
                            false => Self::default(),
                        })
                    }
                    (None, Some(ra)) => Ok(Settings {
                        global_acc_sel: Some(ra),
                        ..Default::default()
                    }),
                    (None, None) => Ok(Settings::default()),
                }
            }
        };
        let accounts = cfg.transaction.accounts.names.iter().try_fold(
            HashMap::new(),
            |mut accs, account| match AccountTreeNode::from(account) {
                Ok(atn) => {
                    accs.insert(account.into(), Arc::new(atn));
                    Ok(accs)
                }
                Err(e) => {
                    let msg = format!("Invalid Chart of Accounts: {e}");
                    Err(msg)
                }
            },
        )?;

        let comms = cfg.transaction.commodities.names.iter().try_fold(
            HashMap::new(),
            |mut chm, comm| match Commodity::from(comm.to_string()) {
                Ok(c) => {
                    chm.insert(comm.into(), Arc::new(c));
                    Ok(chm)
                }
                Err(e) => {
                    let msg = format!("Invalid Chart of Commodities: {e}");
                    Err(msg)
                }
            },
        )?;

        let tags = cfg
            .transaction
            .tags
            .names
            .iter()
            .fold(HashMap::new(), |mut tags, tag| {
                let t = Tag::from(tag.to_string());
                tags.insert(tag.into(), Arc::new(t));
                tags
            });

        Ok(Settings {
            kernel: cfg.kernel.clone(),
            global_acc_sel: report_accounts,
            targets: cfg.report.targets.clone(),
            report: cfg.report,
            export: cfg.export,
            audit_mode: match audit_mode {
                Some(true) => true,
                Some(false) => false,
                None => cfg.kernel.audit.mode,
            },
            accounts,
            commodities: Commodities {
                names: comms,
                permit_empty_commodity: cfg
                    .transaction
                    .commodities
                    .permit_empty_commodity
                    .unwrap_or(false),
            },
            tags,
        })
    }
}
impl Settings {
    pub fn get_hash(&self) -> Option<Hash> {
        if self.audit_mode {
            Some(self.kernel.audit.hash.clone())
        } else {
            None
        }
    }

    pub fn get_txn_account(
        &mut self,
        name: &str,
        commodity: Arc<Commodity>,
    ) -> Result<TxnAccount, Box<dyn Error>> {
        let comm = self.get_commodity(Some(commodity.name.as_str()))?;

        match self.accounts.get(name) {
            Some(account_tree) => Ok(TxnAccount {
                atn: account_tree.clone(),
                comm,
            }),
            None => {
                if self.kernel.strict {
                    let msg = format!("Unknown account: '{}'", name);
                    Err(msg.into())
                } else {
                    let atn = Arc::new(AccountTreeNode::from(name)?);
                    self.accounts.insert(name.into(), atn.clone());
                    Ok(TxnAccount { atn, comm })
                }
            }
        }
    }

    pub fn get_commodity(&mut self, name: Option<&str>) -> Result<Arc<Commodity>, Box<dyn Error>> {
        match name {
            Some(n) => {
                if n.is_empty() {
                    if self.commodities.permit_empty_commodity {
                        return Ok(Arc::new(Commodity::default()));
                    } else {
                        let msg =
                            "Empty commodity and 'permit-empty-commodity' is not set".to_string();
                        return Err(msg.into());
                    }
                }
                match self.commodities.names.get(n) {
                    Some(comm) => Ok(comm.clone()),
                    None => {
                        if self.kernel.strict {
                            let msg = format!("Unknown commodity: '{}'", n);
                            Err(msg.into())
                        } else {
                            let comm = Arc::new(Commodity::from(n.into())?);
                            self.commodities.names.insert(n.into(), comm.clone());
                            Ok(comm)
                        }
                    }
                }
            }
            None => {
                let comm = Arc::new(Commodity::default());
                Ok(comm)
            }
        }
    }
    pub fn get_tag(&mut self, name: &str) -> Result<Arc<Tag>, Box<dyn Error>> {
        if name.is_empty() {
            let msg = "Tag name is empty string".to_string();
            return Err(msg.into());
        }
        match self.tags.get(name) {
            Some(tag) => Ok(tag.clone()),
            None => {
                if self.kernel.strict {
                    let msg = format!("Unknown tag: '{}'", name);
                    Err(msg.into())
                } else {
                    let tag = Arc::new(Tag::from(name));
                    self.tags.insert(name.into(), tag.clone());
                    Ok(tag)
                }
            }
        }
    }

    pub fn get_input_settings(
        &self,
        storage: Option<&String>,
        ref_path: Option<&Path>,
    ) -> Result<InputSettings, Box<dyn Error>> {
        let input = &self.kernel.input;

        let storage_type = match storage {
            Some(storage) => config::StorageType::from(storage.as_str())?,
            None => input.storage.clone(),
        };

        match storage_type {
            config::StorageType::FS => match &input.fs {
                Some(fs) => {
                    let dir = fs.dir.as_str();
                    let suffix = &fs.suffix;
                    let i = FsInput {
                        dir: match ref_path {
                            Some(p) => tackler_rs::get_abs_path(p, dir)?,
                            None => PathBuf::from(dir),
                        },
                        suffix: suffix.strip_prefix('.').unwrap_or(suffix.as_str()).into(),
                    };
                    Ok(InputSettings::Fs(i))
                }
                None => Err("Storage type 'fs' is not configured".into()),
            },
            config::StorageType::Git => match &input.git {
                Some(ref git) => {
                    let repo = git.repo.as_str();
                    let suffix = &git.suffix;
                    let i = GitInput {
                        repo: match ref_path {
                            Some(p) => tackler_rs::get_abs_path(p, repo)?,
                            None => PathBuf::from(repo),
                        },
                        git_ref: GitInputSelector::Reference(git.git_ref.clone()),
                        dir: git.dir.clone(),
                        ext: suffix.strip_prefix('.').unwrap_or(suffix.as_str()).into(),
                    };
                    Ok(InputSettings::Git(i))
                }
                None => Err("Storage type 'git' is not configured".into()),
            },
        }
    }
}

impl Settings {
    pub fn get_offset_datetime(
        &self,
        dt: PrimitiveDateTime,
    ) -> Result<OffsetDateTime, Box<dyn Error>> {
        let ts_tz = match self.kernel.timestamp.timezone {
            TimezoneType::Name(tz) => match dt.assume_timezone(tz) {
                OffsetResult::Some(ts) => ts,
                OffsetResult::Ambiguous(_, _) => {
                    let msg = format!("time conversion is ambiguous '{dt:?}'");
                    return Err(msg.into());
                }
                OffsetResult::None => {
                    let msg = format!("time is invalid '{dt:?}'");
                    return Err(msg.into());
                }
            },
            TimezoneType::Offset(tz) => dt.assume_offset(tz),
        };
        Ok(ts_tz)
    }
    pub fn get_offset_date(&self, date: Date) -> Result<OffsetDateTime, Box<dyn Error>> {
        let ts = PrimitiveDateTime::new(date, self.kernel.timestamp.default_time);
        self.get_offset_datetime(ts)
    }

    fn get_account_selector(&self, acc_sel: &AccountSelectors) -> AccountSelectors {
        match &self.global_acc_sel {
            Some(global_acc_sel) => global_acc_sel.clone(),
            None => acc_sel.clone(),
        }
    }

    pub fn get_report_targets(
        &self,
        arg_trgs: Option<Vec<String>>,
    ) -> Result<Vec<ReportType>, Box<dyn Error>> {
        match arg_trgs {
            Some(trgs) => config::to_report_targets(&trgs),
            None => Ok(self.targets.clone()),
        }
    }

    pub fn get_balance_ras(&self) -> AccountSelectors {
        self.get_account_selector(&self.report.balance.acc_sel)
    }

    pub fn get_balance_group_ras(&self) -> AccountSelectors {
        self.get_account_selector(&self.report.balance_group.acc_sel)
    }

    pub fn get_register_ras(&self) -> AccountSelectors {
        self.get_account_selector(&self.report.register.acc_sel)
    }

    pub fn get_equity_ras(&self) -> AccountSelectors {
        self.get_account_selector(&self.export.equity.acc_sel)
    }
}

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

    #[test]
    fn txnatn_atn() {
        let mut settings = Settings::default();

        let txnatn_1 =
            settings.get_txn_account("a:b:c", Arc::new(Commodity::default())).unwrap(/*:test:*/);

        assert_eq!(txnatn_1.atn.depth, 3);
        assert_eq!(txnatn_1.atn.get_root(), "a");
        assert_eq!(txnatn_1.atn.parent, "a:b");
        assert_eq!(txnatn_1.atn.account, "a:b:c");
        assert_eq!(txnatn_1.atn.get_name(), "c");

        let txnatn_2 =
            settings.get_txn_account("a:b:c", Arc::new(Commodity::default())).unwrap(/*:test:*/);

        assert_eq!(txnatn_2.atn.depth, 3);
        assert_eq!(txnatn_2.atn.get_root(), "a");
        assert_eq!(txnatn_2.atn.parent, "a:b");
        assert_eq!(txnatn_2.atn.account, "a:b:c");
        assert_eq!(txnatn_2.atn.get_name(), "c");

        assert_eq!(settings.accounts.len(), 1);
    }
}