tktax-amazon 0.2.2

High-performance crate for parsing, fusing, and exporting Amazon transaction data for financial recordkeeping.
Documentation
// ---------------- [ File: tktax-amazon/src/write_amazon_tx_to_csv.rs ]
crate::ix!();

pub fn write_to_csv(transactions: Vec<AmazonTx>, filename: &str) 
    -> Result<(), AmazonError> 
{
    // Define custom function to convert u32 to three-letter string
    fn int_to_code(mut n: i32) -> String {
        let mut code = String::new();
        for _ in 0..3 {
            let remainder = n % 26;
            let letter = (b'A' + remainder as u8) as char;
            code.push(letter);
            n /= 26;
        }
        code.chars().rev().collect()
    }

    let mut writer = csv::Writer::from_path(filename)?;

    // Write header row
    writer.write_record(&["quantity", "index", "unit_price", "order_date", "product_name"])?;

    // Initialize counter
    let mut count = -1;

    // Create vector of vectors with numeric record as leftmost column
    let data: Vec<Vec<String>> = transactions.into_iter()
        .map(|tx| {
            count += 1;
            vec![
                format!("{}", tx.quantity()), 
                int_to_code(count),
                format!("{}", tx.unit_price()), 
                tx.order_date().to_string(), 
                tx.product_name().to_string()
            ]
        })
        .collect();

    // Write data rows
    for row in data {
        writer.write_record(row)?;
    }

    writer.flush()?;

    Ok(())
}