Cotton code
164 lines · 6.7 KB · RustRaw
//! A movement of money as a person says it: "spent 450 on groceries at Quay//! Street Grocer". Pure text in, the parts out — which account, which category//! and how many minor units are the caller's to resolve against the book.use regex::Regex;use std::sync::LazyLock;/// What a sentence about money said.#[derive(Debug, Clone, PartialEq, Eq)]pub struct MoneyWords {    /// The money engine's capture verb: `spent`, `received`, `lent` or    /// `borrowed`. A sentence that opens on its amount is a spend.    pub verb: &'static str,    /// The amount's digits before the point, separators removed.    pub whole: String,    /// The digits after the point, as typed (`""`, `"5"`, `"50"`).    pub fraction: String,    /// What it was for: the words after "on" or "for".    pub category: Option<String>,    /// Who it went to or came from: the words after "at" or "to", else those    /// after "from".    pub payee: Option<String>,    /// The words after "from" — an account's name ("from Cash") when the    /// caller finds one by it, else who it came from (already the payee when    /// nothing said "at" or "to").    pub from: Option<String>,    /// Words that sat before any of those ("coffee" in "spent 180 coffee").    pub lead: Option<String>,}impl MoneyWords {    /// The amount in `currency`'s minor units — `None` when it has more    /// decimal places than the currency does, or does not fit.    pub fn minor_units(&self, currency: &str) -> Option<i64> {        let digits = usize::from(crate::records::amount::digits(currency));        if self.fraction.len() > digits {            return None;        }        let padded = format!("{}{:0<width$}", self.whole, self.fraction, width = digits);        padded.parse::<i64>().ok().filter(|minor| *minor > 0)    }    /// The line the owner reads back: who, else the loose words, else what for.    pub fn description(&self) -> String {        let words = self            .payee            .as_deref()            .or(self.lead.as_deref())            .or(self.category.as_deref())            .unwrap_or(match self.verb {                "received" => "Money in",                "lent" => "Lent",                "borrowed" => "Borrowed",                _ => "Spending",            });        let mut letters = words.chars();        match letters.next() {            Some(first) => first.to_uppercase().chain(letters).collect(),            None => String::new(),        }    }}/// Read a sentence about money, or `None` when it names no amount.pub fn money_words(text: &str) -> Option<MoneyWords> {    static AMOUNT: LazyLock<Regex> = LazyLock::new(|| {        Regex::new(r"(?i)(?:₹|\$|€|£|\brs\.?\s*|\binr\s*)?\s*\b([0-9][0-9,]*)(?:\.([0-9]{1,3}))?\b")            .expect("static money pattern")    });    let amount = AMOUNT.captures(text)?;    let whole: String = amount[1].chars().filter(char::is_ascii_digit).collect();    let fraction = amount.get(2).map_or("", |m| m.as_str()).to_string();    let span = amount.get(0)?;    let before = text[..span.start()].trim();    let after = text[span.end()..].trim();    let mut verb = "spent";    let mut lead: Vec<&str> = Vec::new();    for word in before.split_whitespace() {        match word.to_lowercase().as_str() {            "spent" | "paid" | "bought" | "pay" | "spend" => verb = "spent",            "received" | "got" | "earned" | "receive" => verb = "received",            "lent" | "lend" => verb = "lent",            "borrowed" | "borrow" => verb = "borrowed",            _ => lead.push(word),        }    }    let (mut category, mut payee, mut from): (Vec<&str>, Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new(), Vec::new());    #[derive(Clone, Copy)]    enum Part {        Lead,        Category,        Payee,        From,    }    let mut part = Part::Lead;    for word in after.split_whitespace() {        match word.to_lowercase().as_str() {            "on" | "for" if category.is_empty() => part = Part::Category,            "at" | "to" if payee.is_empty() => part = Part::Payee,            "from" if from.is_empty() => part = Part::From,            _ => match part {                Part::Lead => lead.push(word),                Part::Category => category.push(word),                Part::Payee => payee.push(word),                Part::From => from.push(word),            },        }    }    let said = |words: &[&str]| (!words.is_empty()).then(|| words.join(" "));    let from = said(&from);    Some(MoneyWords {        verb,        whole,        fraction,        category: said(&category),        payee: said(&payee).or_else(|| from.clone()),        from,        lead: said(&lead),    })}#[cfg(test)]mod tests {    use super::*;    /// RULE: A sentence about money is read into its verb, its amount, what it was for and who it went to; one that opens on its amount is a spend, and one with no amount is not about money.    #[test]    fn a_sentence_about_money_is_read_into_its_parts() {        let spent = money_words("spent 450 on groceries at quay street grocer").unwrap();        assert_eq!(spent.verb, "spent");        assert_eq!(spent.minor_units("INR"), Some(45_000));        assert_eq!(spent.category.as_deref(), Some("groceries"));        assert_eq!(spent.payee.as_deref(), Some("quay street grocer"));        assert_eq!(spent.description(), "Quay street grocer");        let got = money_words("Received ₹1,20,000.50 from Tidewater Pottery for side work").unwrap();        assert_eq!(got.verb, "received");        assert_eq!(got.minor_units("INR"), Some(12_000_050));        assert_eq!(got.payee.as_deref(), Some("Tidewater Pottery"));        assert_eq!(got.category.as_deref(), Some("side work"));        let bare = money_words("180 coffee").unwrap();        assert_eq!(bare.verb, "spent");        assert_eq!(bare.description(), "Coffee");        assert_eq!(bare.minor_units("JPY"), Some(180));        let paid = money_words("spent 37 on tea at the kiosk from Cash").unwrap();        assert_eq!(paid.payee.as_deref(), Some("the kiosk"));        assert_eq!(paid.from.as_deref(), Some("Cash"));        assert_eq!(money_words("lent 500 to").unwrap().verb, "lent");        assert!(money_words("groceries at the corner").is_none());    }    /// RULE: An amount is never rounded into a currency: more decimal places than the currency carries is refused, not cut.    #[test]    fn an_amount_is_never_rounded_into_its_currency() {        let words = money_words("spent 12.5 on tea").unwrap();        assert_eq!(words.minor_units("INR"), Some(1_250));        assert_eq!(words.minor_units("KWD"), Some(12_500));        assert_eq!(words.minor_units("JPY"), None);        assert_eq!(money_words("spent 0 on tea").unwrap().minor_units("INR"), None);    }}