etradeTaxReturnHelper 0.7.5

Parses etrade and revolut financial documents for transaction details (income, tax paid, cost basis) and compute total income and total tax paid according to chosen tax residency (currency)
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
// SPDX-FileCopyrightText: 2023-2025 RustInFinance
// SPDX-License-Identifier: BSD-3-Clause

#![cfg(feature = "gui")]

pub use crate::logging::ResultExt;
use fltk::{
    app,
    browser::MultiBrowser,
    button::Button,
    dialog,
    enums::{Event, Font, FrameType, Key},
    frame::Frame,
    group::Pack,
    prelude::*,
    text::{TextBuffer, TextDisplay},
    window,
};

use crate::pl::PL;
use crate::run_taxation;

use std::cell::RefCell;
use std::rc::Rc;

#[derive(Copy, Clone)]
pub enum Message {
    ChoiceChanged,
    Changed,
    Execute,
    Open,
    Quit,
    Copy,
    Paste,
}

/// Dummy method for running diagnostic
fn feed_input(browser: &mut MultiBrowser) {
    let docs = [
    "/home/jczaja/e-trade-tax-return-pl-helper/etrade_data/Brokerage Statement - XXXX0848 - 202202.pdf",
    "/home/jczaja/e-trade-tax-return-pl-helper/etrade_data/Brokerage Statement - XXXX0848 - 202203.pdf",
    "/home/jczaja/e-trade-tax-return-pl-helper/etrade_data/Brokerage Statement - XXXX0848 - 202204.pdf",
    "/home/jczaja/e-trade-tax-return-pl-helper/etrade_data/Brokerage Statement - XXXX0848 - 202205.pdf",
    "/home/jczaja/e-trade-tax-return-pl-helper/etrade_data/Brokerage Statement - XXXX0848 - 202206.pdf",
    "/home/jczaja/e-trade-tax-return-pl-helper/etrade_data/G&L_Expanded.xlsx"];

    docs.iter().for_each(|x| browser.add(x));
}

fn create_clear_documents(
    browser: Rc<RefCell<MultiBrowser>>,
    tdisplay: Rc<RefCell<TextDisplay>>,
    sdisplay: Rc<RefCell<TextDisplay>>,
    ndisplay: Rc<RefCell<TextDisplay>>,
    clear_button: &mut Button,
) {
    clear_button.set_callback(move |_| {
        let mut buffer = sdisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Summary TextDisplay");
        let mut nbuffer = ndisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Notes TextDisplay");
        let mut tbuffer = tdisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Transactions TextDisplay");
        let mut filelist = browser.borrow_mut();
        filelist.clear();
        buffer.set_text("");
        tbuffer.set_text("");
        nbuffer.set_text("");
    });
}

