use super::{compositions::Compositions, syntax};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
use std::cmp::Ordering;
mod balances;
mod inventory;
mod prices;
pub(super) fn included_installment_request(input: &str) -> bool {
balances::inclusive_installment_request(input)
}
pub(super) fn staged_coupon_gift_request(input: &str) -> bool {
prices::staged_coupon_gift_request(input)
}
fn coupon_goal_stage(label: &str) -> Option<usize> {
Some(match label {
"original amount" | "purchase amount" => 0,
"coupon value" | "coupon savings" | "discount" | "discount amount" => 1,
"tax base"
| "taxable amount"
| "taxable subtotal"
| "discounted base"
| "coupon-adjusted base"
| "base" => 2,
"tax" => 3,
"taxed total" | "post-tax total" | "after-tax bill" | "post-tax amount"
| "total before card" | "total" => 4,
"card used" | "gift card applied" | "card redemption" | "card amount used"
| "card applied" | "credit applied" | "redemption" => 5,
"remaining due" | "amount due" | "final amount due" | "balance due" | "payable balance"
| "cash due" | "due" => 6,
_ => return None,
})
}
fn included_installment_goal_stage(label: &str) -> Option<usize> {
Some(match label {
"base"
| "pre-tax amount"
| "net amount"
| "net"
| "pre-tax value"
| "net price"
| "tax-exclusive price"
| "pretax value"
| "taxable base" => 0,
"tax" | "included tax" | "embedded tax" | "tax component" => 1,
"remaining balance"
| "post-deposit balance"
| "balance after upfront payment"
| "balance"
| "installment balance"
| "remaining sum" => 2,
"repeated installment"
| "regular installment"
| "first installment"
| "standard installment"
| "regular share"
| "ordinary payment" => 3,
"residual" | "final residual" | "last installment" | "last share" | "final payment"
| "final one" => 4,
_ => return None,
})
}
pub(super) fn simple_interest_fee_request(input: &str) -> Option<regex::Captures<'_>> {
let input = input.trim().trim_end_matches(['?', '.']);
re!(r"(?i)^a business has (.+?) in its account, earns (.+?)% simple annual interest for (.+?) months, and pays a (.+?) fee; what is the ending balance$").captures(input)
}
pub(super) fn fee_priority_request(input: &str) -> bool {
let input = syntax::ungroup(input.trim()).trim_end_matches(['?', '.']);
re!(r"(?i)^an account owes .+?\. apply a .+? late fee first, then a .+? payment; allocate the payment to the fee before principal\. (?:report|give) .+$")
.is_match(input)
|| re!(r"(?i)^a .+? debt receives a .+? fee before a .+? payment, which is allocated first to fees and then principal\. (?:report|give) .+$")
.is_match(input)
}
pub(super) struct PriorityRequest {
payment: String,
categories: String,
both: bool,
credit_label: &'static str,
}
pub(super) fn priority_ledger_request(input: &str) -> Option<PriorityRequest> {
let input = syntax::ungroup(input.trim()).trim_end_matches(['?', '.']);
let forms = [
(
re!(
r"(?i)^allocate a (.+?) payment to (.+?); apply funds in that priority order and report paid and unpaid amounts for each category, with any excess held as account credit$"
),
true,
"account credit",
),
(
re!(
r"(?i)^split a (.+?) payment among (.+?) in that exact priority order; show how much each receives and retain any remaining payment as a customer credit$"
),
false,
"customer credit",
),
(
re!(
r"(?i)^apply (.+?) to balances in this order: (.+?)\. pay each category fully before the next; report the allocation and treat overpayment as a refundable credit$"
),
false,
"refundable credit",
),
(
re!(
r"(?i)^a (.+?) payment must cover (.+?), in that order; give each paid balance and the excess, which stays on the account as credit$"
),
false,
"account credit",
),
];
forms.into_iter().find_map(|(pattern, both, credit_label)| {
let captures = pattern.captures(input)?;
Some(PriorityRequest {
payment: captures[1].to_owned(),
categories: captures[2].to_owned(),
both,
credit_label,
})
})
}
#[derive(Default)]
pub struct BusinessQueries {
engine: Compositions,
}
impl Plugin for BusinessQueries {
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
self.lower(input, context).transpose()
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
syntax::rewrite_groups(input, |part| self.lower(part, context).transpose())
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = syntax::ungroup(input);
if let Some(result) = balances::evaluate_priority(&self.engine, input, context) {
return Some(result);
}
if let Some(result) = balances::evaluate_payment_schedule(&self.engine, input, context) {
return Some(result);
}
if !input.contains("business_summary(") {
return None;
}
Some((|| {
let inner = input
.strip_prefix("business_summary(")
.and_then(|s| s.strip_suffix(')'))
.ok_or_else(|| Error("invalid_expression".into()))?;
let fields = inner.split(';').collect::<Vec<_>>();
let utility_six = fields.len() == 6
&& [
"energy charge|",
"fixed charge|",
"credit|",
"taxable base|",
"tax|",
"total|",
]
.iter()
.all(|label| {
fields
.iter()
.filter(|field| field.starts_with(*label))
.count()
== 1
});
let coupon_six = fields.len() == 6
&& (1..7).all(|stage| {
fields
.iter()
.filter(|field| {
field.split('|').next().and_then(coupon_goal_stage) == Some(stage)
})
.count()
== 1
});
let coupon_seven = fields.len() == 7
&& (0..7).all(|stage| {
fields
.iter()
.filter(|field| {
field.split('|').next().and_then(coupon_goal_stage) == Some(stage)
})
.count()
== 1
});
if !(2..=5).contains(&fields.len()) && !utility_six && !coupon_six && !coupon_seven {
return Err(Error("invalid_expression".into()));
}
let mut output = Vec::new();
for field in fields {
let mut parts = field.splitn(3, '|');
let label = parts.next().unwrap_or_default().trim();
let kind = parts.next().unwrap_or_default().trim();
let expression = parts
.next()
.ok_or_else(|| Error("invalid_expression".into()))?;
let money_label = matches!(
label,
"profit"
| "net profit"
| "cash profit"
| "selling price"
| "cost"
| "profit after fee"
| "gross profit"
| "total sales"
| "total cost"
| "pre-tax price"
| "tax"
| "final amount"
| "total reduction"
| "final price"
| "net sales"
| "commission"
| "payment"
| "remaining principal"
| "energy charge"
| "total bill"
| "subtotal"
| "pre-tax amount"
| "taxable product amount"
| "exempt product amount"
| "grand total"
| "total"
| "original amount"
| "discount"
| "taxable amount"
| "fixed charge"
| "credit"
| "net due"
| "taxable base"
| "fee"
| "payment allocated to fee"
| "payment allocated to principal"
| "remaining fee"
| "principal paid"
| "principal remaining"
| "total amount still owed"
| "gift card applied"
| "cash due"
| "coupon value"
| "purchase amount"
| "coupon savings"
| "discount amount"
| "tax base"
| "taxable subtotal"
| "discounted base"
| "coupon-adjusted base"
| "base"
| "taxed total"
| "post-tax total"
| "after-tax bill"
| "post-tax amount"
| "total before card"
| "card used"
| "card applied"
| "card redemption"
| "card amount used"
| "credit applied"
| "redemption"
| "remaining due"
| "amount due"
| "final amount due"
| "balance due"
| "payable balance"
| "due"
| "net amount"
| "net"
| "pre-tax value"
| "net price"
| "tax-exclusive price"
| "pretax value"
| "included tax"
| "embedded tax"
| "tax component"
| "remaining balance"
| "post-deposit balance"
| "balance after upfront payment"
| "balance"
| "installment balance"
| "remaining sum"
| "repeated installment"
| "regular installment"
| "first installment"
| "standard installment"
| "regular share"
| "ordinary payment"
| "residual"
| "final residual"
| "last installment"
| "last share"
| "final payment"
| "final one"
);
let percent_label = matches!(
label,
"margin"
| "markup"
| "net margin"
| "margin on sales"
| "margin after fees"
| "margin before discount"
| "margin after discount"
| "margin on revenue"
| "net change"
);
let value = if kind == "m" && money_label {
self.engine.evaluate_money(expression, context)?
} else if kind == "n" && label == "item-line count" {
let count = expression
.parse::<u16>()
.ok()
.filter(|count| *count <= 256)
.ok_or_else(|| Error("invalid_expression".into()))?;
count.to_string()
} else if kind == "c" && label == "final inventory" {
let count = self.count(expression, context)?;
self.engine
.evaluate(&format!("{count} * 1 units"), context)
.ok_or_else(|| Error("invalid_expression".into()))??
} else if kind == "p" && percent_label {
self.engine.quantity_value(expression, "1", context)?;
let value = self
.engine
.evaluate(expression, context)
.ok_or_else(|| Error("invalid_expression".into()))??;
format!("{value}%")
} else {
return Err(Error("invalid_expression".into()));
};
let label = if label == "net change" {
"net percentage change"
} else {
label
};
output.push(format!("{label}: {value}"));
}
Ok(output.join("; "))
})())
}
}
fn summary(fields: &[(&str, &str, String)]) -> String {
format!(
"business_summary({})",
fields
.iter()
.map(|(label, kind, expression)| { format!("{label}|{kind}|{expression}") })
.collect::<Vec<_>>()
.join(";")
)
}
fn profit(revenue: &str, cost: &str) -> String {
format!("({revenue} - {cost})")
}
fn ratio_percent(numerator: &str, denominator: &str) -> String {
format!("({numerator} / {denominator}) * 100")
}
impl BusinessQueries {
fn money(&self, input: &str, positive: bool, context: &Context) -> Result<String, Error> {
self.engine.evaluate_money(input, context)?;
let zero = format!("0 * ({input})");
match self.engine.quantity_order(input, &zero, context)? {
Ordering::Less => return Err(Error("invalid_financial_argument".into())),
Ordering::Equal if positive => return Err(Error("division_by_zero".into())),
_ => {}
}
Ok(format!("({input})"))
}
fn count(&self, input: &str, context: &Context) -> Result<String, Error> {
let value = self.engine.quantity_value(input, "1", context)?;
if value < 0.0 {
return Err(Error("invalid_financial_argument".into()));
}
Ok(format!("({input})"))
}
fn rate(
&self,
input: &str,
bounded: bool,
remaining: bool,
context: &Context,
) -> Result<String, Error> {
let value = match super::integer_queries::ratio_value(input) {
Ok((numerator, denominator)) => {
let denominator = denominator * 100;
if numerator.is_negative() || (bounded && numerator > denominator) {
return Err(Error("invalid_financial_rate".into()));
}
let numerator = if remaining {
&denominator - numerator
} else {
numerator
};
let nonzero = !numerator.is_zero();
let value = BigRational::new(numerator, denominator)
.to_f64()
.ok_or_else(|| Error("numeric_overflow".into()))?;
if value == 0.0 && nonzero {
return Err(Error("numeric_underflow".into()));
}
value
}
Err(error)
if matches!(
error.0.as_str(),
"invalid_integer_expression" | "non_rational_expression"
) =>
{
let value = self.engine.quantity_value(input, "1", context)?;
if value < 0.0 || (bounded && value > 100.0) {
return Err(Error("invalid_financial_rate".into()));
}
let fraction = value / 100.0;
if fraction == 0.0 && value != 0.0 {
return Err(Error("numeric_underflow".into()));
}
if remaining { 1.0 - fraction } else { fraction }
}
Err(error) => return Err(error),
};
if !value.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(format!("({value})"))
}
fn margin_price(&self, cost: &str, rate: &str, context: &Context) -> Result<String, Error> {
let cost = self.money(cost, true, context)?;
let remaining = self.rate(rate, true, true, context)?;
if self.engine.quantity_value(&remaining, "1", context)? == 0.0 {
return Err(Error("invalid_financial_rate".into()));
}
Ok(format!("({cost} / {remaining})"))
}
fn tax_profit(
&self,
profit: &str,
rate: &str,
positive_only: bool,
context: &Context,
) -> Result<String, Error> {
let remaining = self.rate(rate, true, true, context)?;
let zero = format!("0 * {profit}");
if positive_only {
Ok(format!(
"(min({profit}, {zero}) + max({profit}, {zero}) * {remaining})"
))
} else if self.engine.quantity_order(profit, &zero, context)? == Ordering::Less {
Err(Error("unsupported_financial_parameters".into()))
} else {
Ok(format!("({profit} * {remaining})"))
}
}
fn inventory(&self, bought: &str, sold: &str, context: &Context) -> Result<(), Error> {
if self.engine.quantity_order(sold, bought, context)? == Ordering::Greater {
Err(Error("invalid_financial_argument".into()))
} else {
Ok(())
}
}
fn lower(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
let input = input.trim().trim_end_matches(['?', '.']);
if let Some(expression) = self.lower_inventory(input, context)? {
return Ok(Some(expression));
}
if let Some(expression) = self.lower_balances(input, context)? {
return Ok(Some(expression));
}
if !re!(
r"(?i)\b(margin|markup|profit|marked up|discount|tax|fee|elasticity|utility|credit)\b"
)
.is_match(input)
{
return Ok(None);
}
if let Some(expression) = self.lower_prices(input, context)? {
return Ok(Some(expression));
}
macro_rules! money {
($c:ident, $n:literal) => {
self.money(&$c[$n], false, context)?
};
($c:ident, $n:literal, positive) => {
self.money(&$c[$n], true, context)?
};
}
macro_rules! rate {
($c:ident, $n:literal) => {
self.rate(&$c[$n], true, false, context)?
};
($c:ident, $n:literal, markup) => {
self.rate(&$c[$n], false, false, context)?
};
($c:ident, $n:literal, remaining) => {
self.rate(&$c[$n], true, true, context)?
};
}
macro_rules! count {
($c:ident, $n:literal) => {
self.count(&$c[$n], context)?
};
}
if let Some(c) = re!(r"(?i)^a product costs (.+?) and sells for (.+?); calculate gross margin percentage and markup percentage$").captures(input) {
let cost=money!(c,1,positive);
let sale=money!(c,2,positive);
let p=profit(&sale,&cost);
return Ok(Some(summary(&[("margin","p",ratio_percent(&p,&sale)),("markup","p",ratio_percent(&p,&cost))])));
}
if let Some(c) =
re!(r"(?i)^what selling price gives a (.+?)% margin on a (.+?) cost$").captures(input)
{
return Ok(Some(self.margin_price(&c[2], &c[1], context)?));
}
if let Some(c) =
re!(r"(?i)^a (.+?) cost is marked up by (.+?)%; what is the selling price$")
.captures(input)
{
let cost = money!(c, 1);
let markup = rate!(c, 2, markup);
return Ok(Some(format!("{cost} * (1 + {markup})")));
}
if let Some(c) =
re!(r"(?i)^revenue is (.+?) and cost is (.+?); find profit and profit margin$")
.captures(input)
{
let revenue = money!(c, 1, positive);
let cost = money!(c, 2);
let p = profit(&revenue, &cost);
return Ok(Some(summary(&[
("profit", "m", p.clone()),
("margin", "p", ratio_percent(&p, &revenue)),
])));
}
if let Some(c) = re!(r"(?i)^compute after-tax profit on (.+?) revenue, (.+?) costs, and (.+?)% tax on positive profit$").captures(input) {
let revenue=money!(c,1);
let cost=money!(c,2);
return Ok(Some(self.tax_profit(&profit(&revenue,&cost),&c[3],true,context)?));
}
if let Some(c) = re!(r"(?i)^markup a (.+?) cost by (.+?)%, discount the resulting price by (.+?)%, then calculate profit and margin$").captures(input) {
let cost=money!(c,1);
let markup=rate!(c,2,markup);
let retained=rate!(c,3,remaining);
let sale=format!("({cost} * (1 + {markup}) * {retained})");
self.money(&sale,true,context)?;
let p=profit(&sale,&cost);
return Ok(Some(summary(&[("profit","m",p.clone()),("margin","p",ratio_percent(&p,&sale))])));
}
if let Some(c) = re!(r"(?i)^a company earns (.+?) revenue, pays (.+?) materials and (.+?) labor, pays a (.+?)% fee on revenue, then (.+?)% tax on remaining profit; calculate net profit and margin$").captures(input) {
let revenue=money!(c,1,positive);
let materials=money!(c,2);
let labor=money!(c,3);
let retained=rate!(c,4,remaining);
let p=format!("({revenue} * {retained} - {materials} - {labor})");
let net=self.tax_profit(&p,&c[5],false,context)?;
return Ok(Some(summary(&[("net profit","m",net.clone()),("net margin","p",ratio_percent(&net,&revenue))])));
}
if let Some(c) = re!(r"(?i)^a shop buys (.+?) units at (.+?) each, sells (.+?) at (.+?) each, and pays a (.+?)% fee on sales; calculate cash profit and margin on sales$").captures(input) {
let bought=count!(c,1);
let buy_price=money!(c,2);
let sold=count!(c,3);
let sell_price=money!(c,4);
let retained=rate!(c,5,remaining);
self.inventory(&bought,&sold,context)?;
let revenue=format!("({sold} * {sell_price})");
self.money(&revenue,true,context)?;
let p=format!("({revenue} * {retained} - {bought} * {buy_price})");
return Ok(Some(summary(&[("cash profit","m",p.clone()),("margin on sales","p",ratio_percent(&p,&revenue))])));
}
if let Some(c) = re!(r"(?i)^a (.+?) item is marked up (.+?)%, then discounted (.+?)%; calculate selling price, profit, and markup on original cost$").captures(input) {
let cost=money!(c,1,positive);
let markup=rate!(c,2,markup);
let retained=rate!(c,3,remaining);
let sale=format!("({cost} * (1 + {markup}) * {retained})");
let p=profit(&sale,&cost);
return Ok(Some(summary(&[("selling price","m",sale),("profit","m",p.clone()),("markup","p",ratio_percent(&p,&cost))])));
}
if let Some(c) = re!(r"(?i)^a (.+?) item is marked up (.+?)%; calculate profit as (.+?)% of the selling price$").captures(input) {
let cost=money!(c,1);
let markup=rate!(c,2,markup);
let claimed=rate!(c,3);
let sale=format!("({cost} * (1 + {markup}))");
let p=profit(&sale,&cost);
if self.engine.quantity_order(&p,&format!("{sale} * {claimed}"),context)? != Ordering::Equal {
return Err(Error("invalid_financial_argument".into()));
}
return Ok(Some(p));
}
if let Some(c) = re!(r"(?i)^for a (.+?) cost and (.+?) sale, calculate markup percentage using profit divided by sale price and margin using profit divided by cost$").captures(input) {
let _cost=money!(c,1,positive);
let _sale=money!(c,2,positive);
return Err(Error("invalid_financial_argument".into()));
}
if let Some(c) = re!(r"(?i)^for a (.+?) cost, set a (.+?)% profit margin and then apply a (.+?)% markup to that selling price; calculate the result$").captures(input) {
let sale=self.margin_price(&c[1],&c[2],context)?;
let markup=rate!(c,3,markup);
return Ok(Some(format!("{sale} * (1 + {markup})")));
}
if let Some(c) = re!(r"(?i)^a shop buys goods for (.+?), adds (.+?)% markup, discounts the sale price by (.+?)%, then pays a (.+?)% fee on proceeds; calculate profit$").captures(input) {
let cost=money!(c,1);
let markup=rate!(c,2,markup);
let discounted=rate!(c,3,remaining);
let retained=rate!(c,4,remaining);
return Ok(Some(format!("({cost} * (1 + {markup}) * {discounted} * {retained}) - {cost}")));
}
if let Some(c) = re!(r"(?i)^a product sells (.+?) units at (.+?) with a (.+?)% fee and costs (.+?) per unit; calculate profit and margin after fees$").captures(input) {
let units=count!(c,1);
let price=money!(c,2);
let retained=rate!(c,3,remaining);
let cost=money!(c,4);
let revenue=format!("({units} * {price})");
self.money(&revenue,true,context)?;
let p=format!("({revenue} * {retained} - {units} * {cost})");
return Ok(Some(summary(&[("profit","m",p.clone()),("margin after fees","p",ratio_percent(&p,&revenue))])));
}
if let Some(c) = re!(r"(?i)^a business has (.+?) revenue, (.+?) cost, (.+?) overhead, and (.+?)% tax on profit after overhead; find net profit$").captures(input) {
let revenue=money!(c,1);
let cost=money!(c,2);
let overhead=money!(c,3);
let p=format!("({revenue} - {cost} - {overhead})");
return Ok(Some(self.tax_profit(&p,&c[4],false,context)?));
}
if let Some(c) = re!(
r"(?i)^a (.+?)% markup on cost produces a (.+?) price; calculate cost and gross margin$"
)
.captures(input)
{
let markup = rate!(c, 1, markup);
let sale = money!(c, 2, positive);
let cost = format!("({sale} / (1 + {markup}))");
let p = profit(&sale, &cost);
return Ok(Some(summary(&[
("cost", "m", cost),
("margin", "p", ratio_percent(&p, &sale)),
])));
}
if let Some(c) = re!(r"(?i)^a company sells (.+?) units at (.+?), incurs (.+?) variable cost each and (.+?) fixed cost; calculate profit and margin$").captures(input) {
let units=count!(c,1);
let price=money!(c,2);
let variable=money!(c,3);
let fixed=money!(c,4);
let revenue=format!("({units} * {price})");
self.money(&revenue,true,context)?;
let p=format!("({revenue} - {units} * {variable} - {fixed})");
return Ok(Some(summary(&[("profit","m",p.clone()),("margin","p",ratio_percent(&p,&revenue))])));
}
if let Some(c) = re!(r"(?i)^a shop buys (.+?) items at (.+?) each, sells (.+?) at (.+?) each, and pays (.+?) fixed fees; calculate realized profit on sold items$").captures(input) {
let bought=count!(c,1);
let cost=money!(c,2);
let sold=count!(c,3);
let price=money!(c,4);
let fixed=money!(c,5);
self.inventory(&bought,&sold,context)?;
return Ok(Some(format!("({sold} * ({price} - {cost})) - {fixed}")));
}
if let Some(c) = re!(r"(?i)^an? (.+?) cost is sold at (.+?); calculate margin, then reduce the sale price by (.+?)% and recalculate margin$").captures(input) {
let cost=money!(c,1);
let before=money!(c,2,positive);
let retained=rate!(c,3,remaining);
let after=format!("({before} * {retained})");
self.money(&after,true,context)?;
return Ok(Some(summary(&[("margin before discount","p",ratio_percent(&profit(&before,&cost),&before)),("margin after discount","p",ratio_percent(&profit(&after,&cost),&after))])));
}
if let Some(c) = re!(r"(?i)^a service earns (.+?) revenue, pays (.+?) labor, a (.+?)% revenue fee, and (.+?)% tax on profit after the fee; calculate net profit$").captures(input) {
let revenue=money!(c,1);
let labor=money!(c,2);
let retained=rate!(c,3,remaining);
let p=format!("({revenue} * {retained} - {labor})");
return Ok(Some(self.tax_profit(&p,&c[4],false,context)?));
}
if let Some(c) = re!(r"(?i)^for a (.+?) cost, calculate selling price at (.+?)% margin, then apply a (.+?)% sales fee; find profit after fee and margin on revenue$").captures(input) {
let cost=money!(c,1);
let sale=self.margin_price(&c[1],&c[2],context)?;
let retained=rate!(c,3,remaining);
let p=format!("({sale} * {retained} - {cost})");
return Ok(Some(summary(&[("selling price","m",sale.clone()),("profit after fee","m",p.clone()),("margin on revenue","p",ratio_percent(&p,&sale))])));
}
if let Some(c) = re!(r"(?i)^a (.+?) project has (.+?)% fee on revenue, (.+?) costs, and (.+?)% tax on positive profit after fee; calculate net profit and net margin$").captures(input) {
let revenue=money!(c,1,positive);
let retained=rate!(c,2,remaining);
let cost=money!(c,3);
let p=format!("({revenue} * {retained} - {cost})");
let net=self.tax_profit(&p,&c[4],true,context)?;
return Ok(Some(summary(&[("net profit","m",net.clone()),("net margin","p",ratio_percent(&net,&revenue))])));
}
Ok(None)
}
}