Skip to content

Commit

Permalink
Move print into TaxableTrade
Browse files Browse the repository at this point in the history
  • Loading branch information
brucify committed Apr 28, 2023
1 parent 46f0528 commit 195136d
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 44 deletions.
6 changes: 3 additions & 3 deletions src/calculator/cost_book.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::collections::HashSet;
use anyhow::{anyhow, Result};
use crate::calculator::Currency;
use crate::calculator::money::Money;
use crate::calculator::TaxableTrade;
use crate::calculator::money::Money;
use crate::calculator::trade::{Direction, Trade};
use anyhow::{anyhow, Result};
use log::debug;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use std::collections::HashSet;
use std::ops::{Neg, Sub};

pub(crate) async fn all_taxable_trades(trades: &Vec<Trade>) -> Vec<TaxableTrade> {
Expand Down
22 changes: 22 additions & 0 deletions src/calculator/taxable_trade.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use anyhow::{anyhow, Result};
use crate::calculator::Currency;
use crate::calculator::money::Money;
use crate::{Config, skatteverket, writer};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::ser::SerializeStruct;
Expand Down Expand Up @@ -64,5 +66,25 @@ impl TaxableTrade {
.fold("".to_string(), |acc, c| format!("{}, {}", acc, c))
}
}

pub(crate) async fn print_taxable_trades(taxable_trades: &Vec<TaxableTrade>, config: &Config) -> Result<()> {
if let Some(sru_conf) = &config.sru_file_config {
Self::print_sru_file(&taxable_trades, sru_conf.sru_org_num.clone(), sru_conf.sru_org_name.clone()).await?;
} else {
writer::print_csv_rows(&taxable_trades).await?;
}
Ok(())
}

async fn print_sru_file(taxable_trades: &Vec<TaxableTrade>, org_num: String, name: Option<String>) -> Result<()> {
let sru_file = skatteverket::SruFile::try_new(taxable_trades, org_num, name)
.ok_or(anyhow!("Failed to create SRU file from taxable trades"))?;

let stdout = std::io::stdout();
let handle = stdout.lock();
sru_file.write(handle)?;

Ok(())
}
}

38 changes: 9 additions & 29 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use anyhow::{anyhow, Result};
use anyhow::Result;
use crate::calculator::TaxableTrade;
use log::info;
use reader::RevolutRow2022;
use reader::RevolutRow2023;
use std::path::PathBuf;
use std::time::Instant;
use crate::calculator::TaxableTrade;

mod calculator;
mod reader;
Expand All @@ -18,12 +18,13 @@ pub struct Config {
pub print_exchanges_only: bool,
pub print_trades: bool,
pub sru_file_config: Option<SruFileConfig>,
pub csv_year: u16,
pub year_traded: Option<u16>,
pub csv_version: u16,
}

pub struct SruFileConfig {
pub sru_org_num: String,
pub sru_name: Option<String>,
pub sru_org_name: Option<String>,
}