fn create_execute_documents(
    browser: Rc<RefCell<MultiBrowser>>,
    tdisplay: Rc<RefCell<TextDisplay>>,
    sdisplay: Rc<RefCell<TextDisplay>>,
    ndisplay: Rc<RefCell<TextDisplay>>,
    execute_button: &mut Button,
) {
    execute_button.set_callback(move |_| {
        let mut buffer = sdisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Summary TextDisplay");
        let mut nbuffer = ndisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Notes TextDisplay");
        let mut tbuffer = tdisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Transactions TextDisplay");
        let mut file_names: Vec<String> = vec![];
        let list_names = browser.borrow();
        log::info!("Processing {} files", list_names.size());
        if list_names.size() == 0 {
            log::info!("No files to process");
            return;
        }
        for i in 1..=list_names.size() {
            let line_content = browser.borrow().text(i);
            match line_content {
                Some(text) => {
                    log::info!("File to be processed: {}", text);
                    file_names.push(text)
                }
                None => {
                    log::error!("Error: No content in Multbrowse line: {i}");
                    nbuffer.set_text("Error: No content in Multbrowse line: {i}");
                }
            }
        }
        buffer.set_text("");
        tbuffer.set_text("");
        nbuffer.set_text("Running...");
        let rd: Box<dyn etradeTaxReturnHelper::Residency> = Box::new(PL {});
        let etradeTaxReturnHelper::TaxCalculationResult {
            gross_income: gross_div,
            tax: tax_div,
            gross_sold,
            cost_sold,
            interests: interests_transactions,
            transactions: div_transactions,
            revolut_dividends_transactions: revolut_transactions,
            sold_transactions,
            revolut_sold_transactions,
        } = match run_taxation(&rd, file_names,false, false) {
            Ok(res) => {
                nbuffer.set_text("Finished.\n\n (Double check if generated tax data (Summary) makes sense and then copy it to your tax form)");
                res
            }
            Err(err) => {
                nbuffer.set_text(&err);
                panic!("Error: unable to perform taxation");
            }
        };
        let (presentation,warning) = rd.present_result(gross_div, tax_div, gross_sold, cost_sold);
        buffer.set_text(&presentation.join("\n"));
        if let Some(warn_msg) = warning {
            nbuffer.set_text(&warn_msg);
        }
        let mut transactions_strings: Vec<String> = vec![];
        interests_transactions
            .iter()
            .for_each(|x| transactions_strings.push(x.format_to_print("INTERESTS").expect_and_log("Error: Formatting INTERESTS transaction failed")));
        div_transactions
            .iter()
            .for_each(|x| transactions_strings.push(x.format_to_print("DIV").expect_and_log("Error: Formatting DIV transaction failed")));
        revolut_transactions
            .iter()
            .for_each(|x| transactions_strings.push(x.format_to_print("REVOLUT ").expect_and_log("Error: Formatting DIV transaction failed")));
        sold_transactions
            .iter()
            .for_each(|x| transactions_strings.push(x.format_to_print("")));
        revolut_sold_transactions
            .iter()
            .for_each(|x| transactions_strings.push(x.format_to_print("REVOLUT ")));
        tbuffer.set_text(&transactions_strings.join("\n"));
    });
}

fn create_choose_documents_dialog(
    browser: Rc<RefCell<MultiBrowser>>,
    tdisplay: Rc<RefCell<TextDisplay>>,
    sdisplay: Rc<RefCell<TextDisplay>>,
    ndisplay: Rc<RefCell<TextDisplay>>,
    load_button: &mut Button,
) {
    load_button.set_callback(move |_| {
        let mut chooser = dialog::FileDialog::new(dialog::FileDialogType::BrowseMultiFile);
        let _ = chooser.set_directory(&".");
        chooser.set_filter("*.{pdf,xlsx,csv}");
        chooser.set_title("Choose e-trade documents with transactions (PDF and/or XLSX)");
        chooser.show();
        if let Some(message) = chooser.error_message() {
            if message != "No error" {
                log::info!("Error in chooser: {}", message);
                return;
            }
        }
        let filenames = chooser.filenames();
        log::info!("{} were selected", filenames.len());
        let mut filelist = browser.borrow_mut();
        for filename in filenames {
            filelist.add(&filename.to_string_lossy());
        }
        let mut buffer = sdisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Summary TextDisplay");
        let mut nbuffer = ndisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Notes TextDisplay");
        let mut tbuffer = tdisplay
            .borrow()
            .buffer()
            .expect_and_log("Error: No buffer assigned to Transactions TextDisplay");
        buffer.set_text("");
        tbuffer.set_text("");
        nbuffer.set_text("");
    });
}

