nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Complete stock/profit roles and the supplied continuous EOQ model.
use super::{BusinessQueries, profit, ratio_percent, summary};
use crate::plugins::{compositions::Compositions, finance, integer_queries, model_coordinates};
use crate::{Context, Error, re};
use num_rational::BigRational;
use num_traits::{ToPrimitive, Zero};

fn authored_money(input: &str) -> Option<(BigRational, &'static str)> {
    // Finance owns currency recognition; its literal parser also excludes
    // expressions, which must retain their computed binary64 provenance.
    let (_, currency) = finance::amount(input)?;
    let literal = re!(r"(?i)([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?)").captures(input)?;
    let (numerator, denominator) =
        integer_queries::ratio_value(&literal[1].replace(',', "")).ok()?;
    Some((BigRational::new(numerator, denominator), currency))
}

fn eoq_root(squared: BigRational, engine: &Compositions, context: &Context) -> Result<f64, Error> {
    let complete = model_coordinates::computed_root(squared, |expression| {
        engine.quantity_value(expression, "1", context)
    })?;
    let result = complete
        .to_f64()
        .filter(|value| value.is_finite())
        .ok_or_else(|| Error("numeric_overflow".into()))?;
    if result == 0.0 && !complete.is_zero() {
        return Err(Error("numeric_underflow".into()));
    }
    Ok(result)
}

