use super::{BusinessQueries, profit, ratio_percent, summary};
use crate::{Context, Error, re};
use num_bigint::BigInt;
use num_integer::Integer;
use num_rational::BigRational;
use num_traits::Signed;
use std::cmp::Ordering;
fn target_money(expression: &str, target: &str) -> Result<String, Error> {
let currency = crate::plugins::finance::currency(target)
.ok_or_else(|| Error("incompatible_units".into()))?;
Ok(format!("({expression}) in {currency}"))
}
fn round_tax_to_cents(tax: BigRational) -> Result<BigRational, Error> {
if tax.is_negative() {
return Err(Error("invalid_financial_rate".into()));
}
crate::plugins::finance_queries::round_money_to_cents(&tax)
}
struct UtilityRoles<'a> {
consumption: &'a str,
tariff_money: &'a str,
unit: &'a str,
fixed_money: &'a str,
credit_money: &'a str,
}
struct CouponGiftRoles<'a> {
bill: &'a str,
coupon: &'a str,
percent_coupon: bool,
tax_percent: &'a str,
gift: &'a str,
}
fn closed_invoice_shape(input: &str, mut spans: Vec<(usize, usize, &str)>) -> bool {
if input.contains('\0') {
return false;
}
spans.sort_by_key(|span| span.0);
if spans.windows(2).any(|pair| pair[0].1 > pair[1].0) {
return false;
}
let mut source = input.to_owned();
for (start, end, role) in spans.into_iter().rev() {
source.replace_range(start..end, &format!(" \0{role}\0 "));
}
let source = re!(r"[,;.]").replace_all(&source, " ");
let source = re!(r"\s+")
.replace_all(source.trim(), " ")
.to_ascii_lowercase();
let Some((products, tax)) = source.split_once(" \0shipping_role\0 ") else {
return false;
};
if !re!(r"^(?:an invoice lists|prepare an invoice (?:with|for)|invoice|bill|an order has|an order contains|charge) \x00product_role\x00(?: (?:and |plus )?\x00product_role\x00)+(?: (?:and|plus))?$")
.is_match(products)
{
return false;
}
re!(r"^(?:\x00policy_role\x00 )?(?:calculate|apply|use|at|the tax rate is|sales tax is) (?:sales tax of )?\x00rate_role\x00(?: (?:sales tax|tax|only to taxable lines))?(?: and)? (?:round(?:ed)? (?:the )?tax|rounded) half up to (?:the nearest cent|cents) before (?:adding (?:tax|it)(?: to (?:the )?pre-tax total)?|adding to (?:the )?pre-tax total|totaling|computing the final amount|the final addition|total)(?: and)? \x00goal_role\x00$")
.is_match(tax.trim())
}
fn staged_coupon_gift_forms() -> [(&'static regex::Regex, bool, bool); 10] {
[
(
re!(
r"(?i)^bill (.+?) for goods, apply a (.+?)% pre-tax coupon, add (.+?)% sales tax, then use a (.+?) gift card after tax up to the unpaid total\. report (.+)$"
),
false,
true,
),
(
re!(
r"(?i)^take (.+?)% off a (.+?) purchase before (.+?)% sales tax, then apply a (.+?) gift card after tax, capped at the amount owed\. report (.+)$"
),
true,
true,
),
(
re!(
r"(?i)^a (.+?) purchase receives a (.+?)% coupon before (.+?)% sales tax; then apply a (.+?) gift card after tax, capped at the remaining balance\. report (.+)$"
),
false,
true,
),
(
re!(
r"(?i)^on a (.+?) order, take (.+?)% off before (.+?)% tax and then redeem a (.+?) gift card after tax, limited to the balance\. give (.+)$"
),
false,
true,
),
(
re!(
r"(?i)^a (.+?) basket gets a (.+?) coupon before (.+?)% tax; afterward use a (.+?) gift card, capped at the post-tax balance\. state (.+)$"
),
false,
false,
),
(
re!(
r"(?i)^for a (.+?) invoice, subtract a (.+?)% coupon before (.+?)% tax and redeem (.+?) after tax, with gift-card use capped by the post-tax amount\. report (.+)$"
),
false,
true,
),
(
re!(
r"(?i)^a purchase is (.+?); apply (.+?)% off before (.+?)% tax, then a (.+?) credit after tax limited to the outstanding balance\. give (.+)$"
),
false,
true,
),
(
re!(
r"(?i)^goods cost (.+?)\. apply a (.+?) coupon before (.+?)% tax, then spend a (.+?) gift card against the after-tax bill up to that bill\. show (.+)$"
),
false,
false,
),
(
re!(
r"(?i)^a (.+?) service charge is discounted by (.+?)% before (.+?)% tax; after tax, apply a (.+?) card credit capped at the balance\. report (.+)$"
),
false,
true,
),
(
re!(
r"(?i)^the pre-discount merchandise price is (.+?)\. apply (.+?)% off, add (.+?)% tax, then use a (.+?) gift certificate after tax, no more than the amount due; report (.+)$"
),
false,
true,
),
]
}
pub(super) fn staged_coupon_gift_request(input: &str) -> bool {
let input = input.trim().trim_end_matches(['?', '.']);
staged_coupon_gift_forms()
.iter()
.any(|(form, _, _)| form.is_match(input))
}
impl BusinessQueries {
fn coupon_gift_values(
&self,
roles: CouponGiftRoles<'_>,
context: &Context,
) -> Result<(&'static str, [BigRational; 7]), Error> {
let bounded = crate::plugins::model_coordinates::bounded;
let read = crate::plugins::finance_queries::nonnegative_money_coordinate;
let convert = crate::plugins::finance_queries::money_in_currency;
let (bill, code) = read(roles.bill, &self.engine, context)?;
let (gift, gift_code) = read(roles.gift, &self.engine, context)?;
let gift = convert(gift.value, gift_code, code, context)?;
let hundred = BigRational::from_integer(100.into());
let percent = |source: &str| -> Result<BigRational, Error> {
let value =
crate::plugins::model_coordinates::read(source, "1", &self.engine, context)?.value;
if value.is_negative() || value > hundred {
return Err(Error("invalid_financial_rate".into()));
}
Ok(value / &hundred)
};
let coupon = if roles.percent_coupon {
bounded(&bill.value * percent(roles.coupon)?)?
} else {
let (value, source) = read(roles.coupon, &self.engine, context)?;
convert(value.value, source, code, context)?
};
let tax_rate = percent(roles.tax_percent)?;
if [&bill.value, &gift]
.iter()
.any(|value| !(*value * &hundred).is_integer())
|| (!roles.percent_coupon && !(&coupon * &hundred).is_integer())
|| coupon > bill.value
{
return Err(Error("invalid_financial_argument".into()));
}
let original = bill.value;
let base = bounded(&original - &coupon)?;
let tax = round_tax_to_cents(bounded(&base * tax_rate)?)?;
let taxed = bounded(&base + &tax)?;
let applied = if gift < taxed { gift } else { taxed.clone() };
let due = bounded(&taxed - &applied)?;
Ok((code, [original, coupon, base, tax, taxed, applied, due]))
}
fn staged_coupon_gift_report(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
let forms = staged_coupon_gift_forms();
for (form, coupon_first, percent_coupon) in forms {
let Some(c) = form.captures(input) else {
continue;
};
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let (bill, coupon) = if coupon_first {
(&c[2], &c[1])
} else {
(&c[1], &c[2])
};
let goal_text = c[5].trim().to_ascii_lowercase();
let goals = if matches!(
goal_text.as_str(),
"each stage and the remaining amount"
| "all monetary stages and final amount due"
| "every stage through final payment"
) {
[
"original amount",
"coupon value",
"tax base",
"tax",
"taxed total",
"card used",
"remaining due",
]
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>()
} else {
re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
.split(&c[5])
.map(|goal| goal.trim().to_ascii_lowercase())
.collect::<Vec<_>>()
};
if !(2..=7).contains(&goals.len()) {
return Err(Error("invalid_expression".into()));
}
let mut stages = Vec::with_capacity(goals.len());
for goal in &goals {
let stage = super::coupon_goal_stage(goal)
.ok_or_else(|| Error("invalid_expression".into()))?;
if stages.contains(&stage) {
return Err(Error("invalid_expression".into()));
}
stages.push(stage);
}
let (code, values) = self.coupon_gift_values(
CouponGiftRoles {
bill,
coupon,
percent_coupon,
tax_percent: &c[3],
gift: &c[4],
},
context,
)?;
let cents = crate::plugins::finance_queries::round_money_to_cents;
let fields = goals
.iter()
.zip(stages)
.map(|(label, stage)| -> Result<_, Error> {
let value = cents(&values[stage])?;
Ok((
label.as_str(),
"m",
format!("(rational({},{}) {code})", value.numer(), value.denom()),
))
})
.collect::<Result<Vec<_>, _>>()?;
let report = summary(&fields);
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
return Ok(Some(report));
}
Ok(None)
}
fn coupon_gift_report(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
let Some(c) = re!(r"(?i)^a bill is (.+?) before tax\. apply a (.+?) coupon before (.+?)% tax, then a (.+?) gift card after tax; the gift card cannot create a cash refund\. round tax to cents half up\. report (.+)$").captures(input) else {
return Ok(None);
};
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
const LABELS: [&str; 4] = ["taxable amount", "tax", "gift card applied", "cash due"];
let goals = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
.split(&c[5])
.map(|goal| goal.trim().to_ascii_lowercase())
.collect::<Vec<_>>();
if goals.len() != LABELS.len()
|| LABELS
.iter()
.any(|label| goals.iter().filter(|goal| goal.as_str() == *label).count() != 1)
{
return Err(Error("invalid_expression".into()));
}
let (code, [_, _, taxable, tax, _, applied, cash]) = self.coupon_gift_values(
CouponGiftRoles {
bill: &c[1],
coupon: &c[2],
percent_coupon: false,
tax_percent: &c[3],
gift: &c[4],
},
context,
)?;
let values = [
("taxable amount", taxable),
("tax", tax),
("gift card applied", applied),
("cash due", cash),
];
let fields = goals
.iter()
.map(|goal| {
let (label, value) = values.iter().find(|(label, _)| *label == goal).unwrap();
(
*label,
"m",
format!("(rational({},{}) {code})", value.numer(), value.denom()),
)
})
.collect::<Vec<_>>();
for (_, _, expression) in &fields {
self.engine.evaluate_money(expression, context)?;
}
let report = summary(&fields);
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(Some(report))
}
fn discounted_tax_report(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
let Some(c) = re!(r"(?i)^a (.+?) purchase has a (.+?)% discount applied before (.+?)% sales tax;\s*round the discounted merchandise amount to cents,\s*then tax half up to cents,\s*and (?:report|give) (.+)$").captures(input) else {
return Ok(None);
};
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let goals = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
.split(&c[4])
.map(|goal| goal.trim().to_ascii_lowercase())
.collect::<Vec<_>>();
let expected = [
"original amount",
"discount",
"taxable amount",
"tax",
"total",
];
if goals.len() != expected.len()
|| goals.iter().any(|goal| !expected.contains(&goal.as_str()))
|| expected
.iter()
.any(|goal| goals.iter().filter(|found| found.as_str() == *goal).count() != 1)
{
return Err(Error("invalid_expression".into()));
}
let bounded = crate::plugins::model_coordinates::bounded;
let (original, code) = crate::plugins::finance_queries::nonnegative_money_coordinate(
&c[1],
&self.engine,
context,
)?;
let rate = |source: &str| -> Result<BigRational, Error> {
let value =
crate::plugins::model_coordinates::read(source, "1", &self.engine, context)?.value;
if value.is_negative() || value > BigRational::from_integer(100.into()) {
return Err(Error("invalid_financial_rate".into()));
}
Ok(value / BigRational::from_integer(100.into()))
};
let discount_rate = rate(&c[2])?;
let tax_rate = rate(&c[3])?;
let discount = bounded(&original.value * discount_rate)?;
let taxable = crate::plugins::finance_queries::round_money_to_cents(&bounded(
&original.value - &discount,
)?)?;
let tax = round_tax_to_cents(bounded(&taxable * tax_rate)?)?;
let total = bounded(&taxable + &tax)?;
let cents = crate::plugins::finance_queries::round_money_to_cents;
let values = [
("original amount", cents(&original.value)?),
("discount", cents(&discount)?),
("taxable amount", taxable),
("tax", tax),
("total", total),
];
let fields = goals
.iter()
.map(|goal| {
let (label, value) = values
.iter()
.find(|(label, _)| *label == goal.as_str())
.unwrap();
(
*label,
"m",
format!("(rational({},{}) {code})", value.numer(), value.denom()),
)
})
.collect::<Vec<_>>();
for (_, _, expression) in &fields {
self.engine.evaluate_money(expression, context)?;
}
let report = summary(&fields);
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(Some(report))
}
fn utility_values(
&self,
roles: UtilityRoles<'_>,
round_components: bool,
context: &Context,
) -> Result<(&'static str, [BigRational; 4]), Error> {
let UtilityRoles {
consumption,
tariff_money,
unit,
fixed_money,
credit_money,
} = roles;
let bounded = crate::plugins::model_coordinates::bounded;
crate::plugins::model_coordinates::read(
&format!("1 {unit}"),
"kWh",
&self.engine,
context,
)?;
let energy =
crate::plugins::model_coordinates::read(consumption, unit, &self.engine, context)?
.value;
if energy.is_negative() {
return Err(Error("invalid_financial_argument".into()));
}
let (tariff, code) = crate::plugins::finance_queries::nonnegative_money_coordinate(
tariff_money,
&self.engine,
context,
)?;
let (fixed, fixed_code) = crate::plugins::finance_queries::nonnegative_money_coordinate(
fixed_money,
&self.engine,
context,
)?;
let (credit, credit_code) = crate::plugins::finance_queries::nonnegative_money_coordinate(
credit_money,
&self.engine,
context,
)?;
let convert = crate::plugins::finance_queries::money_in_currency;
let mut fixed = convert(fixed.value, fixed_code, code, context)?;
let mut credit = convert(credit.value, credit_code, code, context)?;
if round_components {
let cents = crate::plugins::finance_queries::round_money_to_cents;
fixed = cents(&fixed)?;
credit = cents(&credit)?;
}
let charge = crate::plugins::finance_queries::round_money_to_cents(&bounded(
energy * tariff.value,
)?)?;
let gross = bounded(&charge + &fixed)?;
if credit > gross {
return Err(Error("invalid_financial_argument".into()));
}
let net = bounded(gross - &credit)?;
Ok((code, [charge, fixed, credit, net]))
}
fn utility_bill_report(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
let Some(c) = re!(r"(?i)^(?:calculate|compute|find) a utility bill with (.+?) at (.+?) per ([\p{L}]+), a fixed (.+?) charge, and a (.+?) credit;\s*round energy cost to cents and (?:report|give) (.+)$").captures(input) else {
return Ok(None);
};
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let goal = c[6].trim().to_ascii_lowercase();
if goal != "each component and net due" && goal != "net due and each component" {
return Err(Error("invalid_expression".into()));
}
let (code, amounts) = self.utility_values(
UtilityRoles {
consumption: &c[1],
tariff_money: &c[2],
unit: &c[3],
fixed_money: &c[4],
credit_money: &c[5],
},
false,
context,
)?;
let values = [
("energy charge", &amounts[0]),
("fixed charge", &amounts[1]),
("credit", &amounts[2]),
("net due", &amounts[3]),
];
let order = if goal.starts_with("net due") {
[3, 0, 1, 2]
} else {
[0, 1, 2, 3]
};
let fields = order
.iter()
.map(|index| {
let (label, value) = &values[*index];
(
*label,
"m",
format!("(rational({},{}) {code})", value.numer(), value.denom()),
)
})
.collect::<Vec<_>>();
for (_, _, expression) in &fields {
self.engine.evaluate_money(expression, context)?;
}
let report = summary(&fields);
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(Some(report))
}
fn taxed_utility_bill_report(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
let Some(c) = re!(r"(?i)^an [a-z]+ bill uses (.+?) at (.+?) per ([\p{L}]+), a (.+?) fixed service fee, a (.+?) credit, and (.+?)% tax on energy charge plus service fee after credit\. round each monetary component and the final tax half up to cents; itemize (.+)$").captures(input) else {
return Ok(None);
};
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let goals = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
.split(&c[7])
.map(|goal| match goal.trim().to_ascii_lowercase().as_str() {
"energy" | "energy charge" => Some("energy charge"),
"fee" | "fixed charge" | "fixed service fee" => Some("fixed charge"),
"credit" => Some("credit"),
"taxable base" | "taxable amount" => Some("taxable base"),
"tax" => Some("tax"),
"total" | "amount due" => Some("total"),
_ => None,
})
.collect::<Vec<_>>();
const LABELS: [&str; 6] = [
"energy charge",
"fixed charge",
"credit",
"taxable base",
"tax",
"total",
];
if goals.len() != LABELS.len()
|| LABELS
.iter()
.any(|label| goals.iter().filter(|goal| **goal == Some(*label)).count() != 1)
{
return Err(Error("invalid_expression".into()));
}
let (code, amounts) = self.utility_values(
UtilityRoles {
consumption: &c[1],
tariff_money: &c[2],
unit: &c[3],
fixed_money: &c[4],
credit_money: &c[5],
},
true,
context,
)?;
let rate =
crate::plugins::model_coordinates::read(&c[6], "1", &self.engine, context)?.value;
if rate.is_negative() || rate > BigRational::from_integer(100.into()) {
return Err(Error("invalid_financial_rate".into()));
}
let base = &amounts[3];
let tax = round_tax_to_cents(crate::plugins::model_coordinates::bounded(
base * rate / BigRational::from_integer(100.into()),
)?)?;
let total = crate::plugins::model_coordinates::bounded(base + &tax)?;
let values = [
("energy charge", amounts[0].clone()),
("fixed charge", amounts[1].clone()),
("credit", amounts[2].clone()),
("taxable base", base.clone()),
("tax", tax),
("total", total),
];
let fields = goals
.iter()
.map(|goal| {
let (label, value) = values
.iter()
.find(|(label, _)| Some(*label) == *goal)
.unwrap();
(
*label,
"m",
format!("(rational({},{}) {code})", value.numer(), value.denom()),
)
})
.collect::<Vec<_>>();
for (_, _, expression) in &fields {
self.engine.evaluate_money(expression, context)?;
}
let report = summary(&fields);
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(Some(report))
}
fn invoice_report(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
if !re!(r"(?i)\b(?:invoice|bill|order|charge)\b").is_match(input)
|| !re!(
r"(?i)\b(?:item-line count|product-line count|line count|number of item lines)\b"
)
.is_match(input)
|| !re!(r"(?i)\b(?:shipping|freight|delivery)\b").is_match(input)
{
return Ok(None);
}
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let invalid = || Error("invalid_expression".into());
let goal = re!(r"(?i)\b(?:return|provide|give|report|output|state)\b")
.find_iter(input)
.last()
.ok_or_else(invalid)?;
let requested = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
.split(&input[goal.end()..])
.map(|part| match part.trim().to_ascii_lowercase().as_str() {
"item-line count" | "line count" | "number of item lines" => {
Some("item-line count")
}
"product-line count excluding shipping" => {
Some("product-line count excluding shipping")
}
"taxable product amount" => Some("taxable product amount"),
"exempt product amount" => Some("exempt product amount"),
"pre-tax amount"
| "pre-tax total"
| "pre-tax subtotal"
| "subtotal before tax"
| "subtotal" => Some("pre-tax amount"),
"tax" => Some("tax"),
"grand total" | "final total" | "total due" | "total" | "amount due" => {
Some("grand total")
}
_ => None,
})
.collect::<Vec<_>>();
let split_products = requested.len() == 5;
let required: &[&str] = if split_products {
&[
"taxable product amount",
"exempt product amount",
"tax",
"grand total",
]
} else {
&["pre-tax amount", "tax", "grand total"]
};
if !(4..=5).contains(&requested.len())
|| requested.iter().any(Option::is_none)
|| requested
.iter()
.filter(|goal| {
matches!(
**goal,
Some("item-line count" | "product-line count excluding shipping")
)
})
.count()
!= 1
|| required.iter().any(|label| {
requested
.iter()
.filter(|goal| **goal == Some(*label))
.count()
!= 1
})
|| !re!(r"(?i)\bhalf\s+up\b").is_match(&input[..goal.start()])
{
return Err(invalid());
}
let product = re!(
r"(?i)(?:^|[\s,;])([0-9][0-9,]*(?:\.[0-9]+)?)\s+(taxable|exempt)\s+([a-z][a-z-]*)\s+(?:at|priced)\s+((?:us\$|[$€£¥₿])\s*[0-9][0-9,]*(?:\.[0-9]+)?)(?:\s+each)?\b"
);
let products = product
.captures_iter(&input[..goal.start()])
.collect::<Vec<_>>();
if !(2..=256).contains(&products.len()) {
return Err(invalid());
}
let shipping_count_clause = re!(r"(?i)\bshipping counts as an item line\.");
let shipping_as_line = shipping_count_clause
.find_iter(&input[..goal.start()])
.count();
if shipping_as_line > 1
|| (re!(r"(?i)\bshipping\b[^.;]*\b(?:counts?|item line)\b")
.is_match(&input[..goal.start()])
&& shipping_as_line != 1)
{
return Err(invalid());
}
let product_line_count = products.len();
let line_count = product_line_count + shipping_as_line;
let shipping = [
re!(
r"(?i)\b(taxable|exempt)\s+(?:shipping|delivery|freight)\s+(?:of|costs|is|at)\s+(\$\s*[0-9][0-9,]*(?:\.[0-9]+)?)"
),
re!(
r"(?i)\b(?:shipping|delivery|freight)\s+(?:of|at|is)\s+(\$\s*[0-9][0-9,]*(?:\.[0-9]+)?)\s+is\s+(taxable|exempt)\b"
),
re!(
r"(?i)\b(?:shipping|delivery|freight)\s+is\s+(taxable|exempt)\s+(?:at|and\s+costs)\s+(\$\s*[0-9][0-9,]*(?:\.[0-9]+)?)"
),
re!(
r"(?i)(\$\s*[0-9][0-9,]*(?:\.[0-9]+)?)\s+(taxable|exempt)\s+(?:shipping|delivery|freight)\b"
),
re!(
r"(?i)\b(?:shipping|delivery|freight)\s+costs\s+(\$\s*[0-9][0-9,]*(?:\.[0-9]+)?)\s+and\s+is\s+(taxable|exempt)\b"
),
];
let shipping = shipping
.iter()
.enumerate()
.flat_map(|(index, pattern)| {
pattern.captures_iter(&input[..goal.start()]).map(move |c| {
let span = c.get(0).unwrap();
if index == 0 || index == 2 {
(
c[1].to_ascii_lowercase(),
c[2].to_owned(),
span.start(),
span.end(),
)
} else {
(
c[2].to_ascii_lowercase(),
c[1].to_owned(),
span.start(),
span.end(),
)
}
})
})
.collect::<Vec<_>>();
if shipping.len() != 1 {
return Err(invalid());
}
let rates = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)%")
.captures_iter(&input[..goal.start()])
.collect::<Vec<_>>();
let taxable_scope = re!(r"(?i)\bonly\s+to\s+taxable\s+lines\b")
.find_iter(&input[..goal.start()])
.count();
if rates.len() != 1
|| !re!(r"(?i)\b(?:sales\s+)?tax\b").is_match(&input[..goal.start()])
|| taxable_scope > 1
|| re!(r"(?i)\b(?:taxable|exempt)\b")
.find_iter(&input[..goal.start()])
.count()
!= products.len() + 1 + taxable_scope
|| super::super::finance_queries::money_records()
.find_iter(&input[..goal.start()])
.count()
!= products.len() + 1
{
return Err(invalid());
}
let mut spans = products
.iter()
.map(|product| {
let span = product.get(0).unwrap();
(span.start(), span.end(), "product_role")
})
.collect::<Vec<_>>();
spans.extend([
(shipping[0].2, shipping[0].3, "shipping_role"),
(
rates[0].get(0).unwrap().start(),
rates[0].get(0).unwrap().end(),
"rate_role",
),
(goal.start(), input.len(), "goal_role"),
]);
if shipping_as_line == 1 {
let policy = shipping_count_clause.find(input).unwrap();
spans.push((policy.start(), policy.end(), "policy_role"));
}
if !closed_invoice_shape(input, spans) {
return Err(invalid());
}
let bounded = crate::plugins::model_coordinates::bounded;
let rate =
crate::plugins::model_coordinates::read(&rates[0][1], "1", &self.engine, context)?
.value;
if rate.is_negative() || rate > BigRational::from_integer(100.into()) {
return Err(Error("invalid_financial_rate".into()));
}
let (_, code) = crate::plugins::finance_queries::nonnegative_money_coordinate(
&products[0][4],
&self.engine,
context,
)?;
let convert = crate::plugins::finance_queries::money_in_currency;
let mut subtotal = BigRational::from_integer(0.into());
let mut taxable = BigRational::from_integer(0.into());
let mut taxable_products = BigRational::from_integer(0.into());
let mut exempt_products = BigRational::from_integer(0.into());
for product in products {
let count =
crate::plugins::model_coordinates::read(&product[1], "1", &self.engine, context)?
.value;
if count.is_negative() || !count.is_integer() {
return Err(Error("invalid_financial_argument".into()));
}
let (price, price_code) =
crate::plugins::finance_queries::nonnegative_money_coordinate(
&product[4],
&self.engine,
context,
)?;
let price = convert(price.value, price_code, code, context)?;
let extended = bounded(count * price)?;
subtotal = bounded(subtotal + &extended)?;
if product[2].eq_ignore_ascii_case("taxable") {
taxable_products = bounded(taxable_products + &extended)?;
taxable = bounded(taxable + extended)?;
} else {
exempt_products = bounded(exempt_products + extended)?;
}
}
let (charge, charge_code) = crate::plugins::finance_queries::nonnegative_money_coordinate(
&shipping[0].1,
&self.engine,
context,
)?;
let charge = convert(charge.value, charge_code, code, context)?;
subtotal = bounded(subtotal + &charge)?;
if shipping[0].0 == "taxable" {
taxable = bounded(taxable + charge)?;
}
let tax = round_tax_to_cents(bounded(
taxable * rate / BigRational::from_integer(100.into()),
)?)?;
let total = bounded(&subtotal + &tax)?;
let money =
|value: &BigRational| format!("(rational({},{}) {code})", value.numer(), value.denom());
let fields = requested
.into_iter()
.map(|goal| match goal.unwrap() {
"item-line count" => ("item-line count", "n", line_count.to_string()),
"product-line count excluding shipping" => {
("item-line count", "n", product_line_count.to_string())
}
"pre-tax amount" => ("pre-tax amount", "m", money(&subtotal)),
"taxable product amount" => {
("taxable product amount", "m", money(&taxable_products))
}
"exempt product amount" => ("exempt product amount", "m", money(&exempt_products)),
"tax" => ("tax", "m", money(&tax)),
_ => ("grand total", "m", money(&total)),
})
.collect::<Vec<_>>();
for (_, kind, expression) in &fields {
if *kind == "m" {
self.engine.evaluate_money(expression, context)?;
}
}
Ok(Some(summary(&fields)))
}
pub(super) fn lower_prices(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
if let Some(report) = self.staged_coupon_gift_report(input, context)? {
return Ok(Some(report));
}
if let Some(report) = self.coupon_gift_report(input, context)? {
return Ok(Some(report));
}
if let Some(report) = self.taxed_utility_bill_report(input, context)? {
return Ok(Some(report));
}
if let Some(report) = self.discounted_tax_report(input, context)? {
return Ok(Some(report));
}
if let Some(report) = self.utility_bill_report(input, context)? {
return Ok(Some(report));
}
if let Some(report) = self.invoice_report(input, context)? {
return Ok(Some(report));
}
if let Some(c) = re!(r"(?i)^invoice (.+?) items? at (.+?) each and (.+?) at (.+?) each, with a (.+?) shipping charge that is taxable\. apply (.+?)% tax to the full pre-tax subtotal only, round tax half up to cents, and report subtotal, tax, and total$").captures(input) {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let bounded = crate::plugins::model_coordinates::bounded;
let count = |role: &str| -> Result<BigRational, Error> {
let value = crate::plugins::model_coordinates::read(role, "1", &self.engine, context)?.value;
if value.is_negative() || !value.is_integer() {
return Err(Error("invalid_financial_argument".into()));
}
Ok(value)
};
let first_count = count(&c[1])?;
let second_count = count(&c[3])?;
let (first_price, code) = crate::plugins::finance_queries::nonnegative_money_coordinate(&c[2], &self.engine, context)?;
let (second_price, second_code) = crate::plugins::finance_queries::nonnegative_money_coordinate(&c[4], &self.engine, context)?;
let (shipping, shipping_code) = crate::plugins::finance_queries::nonnegative_money_coordinate(&c[5], &self.engine, context)?;
for role in [&c[4], &c[5]] {
self.engine.quantity_value(role, code, context)?;
}
let convert = crate::plugins::finance_queries::money_in_currency;
let second_price = convert(second_price.value, second_code, code, context)?;
let shipping = convert(shipping.value, shipping_code, code, context)?;
let tax_percent = crate::plugins::model_coordinates::read(&c[6], "1", &self.engine, context)?.value;
if tax_percent.is_negative() || tax_percent > BigRational::from_integer(100.into()) {
return Err(Error("invalid_financial_rate".into()));
}
let subtotal = bounded(bounded(first_count * first_price.value)? + bounded(second_count * second_price)? + shipping)?;
let tax = round_tax_to_cents(bounded(
&subtotal * tax_percent / BigRational::from_integer(100.into()),
)?)?;
let total = bounded(&subtotal + &tax)?;
let money = |value: &BigRational| format!(
"(rational({},{}) {code})", value.numer(), value.denom()
);
let fields = [
("subtotal", "m", money(&subtotal)),
("tax", "m", money(&tax)),
("total", "m", money(&total)),
];
for (_, _, expression) in &fields {
self.engine.evaluate_money(expression, context)?;
}
return Ok(Some(summary(&fields)));
}
if let Some(c) = re!(r"(?i)^a delivery service charges a fixed (.+?) plus (.+?) for each started (.+?)-kilometer block; any positive partial block counts as a full block\. find the fee for (.+)$").captures(input) {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let fixed = self.money(&c[1], false, context)?;
let per_block = self.money(&c[2], false, context)?;
let block = crate::plugins::model_coordinates::read(
&format!("{} kilometers", &c[3]), "km", &self.engine, context,
)?;
let distance = crate::plugins::model_coordinates::read(&c[4], "km", &self.engine, context)?;
if !block.value.is_positive() || distance.value.is_negative() {
return Err(Error("invalid_financial_argument".into()));
}
let ratio = crate::plugins::model_coordinates::bounded(distance.value / block.value)?;
let blocks = ratio.numer().div_ceil(ratio.denom());
let expression = format!("({fixed} + {per_block} * {blocks})");
if expression.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
self.engine.evaluate_money(&expression, context)?;
return Ok(Some(expression));
}
if let Some(c) = re!(r"(?i)^an invoice has taxable items of (.+?) and (.+?), a nontaxable item of (.+?), and sales tax of (.+?)% applied only to taxable items\. find the total, rounding tax to cents$").captures(input) {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let bounded = crate::plugins::model_coordinates::bounded;
let (first, code) = crate::plugins::finance_queries::nonnegative_money_coordinate(&c[1], &self.engine, context)?;
let (second, second_code) = crate::plugins::finance_queries::nonnegative_money_coordinate(&c[2], &self.engine, context)?;
let (exempt, exempt_code) = crate::plugins::finance_queries::nonnegative_money_coordinate(&c[3], &self.engine, context)?;
for role in [&c[2], &c[3]] {
self.engine.quantity_value(role, code, context)?;
}
let second = crate::plugins::finance_queries::money_in_currency(second.value, second_code, code, context)?;
let exempt = crate::plugins::finance_queries::money_in_currency(exempt.value, exempt_code, code, context)?;
let percentage = crate::plugins::model_coordinates::read(&c[4], "1", &self.engine, context)?.value;
if percentage.is_negative() || percentage > BigRational::from_integer(BigInt::from(100)) {
return Err(Error("invalid_financial_rate".into()));
}
let taxable = bounded(first.value + second)?;
let tax = round_tax_to_cents(bounded(
taxable.clone() * percentage / BigRational::from_integer(BigInt::from(100)),
)?)?;
let total = bounded(taxable + tax + exempt)?;
let expression = format!("(rational({},{}) {code})", total.numer(), total.denom());
self.engine.evaluate_money(&expression, context)?;
return Ok(Some(expression));
}
if let Some(c) = re!(r"(?i)^a parking lot charges (.+?) for the first hour and (.+?) for each additional started hour, plus a one-time (.+?) entry fee\. what is the total for (.+)$").captures(input) {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let duration = if let Some(parts) = re!(r"(?i)^(.+? hours?)\s+(.+? minutes?)$").captures(&c[4]) {
let hours = crate::plugins::model_coordinates::read(&parts[1], "hours", &self.engine, context)?;
let minutes = crate::plugins::model_coordinates::read(&parts[2], "hours", &self.engine, context)?;
if hours.value.is_negative() || minutes.value.is_negative() {
return Err(Error("invalid_duration".into()));
}
crate::plugins::model_coordinates::bounded(hours.value + minutes.value)?
} else {
crate::plugins::model_coordinates::read(&c[4], "hours", &self.engine, context)?.value
};
if !duration.is_positive() {
return Err(Error("invalid_duration".into()));
}
let first = self.money(&c[1], false, context)?;
let additional = self.money(&c[2], false, context)?;
let entry = self.money(&c[3], false, context)?;
let blocks = duration.numer().div_ceil(duration.denom());
let expression = format!("({first} + {additional} * {} + {entry})", blocks - 1u8);
if expression.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
self.engine.evaluate_money(&expression, 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)?
};
}
if let Some(c) = re!(r"(?i)^a [\p{L}][\p{L} '-]* uses (.+?) per day for (.+?) at (.+?) plus a fixed (.+?) fee[.;]\s*(?:report|calculate|find) (energy charge and total bill|total bill and energy charge)$").captures(input) {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
for (input, reference) in [(&c[1], "kWh"), (&c[2], "days")] {
let coordinate = crate::plugins::model_coordinates::read(input, reference, &self.engine, context)?;
if coordinate.value.is_negative() {
return Err(Error("invalid_financial_argument".into()));
}
}
self.money(&format!("({}) * (1 kWh)", &c[3]), false, context)?;
let fee = money!(c, 4);
let charge = format!("(({}) / (1 day)) * ({}) * ({})", &c[1], &c[2], &c[3]);
self.money(&charge, false, context)?;
let bill = format!("({charge}) + {fee}");
self.money(&bill, false, context)?;
let fields = if c[5].to_ascii_lowercase().starts_with("energy") {
[("energy charge", "m", charge), ("total bill", "m", bill)]
} else {
[("total bill", "m", bill), ("energy charge", "m", charge)]
};
let result = summary(&fields);
if result.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
return Ok(Some(result));
}
if let Some(c) = re!(r"(?i)^(?:the )?price (rises|falls|changes) from (.+?) to (.+?) and quantity (rises|falls|changes) from (.+?) to (.+?)\. using midpoint percentage changes, (?:calculate|compute|find) elasticity as percentage quantity change divided by percentage price change; (?:give|report) (?:two|2) decimals and preserve sign$").captures(input) {
let price_before = money!(c, 2);
let price_after = money!(c, 3);
let quantity_before = self.count(&c[5], context)?;
let quantity_after = self.count(&c[6], context)?;
let price_order = self.engine.quantity_order(&price_after, &price_before, context)?;
let quantity_order = self.engine.quantity_order(&quantity_after, &quantity_before, context)?;
if price_order == Ordering::Equal
|| (self.engine.quantity_order(&quantity_before, "0", context)? == Ordering::Equal
&& self.engine.quantity_order(&quantity_after, "0", context)? == Ordering::Equal)
{
return Err(Error("division_by_zero".into()));
}
for (direction, order) in [(&c[1], price_order), (&c[4], quantity_order)] {
let agrees = match direction.to_ascii_lowercase().as_str() {
"rises" => order == Ordering::Greater,
"falls" => order == Ordering::Less,
"changes" => true,
_ => false,
};
if !agrees {
return Err(Error("invalid_financial_argument".into()));
}
}
let quantity_change = format!("(({quantity_after} - {quantity_before}) / (({quantity_before} + {quantity_after}) / 2))");
let price_change = format!("(({price_after} - {price_before}) / (({price_before} + {price_after}) / 2))");
return Ok(Some(format!("round({quantity_change} / {price_change}, 2)")));
}
if let Some(c) = re!(r"(?i)^a metal part costing (.+?) has a (.+?)% markup on cost, then a (.+?)% discount on marked price\. what is the final price in (.+?)$").captures(input) {
let cost=money!(c,1);
let markup=rate!(c,2,markup);
let retained=rate!(c,3,remaining);
return Ok(Some(target_money(&format!("{cost} * (1 + {markup}) * {retained}"),&c[4])?));
}
if let Some(c) = re!(r"(?i)^an item sells for (.+?) at a (.+?)% gross margin on selling price\. find its cost and gross profit in (.+?)$").captures(input) {
let sale=money!(c,1,positive);
let retained=rate!(c,2,remaining);
let cost=format!("({sale} * {retained})");
let p=profit(&sale,&cost);
return Ok(Some(summary(&[("cost","m",target_money(&cost,&c[3])?),("gross profit","m",target_money(&p,&c[3])?)])));
}
if let Some(c) = re!(r"(?i)^an object costs (.+?); apply a (.+?)% markup on cost and then (.+?)% sales tax on the marked price\. give final (.+?) price$").captures(input) {
let cost=money!(c,1);
let markup=rate!(c,2,markup);
let tax=rate!(c,3);
return Ok(Some(target_money(&format!("{cost} * (1 + {markup}) * (1 + {tax})"),&c[4])?));
}
if let Some(c) = re!(r"(?i)^a (.+?) item receives a (.+?)% discount and then a (.+?)% tax on the discounted price\. find final price in (.+?)$").captures(input) {
let price=money!(c,1);
let retained=rate!(c,2,remaining);
let tax=rate!(c,3);
return Ok(Some(target_money(&format!("{price} * {retained} * (1 + {tax})"),&c[4])?));
}
if let Some(c) = re!(r"(?i)^a merchant buys for (.+?) and sells for (.+?)\. calculate profit, margin as a percentage of selling price, and markup as a percentage of cost$").captures(input) {
let cost=money!(c,1,positive);
let sale=money!(c,2,positive);
let p=profit(&sale,&cost);
return Ok(Some(summary(&[("profit","m",p.clone()),("margin","p",ratio_percent(&p,&sale)),("markup","p",ratio_percent(&p,&cost))])));
}
if let Some(c) = re!(r"(?i)^a (.+?) sale includes a (.+?)% tax calculated on the pre-tax price\. find the pre-tax price and tax amount$").captures(input) {
let total=money!(c,1);
let tax=rate!(c,2);
let base=format!("({total} / (1 + {tax}))");
let amount=format!("({total} * {tax} / (1 + {tax}))");
return Ok(Some(summary(&[("pre-tax price","m",base),("tax","m",amount)])));
}
if let Some(c) = re!(r"(?i)^an item[’']s pre-tax price is (.+?), with (.+?)% tax, then a (.+?)% payment fee applied to the tax-inclusive total\. what is the final (.+?) charge$").captures(input) {
let base=money!(c,1);
let tax=rate!(c,2);
let fee=rate!(c,3);
return Ok(Some(target_money(&format!("{base} * (1 + {tax}) * (1 + {fee})"),&c[4])?));
}
if let Some(c) = re!(r"(?i)^price is (.+?) before a (.+?)% discount; a (.+?)% fee then applies to the discounted amount\. report final (.+?) amount and total reduction from original$").captures(input) {
let original=money!(c,1);
let retained=rate!(c,2,remaining);
let fee=rate!(c,3);
let final_price=format!("({original} * {retained} * (1 + {fee}))");
let reduction=profit(&original,&final_price);
return Ok(Some(summary(&[("final amount","m",target_money(&final_price,&c[4])?),("total reduction","m",target_money(&reduction,&c[4])?)])));
}
if let Some(c) = re!(r"(?i)^a service costs (.+?)\. apply a (.+?)% markup on cost, then a (.+?)% discount on marked price, then (.+?)% tax on the discounted price\. give the customer total$").captures(input) {
let cost=money!(c,1);
let markup=rate!(c,2,markup);
let retained=rate!(c,3,remaining);
let tax=rate!(c,4);
return Ok(Some(format!("{cost} * (1 + {markup}) * {retained} * (1 + {tax})")));
}
if let Some(c) = re!(r"(?i)^an item is discounted by (.+?)% from (.+?), then a (.+?)% fee is added\. compute the net price in (.+?) using ([a-z]{3})=(.+?) per common base and ([a-z]{3})=(.+?)$").captures(input) {
let original=money!(c,2);
let retained=rate!(c,1,remaining);
let fee=rate!(c,3);
crate::plugins::finance::validate_supplied_rate(&c[5],&c[6],&self.engine,context)?;
crate::plugins::finance::validate_supplied_rate(&c[7],&c[8],&self.engine,context)?;
return Ok(Some(target_money(&format!("{original} * {retained} * (1 + {fee})"),&c[4])?));
}
if let Some(c) = re!(r"(?i)^a seller wants a (.+?)% margin on a product that costs (.+?)\. find the selling price and profit$").captures(input) {
let cost=money!(c,2);
let sale=self.margin_price(&c[2],&c[1],context)?;
let p=profit(&sale,&cost);
return Ok(Some(summary(&[("selling price","m",sale),("profit","m",p)])));
}
if let Some(c) = re!(r"(?i)^an item sells for (.+?) after a (.+?)% discount from its original price; calculate the discount amount without knowing the original price$").captures(input) {
let net=money!(c,1);
let retained=rate!(c,2,remaining);
let discount=rate!(c,2);
if self.engine.quantity_value(&retained,"1",context)?==0.0 {
return Err(Error("invalid_financial_rate".into()));
}
return Ok(Some(format!("({net} * {discount} / {retained})")));
}
if let Some(c) = re!(r"(?i)^a (.+?) purchase has a (.+?)% fee and a (.+?)% tax, but the fee and tax are each assessed on the other charge only\. find the total$").captures(input) {
let purchase=money!(c,1);
let fee_remaining=rate!(c,2,remaining);
let tax_remaining=rate!(c,3,remaining);
if self.engine.quantity_value(&fee_remaining,"1",context)?==0.0 && self.engine.quantity_value(&tax_remaining,"1",context)?==0.0 {
return Err(Error("invalid_financial_argument".into()));
}
return Ok(Some(purchase));
}
if let Some(c) = re!(r"(?i)^a (.+?) sale with (.+?)% tax on the pre-tax price: calculate the tax as (.+?)% of the tax-inclusive sale instead$").captures(input) {
let total=money!(c,1);
let _original_rate=rate!(c,2);
let selected_rate=rate!(c,3);
return Ok(Some(format!("{total} * {selected_rate}")));
}
Ok(None)
}
}