/// Reads the transactions with type `Exchange` from the path and prints the results to
Expand Down Expand Up @@ -80,7 +81,7 @@ pub async fn merge_exchanges(path: &PathBuf, currency: &String) -> Result<()> {
/// converts the csv rows into transactions,
/// calculates tax from the transactions,
/// and finally prints the results to `std::io::stdout()`.
pub async fn calculate_tax_2022(config: &Config) -> Result<()> {
pub async fn calculate_tax_v2022(config: &Config) -> Result<()> {
let now = Instant::now();
let rows = RevolutRow2022::read_exchanges_in_currency(&config.path, &config.currency).await?;
info!("Done reading csv file. Elapsed: {:.2?}", now.elapsed());
Expand All @@ -94,13 +95,13 @@ pub async fn calculate_tax_2022(config: &Config) -> Result<()> {
info!("Done calculating taxes. Elapsed: {:.2?}", now.elapsed());

let now = Instant::now();
print_result(&taxable_trades, config).await?;
TaxableTrade::print_taxable_trades(&taxable_trades, config).await?;
info!("Done printing results. Elapsed: {:.2?}", now.elapsed());

Ok(())
}

pub async fn calculate_tax_2023(config: &Config) -> Result<()> {
pub async fn calculate_tax_v2023(config: &Config) -> Result<()> {
let now = Instant::now();
let trades = RevolutRow2023::deserialize_from(&config.path).await?;
info!("Done reading csv file. Elapsed: {:.2?}", now.elapsed());
Expand All @@ -110,29 +111,8 @@ pub async fn calculate_tax_2023(config: &Config) -> Result<()> {
info!("Done calculating taxes. Elapsed: {:.2?}", now.elapsed());

let now = Instant::now();
print_result(&taxable_trades, config).await?;
TaxableTrade::print_taxable_trades(&taxable_trades, config).await?;
info!("Done printing results. Elapsed: {:.2?}", now.elapsed());

Ok(())
}

async fn print_result(taxable_trades: &Vec<TaxableTrade>, config: &Config) -> Result<()> {
if let Some(sru_conf) = &config.sru_file_config {
print_sru_file(&taxable_trades, sru_conf.sru_org_num.clone(), sru_conf.sru_name.clone()).await?;
} else {
writer::print_csv_rows(&taxable_trades).await?;
}
Ok(())
}

async fn print_sru_file(taxable_trades: &Vec<TaxableTrade>, org_num: String, name: Option<String>) -> Result<()> {
let now = Instant::now();
let sru_file = skatteverket::SruFile::try_new(taxable_trades, org_num, name)
.ok_or(anyhow!("Failed to create SRU file from taxable trades"))?;
let stdout = std::io::stdout();
let handle = stdout.lock();
sru_file.write(handle)?;
info!("Done printing SRU file. Elapsed: {:.2?}", now.elapsed());

Ok(())
}
27 changes: 16 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::{anyhow, Context, Result};
use clap::Parser;
use futures::executor::block_on;
use log::info;
use log::error;

/// Search for currency exchanges in a Revolut csv file and output a new csv containing the tax information.
#[derive(Parser)]
Expand Down Expand Up @@ -29,10 +29,13 @@ struct Cli {
sru_org_num: Option<String>,

#[arg(long, help = "Name to print in the SRU file")]
sru_name: Option<String>,
sru_org_name: Option<String>,

#[arg(long, help = "Only include taxable trades from this year")]
year_traded: Option<u16>,

#[arg(long, help = "Specify the year of the Revolut CSV file to process. Defaults to 2023")]
csv_year: Option<u16>,
csv_version: Option<u16>,
}

impl Cli {
Expand All @@ -45,14 +48,15 @@ impl Cli {
print_trades,
sru_file,
sru_org_num,
sru_name,
csv_year,
sru_org_name,
year_traded,
csv_version,
} = self;

let sru_file_config = if sru_file {
Some(cryptotax::SruFileConfig {
sru_org_num: sru_org_num.ok_or(anyhow!("--sru_org_num <SRU_ORG_NUM> is mandatory if --sru_file is given"))?,
sru_name,
sru_org_name,
})
} else {
None
Expand All @@ -65,7 +69,8 @@ impl Cli {
print_exchanges_only,
print_trades,
sru_file_config,
csv_year: csv_year.unwrap_or(2023),
year_traded,
csv_version: csv_version.unwrap_or(2023),
};

Ok(config)
Expand All @@ -78,7 +83,7 @@ fn main() {
let args = Cli::parse();
let config = args.to_config().with_context(|| format!("Invalid command line flags")).unwrap();

match (config.csv_year, config.print_exchanges_only, config.print_trades) {
match (config.csv_version, config.print_exchanges_only, config.print_trades) {
(2022, true, _) => {
match config.currency.as_str() {
"ALL" => block_on(cryptotax::print_exchanges(&config.path)),
Expand All @@ -93,17 +98,17 @@ fn main() {
.unwrap();
},
(2022, false, false) => {
block_on(cryptotax::calculate_tax_2022(&config))
block_on(cryptotax::calculate_tax_v2022(&config))
.with_context(|| format!("Could not calculate tax from file `{:?}`", &config.path))
.unwrap();
},
(2023, _, _) => {
block_on(cryptotax::calculate_tax_2023(&config))
block_on(cryptotax::calculate_tax_v2023(&config))
.with_context(|| format!("Could not calculate tax from file `{:?}`", &config.path))
.unwrap();
},
_ => {
info!("Unknown csv year")
error!("Unknown csv year")
},
}
}
3 changes: 2 additions & 1 deletion src/skatteverket/sru_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/

use anyhow::{anyhow, Result};
use chrono::Datelike;
use log::debug;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
Expand Down Expand Up @@ -80,7 +81,7 @@ impl SruFile {
.ok()
.map(|information| {
SruFile {
form: format!("K4-{}P4", chrono::Utc::now().format("%Y")),
form: format!("K4-{}P4", chrono::Utc::now().year() - 1),
identity: Identity { org_num },
name,
information,
Expand Down

0 comments on commit 195136d

Please sign in to comment.