impl BusinessQueries {
    pub(super) fn lower_inventory(
        &self,
        input: &str,
        context: &Context,
    ) -> Result<Option<String>, Error> {
        if let Some(c) = re!(r"(?i)^a (?:shop|store) buys (.+?) [\p{L}]+ (?:for|at) (.+?) each and pays (?:a )?flat (.+?) freight bill[.;]\s*it sells (.+?)% of them for (.+?) each and the rest for (.+?) each[.;]\s*(?:what are|calculate|find|report|give) (.+)$").captures(input) {
            let bought = self.count(&c[1], context)?;
            let buy_price = self.money(&c[2], false, context)?;
            let freight = self.money(&c[3], false, context)?;
            let share = self.rate(&c[4], true, false, context)?;
            let complement = self.rate(&c[4], true, true, context)?;
            let first_price = self.money(&c[5], false, context)?;
            let remaining_price = self.money(&c[6], false, context)?;
            let first = format!("({bought} * {share})");
            let remaining = format!("({bought} * {complement})");
            self.inventory(&bought, &first, context)?;
            self.inventory(&bought, &remaining, context)?;
            // Both groups refer to the purchased stock; freight is paid once.
            let revenue = format!("({first} * {first_price} + {remaining} * {remaining_price})");
            let cost = format!("({bought} * {buy_price} + {freight})");
            let gross_profit = profit(&revenue, &cost);
            let requested = c[7].to_ascii_lowercase();
            let goals = re!(r"\s*,\s*(?:and\s+)?|\s+and\s+")
                .split(&requested)
                .map(|goal| goal.trim().strip_prefix("the ").unwrap_or(goal.trim()))
                .collect::<Vec<_>>();
            if goals.len() != 3 || !["total sales", "total cost", "gross profit"].iter().all(|goal| goals.contains(goal)) {
                return Err(Error("invalid_expression".into()));
            }
            let fields = goals.into_iter().map(|goal| {
                let expression = match goal {
                    "total sales" => revenue.clone(),
                    "total cost" => cost.clone(),
                    _ => gross_profit.clone(),
                };
                (goal, "m", expression)
            }).collect::<Vec<_>>();
            return Ok(Some(summary(&fields)));
        }
        if let Some(c) = re!(r"(?i)^a warehouse has (.+?) units, ships (.+?)% of them, then receives (.+?) units; report the (final inventory|net percentage change from the starting inventory) and the (final inventory|net percentage change from the starting inventory)$").captures(input) {
            let initial = self.count(&c[1], context)?;
            let retained = self.rate(&c[2], true, true, context)?;
            let received = self.count(&c[3], context)?;
            if self.engine.quantity_value(&initial, "1", context)? == 0.0 {
                return Err(Error("division_by_zero".into()));
            }
            let shipped = format!("({initial} * (1 - {retained}))");
            self.inventory(&initial, &shipped, context)?;
            let final_inventory = format!("({initial} * {retained} + {received})");
            let change = ratio_percent(&format!("({final_inventory} - {initial})"), &initial);
            let goals = [c[4].to_ascii_lowercase(), c[5].to_ascii_lowercase()];
            if goals[0] == goals[1] {
                return Err(Error("invalid_expression".into()));
            }
            let fields = goals.map(|goal| {
                if goal == "final inventory" {
                    ("final inventory", "c", final_inventory.clone())
                } else {
                    ("net change", "p", change.clone())
                }
            });
            return Ok(Some(summary(&fields)));
        }
        if let Some(c) = re!(r"(?i)^a (?:shop|store) buys (.+?) [\p{L}]+ at (.+?) each and sells (?:them|all of them) for (.+?) each; (?:what is|calculate|find) (?:the )?(total gross profit|gross profit|gross margin percentage) and (?:the )?(total gross profit|gross profit|gross margin percentage)$").captures(input) {
            let bought = self.count(&c[1], context)?;
            let buy_price = self.money(&c[2], false, context)?;
            let sell_price = self.money(&c[3], false, context)?;
            // The reference is to all purchased items, so matched cost and
            // revenue use the same validated inventory count.
            self.inventory(&bought, &bought, context)?;
            let revenue = format!("({bought} * {sell_price})");
            self.money(&revenue, true, context)?;
            let cost = format!("({bought} * {buy_price})");
            let gross_profit = profit(&revenue, &cost);
            let goals = [c[4].to_ascii_lowercase(), c[5].to_ascii_lowercase()];
            if (goals[0] == "gross margin percentage") == (goals[1] == "gross margin percentage") {
                return Err(Error("invalid_expression".into()));
            }
            let fields = goals.map(|goal| {
                if goal == "gross margin percentage" {
                    ("margin", "p", ratio_percent(&gross_profit, &revenue))
                } else {
                    ("gross profit", "m", gross_profit.clone())
                }
            });
            return Ok(Some(summary(&fields)));
        }
        if let Some(c) = re!(r"(?i)^a store buys (.+?) units at (.+?) each and sells (.+?) units at (.+?) each; what is gross profit on the units sold, ignoring all other costs$").captures(input) {
            let bought = self.count(&c[1], context)?;
            let buy_price = self.money(&c[2], false, context)?;
            let sold = self.count(&c[3], context)?;
            let sell_price = self.money(&c[4], false, context)?;
            self.inventory(&bought, &sold, context)?;
            return Ok(Some(format!("{sold} * ({sell_price} - {buy_price})")));
        }
        if let Some(c) = re!(r"(?i)^an inventory item has annual demand of (.+?) units, ordering cost of (.+?) per order, and annual holding cost of (.+?) per unit; what is the economic order quantity using the square root of \(2 times demand times ordering cost divided by holding cost\)$").captures(input) {
            self.count(&c[1], context)?;
            self.money(&c[2], false, context)?;
            self.money(&c[3], true, context)?;
            let demand = model_coordinates::read(&c[1], "1", &self.engine, context)?.value;
            let price_ratio = match (authored_money(&c[2]), authored_money(&c[3])) {
                (Some((ordering, first)), Some((holding, second))) => {
                    let currency_ratio = if first == second {
                        BigRational::from_integer(1.into())
                    } else {
                        // A quoted currency is a common-base coordinate with
                        // scale 1/rate. Use only the two supplied currencies;
                        // quote floats retain their actual computed provenance.
                        let quote = |code: &str| {
                            let value = context
                                .rates
                                .get(code)
                                .filter(|rate| rate.is_finite() && **rate > 0.0)
                                .ok_or_else(|| Error("incompatible_units".into()))?;
                            BigRational::from_float(*value)
                                .ok_or_else(|| Error("numeric_overflow".into()))
                        };
                        quote(second)? / quote(first)?
                    };
                    model_coordinates::bounded((ordering / holding) * currency_ratio)?
                }
                _ => {
                    // Computed money must use the typed quotient as a whole:
                    // its currency compatibility and actual binary64 result
                    // come from the shared engine, with no third-currency role.
                    let value = self.engine.quantity_value(
                        &format!("({} / {})", &c[2], &c[3]),
                        "1",
                        context,
                    )?;
                    model_coordinates::bounded(
                        BigRational::from_float(value)
                            .ok_or_else(|| Error("numeric_overflow".into()))?,
                    )?
                }
            };
            let squared = model_coordinates::bounded(
                BigRational::from_integer(2.into()) * demand * price_ratio,
            )?;
            let result = eoq_root(squared, &self.engine, context)?;
            let optimum = format!("(real({result:e}) units)");
            self.engine.quantity_value(&optimum, "units", context)?;
            return Ok(Some(optimum));
        }
        Ok(None)
    }
}