pub fn run_gui() {
    log::info!("Starting GUI");

    const WIND_SIZE_X: i32 = 1024;
    const WIND_SIZE_Y: i32 = 768;
    const DOCUMENTS_REL_WIDTH: f64 = 0.2;
    const TRANSACTIONS_REL_WIDTH: f64 = 0.4;
    const SUMMARY_REL_WIDTH: f64 = 0.4;
    const DOCUMENTS_COL_WIDTH: i32 = (DOCUMENTS_REL_WIDTH * WIND_SIZE_X as f64) as i32;
    const TRANSACTIONS_COL_WIDTH: i32 = (TRANSACTIONS_REL_WIDTH * WIND_SIZE_X as f64) as i32;
    const SUMMARY_COL_WIDTH: i32 = (SUMMARY_REL_WIDTH * WIND_SIZE_X as f64) as i32;

    let app = app::App::default();

    let mut wind = window::Window::default()
        .with_size(WIND_SIZE_X, WIND_SIZE_Y)
        .center_screen()
        .with_label("eTradeTaxReturnHelper");

    wind.make_resizable(true);

    let mut uberpack = Pack::new(0, 0, WIND_SIZE_X as i32, WIND_SIZE_Y as i32, "");

    let mut pack = Pack::new(0, 0, WIND_SIZE_X as i32, WIND_SIZE_Y / 2 as i32, "");
    pack.set_type(fltk::group::PackType::Horizontal);

    let mut pack1 = Pack::new(0, 0, DOCUMENTS_COL_WIDTH, 300, "");
    pack1.set_type(fltk::group::PackType::Vertical);
    let mut frame1 = Frame::new(0, 0, DOCUMENTS_COL_WIDTH, 30, "Documents");
    frame1.set_frame(FrameType::EngravedFrame);

    let browser = Rc::new(RefCell::new(MultiBrowser::new(
        0,
        30,
        DOCUMENTS_COL_WIDTH,
        270,
        "",
    )));
    //feed_input(&mut browser.borrow_mut());

    let mut load_button = Button::new(0, 300, DOCUMENTS_COL_WIDTH, 30, "1. Add");
    load_button.set_label_font(Font::HelveticaBold);
    let mut clear_button = Button::new(0, 300, DOCUMENTS_COL_WIDTH, 30, "Remove All");
    clear_button.set_label_font(Font::HelveticaBold);
    pack1.end();

    let mut pack2 = Pack::new(0, 0, TRANSACTIONS_COL_WIDTH, 300, "");
    pack2.set_type(fltk::group::PackType::Vertical);
    let mut frame2 = Frame::new(0, 0, TRANSACTIONS_COL_WIDTH, 30, "Detected Transactions");
    frame2.set_frame(FrameType::EngravedFrame);

    let mut buffer = TextBuffer::default();
    buffer.set_text("");

    let tdisplay = Rc::new(RefCell::new(TextDisplay::new(
        0,
        30,
        TRANSACTIONS_COL_WIDTH,
        270,
        "",
    )));
    tdisplay.borrow_mut().set_buffer(buffer);

    pack2.end();

    let mut pack3 = Pack::new(0, 0, SUMMARY_COL_WIDTH, 300, "");
    pack3.set_type(fltk::group::PackType::Vertical);
    let mut frame3 = Frame::new(
        0,
        0,
        SUMMARY_COL_WIDTH,
        30,
        "Summary (Data for your Tax form)",
    );
    frame3.set_frame(FrameType::EngravedFrame);

    let buffer = TextBuffer::default();

    let sdisplay = Rc::new(RefCell::new(TextDisplay::new(
        0,
        30,
        SUMMARY_COL_WIDTH,
        270,
        "",
    )));
    sdisplay.borrow_mut().set_buffer(buffer);

    let mut execute_button = Button::new(0, 300, SUMMARY_COL_WIDTH, 30, "2. Execute");
    execute_button.set_label_font(Font::HelveticaBold);

    pack3.end();

    pack.end();

    let mut frame4 = Frame::new(0, pack.height(), WIND_SIZE_X, 30, "Notes:");
    frame4.set_frame(FrameType::EngravedFrame);
    let mut buffer = TextBuffer::default();
    buffer.set_text("Hi!\n\n 1. Add your documents \n 2.  Execute calculation");
    let ndisplay = Rc::new(RefCell::new(TextDisplay::new(0, 30, WIND_SIZE_X, 270, "")));
    ndisplay.borrow_mut().set_buffer(buffer);
    ndisplay.borrow_mut().set_text_size(20);

    uberpack.end();

    create_choose_documents_dialog(
        browser.clone(),
        tdisplay.clone(),
        sdisplay.clone(),
        ndisplay.clone(),
        &mut load_button,
    );
    create_clear_documents(
        browser.clone(),
        tdisplay.clone(),
        sdisplay.clone(),
        ndisplay.clone(),
        &mut clear_button,
    );
    create_execute_documents(
        browser.clone(),
        tdisplay.clone(),
        sdisplay.clone(),
        ndisplay.clone(),
        &mut execute_button,
    );

    wind.handle(move |wind, ev| {
        let mut dnd = false;
        let mut released = false;
        match ev {
            Event::DndEnter => {
                dnd = true;
                true
            }
            Event::DndDrag => true,
            Event::DndRelease => {
                released = true;
                true
            }
            Event::Paste => {
                let files = app::event_text();
                for file in files.split('\n') {
                    browser.borrow_mut().add(file);
                }
                true
            }
            Event::Resize => {
                uberpack.set_size(wind.width(), wind.height());
                frame4.set_size(wind.width(), frame4.height());

                // First column
                pack.set_size(
                    (DOCUMENTS_REL_WIDTH * wind.width() as f64) as i32,
                    wind.height() / 2,
                );
                pack1.set_size(
                    (DOCUMENTS_REL_WIDTH * wind.width() as f64) as i32,
                    pack1.height(),
                );
                frame1.set_size(
                    (DOCUMENTS_REL_WIDTH * wind.width() as f64) as i32,
                    frame1.height(),
                );

                let height = browser.borrow().height();
                browser
                    .borrow_mut()
                    .set_size((DOCUMENTS_REL_WIDTH * wind.width() as f64) as i32, height);

                //Second column
                pack2.set_size(
                    (TRANSACTIONS_REL_WIDTH * wind.width() as f64) as i32,
                    pack2.height(),
                );
                frame2.set_size(
                    (TRANSACTIONS_REL_WIDTH * wind.width() as f64) as i32,
                    frame2.height(),
                );
                let ht = tdisplay.borrow().height();
                tdisplay
                    .borrow_mut()
                    .set_size((TRANSACTIONS_REL_WIDTH * wind.width() as f64) as i32, ht);

                //Third column
                pack3.set_size(
                    (TRANSACTIONS_REL_WIDTH * wind.width() as f64) as i32,
                    pack3.height(),
                );
                frame3.set_size(
                    (TRANSACTIONS_REL_WIDTH * wind.width() as f64) as i32,
                    frame3.height(),
                );
                let height = sdisplay.borrow().height();
                sdisplay.borrow_mut().set_size(
                    (TRANSACTIONS_REL_WIDTH * wind.width() as f64) as i32,
                    height,
                );
                true
            }

            Event::KeyUp => {
                if app::event_key() == Key::Delete {
                    let mut list = browser.borrow_mut();
                    let list_size = list.size();
                    // Go in descending order to avoid deleting wrong indices
                    log::info!("Removing elements from list of size: {list_size}");
                    for idx in (1..=list_size).rev() {
                        if list.selected(idx) == true {
                            log::info!("Removing element of index: {idx}");
                            list.remove(idx);
                        }
                    }

                    let mut buffer = sdisplay
                        .borrow()
                        .buffer()
                        .expect_and_log("Error: No buffer assigned to Summary TextDisplay");
                    let mut nbuffer = ndisplay
                        .borrow()
                        .buffer()
                        .expect_and_log("Error: No buffer assigned to Notes TextDisplay");
                    let mut tbuffer = tdisplay
                        .borrow()
                        .buffer()
                        .expect_and_log("Error: No buffer assigned to Transactions TextDisplay");
                    buffer.set_text("");
                    tbuffer.set_text("");
                    nbuffer.set_text("");
                }
                true
            }

            _ => false,
        }
    });

    wind.end();
    wind.show();

    app.run().unwrap();
}