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
/*!
 * Runs Ledger-cli to retrieve required reports.
 */

use std::process::{Command, Output};

use chrono::{Days, Local};

use crate::{compare::TRANSACTION_DAYS, ledger_reg_output_parser, model::CommonTransaction};

/// Get ledger transactions
/// Ledger must be callable from the current directory.
pub fn get_ledger_tx(ledger_init_file: Option<String>) -> Vec<CommonTransaction> {
    let end_date = Local::now().date_naive();
    let start_date = end_date
        .checked_sub_days(Days::new(TRANSACTION_DAYS.into()))
        .expect("calculated start date");

    let date_param = start_date.format("%Y-%m-%d").to_string();

    let cmd = get_ledger_cmd(&date_param, ledger_init_file);

    log::debug!("running: {}", cmd);

    let output = cli_runner::run(&cmd);

    if !output.status.success() {
        let err = cli_runner::get_stderr(&output);
        panic!("Error running Ledger command: {}", err);
        // log::debug!("error: {:?}", err);
        // assert!(err.is_empty());
    }
    let out = cli_runner::get_stdout(&output);

    log::debug!("ledger output: {:?}", out);

    let lines: Vec<&str> = out.lines().collect();

    // cleanup
    let clean_lines = ledger_reg_output_parser::clean_up_register_output(lines);

    // Parse output.
    let txs = ledger_reg_output_parser::get_rows_from_register(clean_lines);

    txs
}

#[allow(unused)]
fn run_ledger_args(args: Vec<String>) -> Output {
    log::debug!("ledger args: {:?}", args);

    let output = Command::new("ledger")
        .args(args)
        .output()
        .expect("ledger command ran");

    output
}

#[allow(unused)]
fn get_ledger_args(date_param: &str, ledger_init_file: Option<String>) -> Vec<String> {
    let mut args: Vec<String> = vec!["r".to_owned()];
    args.push("-b".to_owned());
    args.push(date_param.to_owned());
    args.push("-d".to_owned());
    args.push(r#""(account =~ /income/ and account =~ /ib/) or (account =~ /ib/ and account =~ /withh/)""#.to_owned());

    if crate::compare::DATE_MODE == "effective" {
        args.push("--effective".to_owned());
    }

    if let Some(init_file) = ledger_init_file {
        args.push("--init-file".to_owned());
        args.push(init_file.to_owned());
    }

    args
}

fn get_ledger_cmd(date_param: &str, ledger_init_file: Option<String>) -> String {
    let mut cmd = format!("ledger r -b {date_param} -d");

    cmd.push_str(r#" "(account =~ /income/ and account =~ /ib/) or (account =~ /ib/ and account =~ /withh/)""#);

    if crate::compare::DATE_MODE == "effective" {
        cmd.push_str(" --effective");
    }

    if let Some(init_file) = ledger_init_file {
        cmd.push_str(" --init-file ");
        cmd.push_str(&init_file);
    };

    cmd
}

/// Runs Ledger with the given command and returns the output in lines.
/// cmd: The ledger command to execute, without `ledger` at the beginning.
/// Returns the lines of the Ledger output.
#[allow(unused)]
fn run_ledger(args: Vec<String>) -> Vec<String> {
    // cmd: &str

    // let output = run_ledger_cmd(cmd);
    let output = run_ledger_args(args);

    log::debug!("output is {:?}", output);

    assert!(output.stderr.is_empty());

    let result: Vec<String> = String::from_utf8(output.stdout)
        .unwrap()
        .lines()
        //.map(|line| line.trim().to_owned())
        .map(|line| line.to_owned())
        .collect();

    result
}

////
// Tests
////

#[cfg(test)]
mod tests {
    use super::get_ledger_tx;
    use super::run_ledger;
    use crate::test_fixtures::*;

    /// Confirm that Ledger can be invoked from the current directory.
    #[rstest::rstest]
    #[test_log::test]
    fn run_ledger_test(ledger_init_path: String) {
        let mut cmd = "b active and cash --init-file ".to_string();
        cmd.push_str(&ledger_init_path);
        // let actual = run_ledger(&cmd);

        // let mut args = vec!["b".to_owned()];
        // args.push("active".to_owned());
        // args.push("and".to_owned());
        // args.push("cash".to_owned());
        // args.push("--init-file".to_owned());
        // args.push(ledger_init_path);
        let args = cmd
            .split_whitespace()
            .into_iter()
            .map(|item| item.to_owned())
            .collect();
        let actual = run_ledger(args);

        assert!(!actual.is_empty());
        assert_ne!(actual[0], String::default());
        assert_eq!("           -3.00 EUR  Assets:Active:Cash", actual[0]);
    }

    /// Test fetching the required Ledger transactions.
    #[rstest::rstest]
    #[test_log::test]
    fn test_get_ledger_tx(ledger_init_path: String) {
        println!("ledger_init_path: {:?}", ledger_init_path);

        let path_opt = Some(ledger_init_path);
        let actual = get_ledger_tx(path_opt);

        println!("txs: {:?}", actual);

        assert!(!actual.is_empty());
        assert_eq!(2, actual.len());
    }

    /// Run the complex query on Ledger, using shell-words.
    #[test_log::test]
    fn test_ledger_words() {
        let cmd = r#"r -b 2022-03-01 -d  "(account =~ /income/ and account =~ /ib/) or (account =~ /ib/ and account =~ /withh/)" --init-file tests/init.ledger"#;
        let args = shell_words::split(cmd).unwrap();

        let actual = run_ledger(args);

        let expected: Vec<&str> = r#"2022-12-15 TRET_AS Distribution               Income:Investment:IB:TRET_AS                      -38.40 EUR           -38.40 EUR
                                              Expenses:Investment:IB:Withholding Tax              5.77 EUR           -32.63 EUR"#.lines().collect();

        assert!(!actual.is_empty());
        assert_eq!(expected, actual);
    }

    #[test_log::test]
    fn test_shellwords() {
        let cmd = r#"ledger r -b 2022-03-01 -d "(account =~ /income/ and account =~ /ib/) or (account =~ /ib/ and account =~ /withh/)" --init-file tests/init.ledger"#;
        let actual = shell_words::split(cmd).unwrap();

        log::debug!("result: {:?}", actual);

        assert!(!actual.is_empty());
        assert_eq!(8, actual.len());
    }

    #[test_log::test]
    fn test_cli_runner() {
        let cmd = r#"ledger r -b 2022-03-01 -d "(account =~ /income/ and account =~ /ib/) or (account =~ /ib/ and account =~ /withh/)" --init-file tests/init.ledger"#;

        let actual = cli_runner::run(cmd);

        let stderr: String = String::from_utf8(actual.stderr).expect("stdout string");
        let stdout: String = String::from_utf8(actual.stdout).expect("stdout string");

        assert!(!stdout.is_empty());
        assert!(stderr.is_empty());
    }

    #[test_log::test]
    fn test_output_conversion() {
        let cmd = r#"ledger r -b 2022-03-01 -d "(account =~ /income/ and account =~ /ib/) or (account =~ /ib/ and account =~ /withh/)" --init-file tests/init.ledger"#;
        let output = cli_runner::run(cmd);

        let so = cli_runner::get_stdout(&output);
        log::debug!("so: {:?}", so);
        assert!(!so.is_empty());

        let se = cli_runner::get_stderr(&output);
        assert!(se.is_empty());
    }
}