use super::{BusinessQueries, ratio_percent, summary};
use crate::{Context, Error, re};
use num_bigint::BigInt;
use num_integer::Integer;
use num_rational::BigRational;
use num_traits::{Signed, Zero};
fn exact(value: &BigRational) -> String {
format!("rational({},{})", value.numer(), value.denom())
}
fn payment_count(input: &str, ordinal: bool) -> Result<usize, Error> {
let word = input.trim().to_ascii_lowercase();
let names = if ordinal {
[
"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
"tenth", "eleventh", "twelfth",
]
} else {
[
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve",
]
};
let (number, suffix) = if let Some(index) = names.iter().position(|name| *name == word) {
(BigInt::from(index + 1), None)
} else if ordinal {
let c = re!(r"^([0-9]+)(st|nd|rd|th)$")
.captures(&word)
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
(
crate::plugins::integer_queries::value(&c[1])?,
Some(c[2].to_owned()),
)
} else {
(crate::plugins::integer_queries::value(&word)?, None)
};
let count = crate::plugins::integer_queries::bounded(&number, 256)? as usize;
if count == 0 {
return Err(Error("invalid_financial_argument".into()));
}
if let Some(suffix) = suffix {
let expected = if (11..=13).contains(&(count % 100)) {
"th"
} else {
match count % 10 {
1 => "st",
2 => "nd",
3 => "rd",
_ => "th",
}
};
if suffix != expected {
return Err(Error("invalid_financial_argument".into()));
}
}
Ok(count)
}
fn installment_shares(
unpaid: BigRational,
count: usize,
) -> Result<(BigRational, BigRational), Error> {
let unpaid_cents =
crate::plugins::model_coordinates::bounded(unpaid * BigRational::from_integer(100.into()))?;
if !unpaid_cents.is_integer() {
return Err(Error("invalid_financial_argument".into()));
}
let unpaid_cents = unpaid_cents.to_integer();
let n = BigInt::from(count);
let (regular_cents, fraction) = unpaid_cents.div_rem(&n);
let regular_cents = regular_cents + if fraction * 2u8 >= n { 1u8 } else { 0u8 };
let final_cents = &unpaid_cents - ®ular_cents * BigInt::from(count - 1);
if final_cents.is_negative() {
return Err(Error("invalid_financial_argument".into()));
}
Ok((
BigRational::new(regular_cents, 100.into()),
BigRational::new(final_cents, 100.into()),
))
}
pub(super) fn evaluate_payment_schedule(
engine: &crate::plugins::compositions::Compositions,
input: &str,
context: &Context,
) -> crate::Outcome {
let inner = input
.strip_prefix("business_payment_schedule(")?
.strip_suffix(')')?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let fields = inner.split('|').collect::<Vec<_>>();
let [code, now, count, regular, final_payment] = fields.as_slice() else {
return Err(Error("invalid_expression".into()));
};
if crate::plugins::finance::currency(code).is_none() {
return Err(Error("incompatible_units".into()));
}
let count = count
.parse::<u16>()
.ok()
.filter(|count| (1..=256).contains(count))
.ok_or_else(|| Error("invalid_financial_argument".into()))?
as usize;
let read = |source: &str| -> Result<BigRational, Error> {
let (n, d) = crate::plugins::integer_queries::ratio_value(source)?;
if d.is_zero() {
return Err(Error("invalid_financial_argument".into()));
}
let amount = BigRational::new(n, d);
if amount.is_negative() || !(amount.clone() * BigInt::from(100u8)).is_integer() {
return Err(Error("invalid_financial_argument".into()));
}
Ok(amount)
};
let now = read(now)?;
let regular = read(regular)?;
let final_payment = read(final_payment)?;
let display = |amount: &BigRational| {
engine.evaluate_money(&format!("({} {code})", exact(amount)), context)
};
let mut output = vec![format!("payment now: {}", display(&now)?)];
for index in 1..=count {
let value = if index == count {
&final_payment
} else {
®ular
};
output.push(format!("month {index} payment: {}", display(value)?));
}
let total = crate::plugins::model_coordinates::bounded(
now + regular * BigInt::from(count - 1) + final_payment,
)?;
output.push(format!("total paid: {}", display(&total)?));
let report = output.join("; ");
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(report)
})())
}
fn priority_categories(input: &str) -> Result<Vec<(String, String)>, Error> {
let invalid = || Error("invalid_financial_argument".into());
let pieces = re!(r"(?i),\s+(?:(?:and|then to)\s+)?")
.split(input)
.collect::<Vec<_>>();
if !(2..=256).contains(&pieces.len()) {
return Err(invalid());
}
let mut categories = Vec::with_capacity(pieces.len());
for (index, piece) in pieces.into_iter().enumerate() {
let piece = piece.trim();
let money = crate::plugins::finance_queries::money_records()
.find(piece)
.ok_or_else(invalid)?;
if !matches!(
piece[..money.start()].trim().to_ascii_lowercase().as_str(),
"" | "a" | "an" | "to"
) {
return Err(invalid());
}
let mut name = piece[money.end()..].trim().to_ascii_lowercase();
if let Some(before) = name.strip_suffix(" first") {
if index != 0 {
return Err(invalid());
}
name = before.to_owned();
}
if let Some(after) = name
.strip_prefix("of ")
.or_else(|| name.strip_prefix("in "))
{
name = after.to_owned();
}
if name.is_empty()
|| name.len() > 64
|| !re!(r"^[a-z]+(?: [a-z]+)*$").is_match(&name)
|| categories.iter().any(|(prior, _)| prior == &name)
{
return Err(invalid());
}
categories.push((name, money.as_str().trim().to_owned()));
}
Ok(categories)
}
pub(super) fn evaluate_priority(
engine: &crate::plugins::compositions::Compositions,
input: &str,
context: &Context,
) -> crate::Outcome {
let inner = input
.strip_prefix("business_priority_ledger(")?
.strip_suffix(')')?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let fields = inner.splitn(5, '|').collect::<Vec<_>>();
let [code, mode, credit_label, credit, entries] = fields.as_slice() else {
return Err(Error("invalid_expression".into()));
};
if crate::plugins::finance::currency(code).is_none()
|| !matches!(*mode, "both" | "paid")
|| !matches!(
*credit_label,
"account credit" | "customer credit" | "refundable credit"
)
{
return Err(Error("invalid_expression".into()));
}
let parts = entries.split(';').collect::<Vec<_>>();
if !(2..=256).contains(&parts.len()) {
return Err(Error("invalid_expression".into()));
}
let value = |expression: &str| -> Result<String, Error> {
let (n, d) = crate::plugins::integer_queries::ratio_value(expression)?;
if d == 0.into() {
return Err(Error("invalid_financial_argument".into()));
}
let amount = BigRational::new(n, d);
if amount.is_negative() {
return Err(Error("invalid_financial_argument".into()));
}
engine.evaluate_money(&format!("({} {code})", exact(&amount)), context)
};
let mut seen = Vec::new();
let mut output = Vec::new();
for part in parts {
let fields = part.split('~').collect::<Vec<_>>();
let [name, paid, unpaid] = fields.as_slice() else {
return Err(Error("invalid_expression".into()));
};
if name.len() > 64
|| !re!(r"^[a-z]+(?: [a-z]+)*$").is_match(name)
|| seen.contains(name)
{
return Err(Error("invalid_expression".into()));
}
seen.push(*name);
output.push(format!("{name} paid: {}", value(paid)?));
if *mode == "both" {
output.push(format!("{name} unpaid: {}", value(unpaid)?));
} else {
value(unpaid)?;
}
}
output.push(format!("{credit_label}: {}", value(credit)?));
let report = output.join("; ");
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(report)
})())
}
fn inclusive_installment_forms() -> [&'static regex::Regex; 10] {
[
re!(
r"(?i)^the tax-inclusive invoice is (.+?) at (.+?)% tax\. pay (.+?) now, then divide the balance into (.+?) installments with the first (.+?) rounded individually to cents using half-up rounding and the (.+?) equal to the exact residual\. report (.+)$"
),
re!(
r"(?i)^an invoice total of (.+?) already includes (.+?)% tax\. the customer pays (.+?) upfront; split the remainder into (.+?) equal-cent installments by rounding each of the first (.+?) installments to the nearest cent, half up, and make installment (.+?) the exact residual\. report (.+)$"
),
re!(
r"(?i)^a tax-inclusive bill of (.+?) includes (.+?)% tax\. after a (.+?) deposit, charge (.+?) monthly installments: round each of the first (.+?) equal shares to the nearest cent, half up, and set the (.+?) to the exact remaining cents\. give (.+)$"
),
re!(
r"(?i)^a final amount of (.+?) includes (.+?)% tax\. deduct an upfront payment of (.+?) and split the rest into (.+?) payments: round the first (.+?) equal portions to cents half up and make payment (.+?) the exact residual\. find (.+)$"
),
re!(
r"(?i)^an invoice of (.+?) includes (.+?)% tax\. the payer makes a (.+?) initial payment and chooses (.+?) equal monthly installments; round each of the first (.+?) portions to cents half up and assign the (.+?) the exact leftover\. return (.+)$"
),
re!(
r"(?i)^a (.+?) tax-inclusive total has a (.+?)% tax rate\. after paying (.+?) in advance, split the rest into (.+?) installments; round the first (.+?) equal shares half up to cents and set the (.+?) to the exact residual\. report (.+)$"
),
re!(
r"(?i)^for a (.+?) total including (.+?)% tax, a (.+?) upfront payment leaves an amount for (.+?) installments\. round the first (.+?) equal installments to the nearest cent with half-up ties and make the (.+?) exactly the residual; calculate (.+)$"
),
re!(
r"(?i)^a (.+?) tax-inclusive charge at (.+?)% is partly paid with (.+?) upfront\. divide the rest among (.+?) monthly payments, rounding the first (.+?) equal portions to cents half up and making the (.+?) the exact residual\. give (.+)$"
),
re!(
r"(?i)^a (.+?) tax-inclusive invoice includes tax at (.+?)%\. subtract a (.+?) down payment, then split what remains into (.+?) installments: round the first (.+?) to cents half up and make the (.+?) the exact residual\. report (.+)$"
),
re!(
r"(?i)^the grand total is (.+?) inclusive of (.+?)% tax\. a (.+?) deposit is paid; the remaining amount is allocated to (.+?) installments, first (.+?) rounded independently to cents half up, final (.+?) set to the residual\. calculate (.+)$"
),
]
}
pub(super) fn inclusive_installment_request(input: &str) -> bool {
let input = input.trim().trim_end_matches(['?', '.']);
inclusive_installment_forms()
.iter()
.any(|form| form.is_match(input))
}
impl BusinessQueries {
fn inclusive_installment_report(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
let forms = inclusive_installment_forms();
for form in forms {
let Some(c) = form.captures(input) else {
continue;
};
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let count = payment_count(&c[4], false)?;
let first = if matches!(c[5].to_ascii_lowercase().as_str(), "0" | "zero") {
0
} else if c[5].eq_ignore_ascii_case("half") && count == 2 {
1
} else {
payment_count(&c[5], false)?
};
let final_count = if c[6].eq_ignore_ascii_case("one")
&& input
.to_ascii_lowercase()
.contains("final one set to the residual")
{
count
} else {
payment_count(&c[6], true).or_else(|_| payment_count(&c[6], false))?
};
if first + 1 != count || final_count != count {
return Err(Error("invalid_financial_argument".into()));
}
let clauses = re!(r"(?i),\s*(?:and\s+)?|\s+and\s+")
.split(&c[7])
.map(|goal| goal.trim().to_ascii_lowercase())
.collect::<Vec<_>>();
let mut goals = Vec::new();
for clause in clauses {
if matches!(
clause.as_str(),
"both installment amounts"
| "installments"
| "each payment"
| "installment amounts"
) {
goals.push("repeated installment".to_owned());
goals.push("residual".to_owned());
} else {
goals.push(clause.strip_prefix("the ").unwrap_or(&clause).to_owned());
}
}
if goals.len() != 5 {
return Err(Error("invalid_expression".into()));
}
let mut stages = Vec::with_capacity(5);
for goal in &goals {
let stage = super::included_installment_goal_stage(goal)
.ok_or_else(|| Error("invalid_expression".into()))?;
if stages.contains(&stage) {
return Err(Error("invalid_expression".into()));
}
stages.push(stage);
}
let bounded = crate::plugins::model_coordinates::bounded;
let rate =
crate::plugins::model_coordinates::read(&c[2], "1", &self.engine, context)?.value;
if rate.is_negative() || rate > BigRational::from_integer(100.into()) {
return Err(Error("invalid_financial_rate".into()));
}
let read = crate::plugins::finance_queries::nonnegative_money_coordinate;
let (gross, code) = read(&c[1], &self.engine, context)?;
let (upfront, upfront_code) = read(&c[3], &self.engine, context)?;
let upfront = crate::plugins::finance_queries::money_in_currency(
upfront.value,
upfront_code,
code,
context,
)?;
let hundred = BigRational::from_integer(100.into());
if !(&gross.value * &hundred).is_integer()
|| !(&upfront * &hundred).is_integer()
|| upfront > gross.value
{
return Err(Error("invalid_financial_argument".into()));
}
let factor = bounded(&hundred + &rate)?;
let base = bounded(&gross.value * &hundred / &factor)?;
let tax = bounded(&gross.value * &rate / factor)?;
let balance = bounded(&gross.value - upfront)?;
let (regular, residual) = installment_shares(balance.clone(), count)?;
let values = [base, tax, balance, regular, residual];
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!("({} {code})", exact(&value))))
})
.collect::<Result<Vec<_>, _>>()?;
let report = summary(&fields);
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
return Ok(Some(report));
}
Ok(None)
}
pub(super) fn lower_balances(
&self,
input: &str,
context: &Context,
) -> Result<Option<String>, Error> {
if let Some(report) = self.inclusive_installment_report(input, context)? {
return Ok(Some(report));
}
if let Some(c) = re!(r"(?i)^an invoice totals (.+?) including (.+?)% tax\. a customer pays (.+?) now and makes (.+?) equal end-of-month payments on the unpaid balance, with no interest\. round the equal payment to cents half up, make the (.+?) payment the exact remaining cents, and report all payments and their sum$").captures(input) {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let count = payment_count(&c[4], false)?;
let final_ordinal = payment_count(&c[5], true)?;
let bounded = crate::plugins::model_coordinates::bounded;
let rate = crate::plugins::model_coordinates::read(
&c[2], "1", &self.engine, context,
)?.value;
if rate.is_negative() || rate > BigRational::from_integer(100.into()) {
return Err(Error("invalid_financial_rate".into()));
}
let read = crate::plugins::finance_queries::nonnegative_money_coordinate;
let (gross, code) = read(&c[1], &self.engine, context)?;
let (now, now_code) = read(&c[3], &self.engine, context)?;
let now = crate::plugins::finance_queries::money_in_currency(
now.value, now_code, code, context,
)?;
let cents = BigRational::from_integer(100.into());
if !(gross.value.clone() * ¢s).is_integer()
|| !(now.clone() * ¢s).is_integer()
|| now > gross.value
{
return Err(Error("invalid_financial_argument".into()));
}
if final_ordinal != count {
return Err(Error("invalid_financial_argument".into()));
}
let (regular, final_payment) = installment_shares(bounded(&gross.value - &now)?, count)?;
let carrier = format!(
"business_payment_schedule({code}|{}|{count}|{}|{})",
exact(&now), exact(®ular), exact(&final_payment),
);
if carrier.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
return Ok(Some(carrier));
}
if let Some(request) = super::priority_ledger_request(input) {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let categories = priority_categories(&request.categories)?;
let read = crate::plugins::finance_queries::nonnegative_money_coordinate;
let convert = crate::plugins::finance_queries::money_in_currency;
let bounded = crate::plugins::model_coordinates::bounded;
let (payment, code) = read(&request.payment, &self.engine, context)?;
let mut amounts = Vec::with_capacity(categories.len());
for (name, expression) in categories {
let (amount, source) = read(&expression, &self.engine, context)?;
amounts.push((name, convert(amount.value, source, code, context)?));
}
let mut remaining = payment.value;
let mut fields = Vec::with_capacity(amounts.len());
for (name, owed) in amounts {
let paid = if remaining < owed {
remaining.clone()
} else {
owed.clone()
};
let unpaid = bounded(&owed - &paid)?;
remaining = bounded(remaining - &paid)?;
fields.push(format!("{name}~{}~{}", exact(&paid), exact(&unpaid)));
}
let carrier = format!(
"business_priority_ledger({code}|{}|{}|{}|{})",
if request.both { "both" } else { "paid" },
request.credit_label,
exact(&remaining),
fields.join(";")
);
if carrier.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
return Ok(Some(carrier));
}
if super::fee_priority_request(input) {
let c = re!(r"(?i)^an account owes (.+?)\. apply a (.+?) late fee first, then a (.+?) payment; allocate the payment to the fee before principal\. (?:report|give) (.+)$")
.captures(input)
.or_else(|| re!(r"(?i)^a (.+?) debt receives a (.+?) fee before a (.+?) payment, which is allocated first to fees and then principal\. (?:report|give) (.+)$").captures(input))
.ok_or_else(|| Error("invalid_expression".into()))?;
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<_>>();
const FIRST: [&str; 4] = [
"fee",
"payment allocated to fee",
"payment allocated to principal",
"remaining principal",
];
const SECOND: [&str; 4] = [
"remaining fee",
"principal paid",
"principal remaining",
"total amount still owed",
];
if goals.len() != 4
|| ![FIRST, SECOND].iter().any(|set| {
set.iter().all(|goal| {
goals.iter().filter(|found| found.as_str() == *goal).count() == 1
})
})
{
return Err(Error("invalid_expression".into()));
}
let read = crate::plugins::finance_queries::nonnegative_money_coordinate;
let (principal, code) = read(&c[1], &self.engine, context)?;
let (fee, fee_code) = read(&c[2], &self.engine, context)?;
let (payment, payment_code) = read(&c[3], &self.engine, context)?;
let convert = crate::plugins::finance_queries::money_in_currency;
let bounded = crate::plugins::model_coordinates::bounded;
let fee = convert(fee.value, fee_code, code, context)?;
let payment = convert(payment.value, payment_code, code, context)?;
if payment > bounded(&principal.value + &fee)? {
return Err(Error("invalid_financial_argument".into()));
}
let paid_fee = if payment < fee {
payment.clone()
} else {
fee.clone()
};
let paid_principal = bounded(&payment - &paid_fee)?;
let remaining_fee = bounded(&fee - &paid_fee)?;
let remaining_principal = bounded(&principal.value - &paid_principal)?;
let total_owed = bounded(&remaining_fee + &remaining_principal)?;
let values = [
("fee", fee),
("payment allocated to fee", paid_fee),
("payment allocated to principal", paid_principal.clone()),
("remaining principal", remaining_principal.clone()),
("remaining fee", remaining_fee),
("principal paid", paid_principal),
("principal remaining", remaining_principal),
("total amount still owed", total_owed),
];
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()));
}
return Ok(Some(report));
}
if let Some(c) = re!(r"(?i)^a caf(?:é|e) starts with (.+?) cash, receives (.+?) in sales, pays (.+?) for supplies and (.+?) for delivery, then refunds (.+?); what is the ending cash balance$").captures(input) {
let initial = self.money(&c[1], false, context)?;
let sales = self.money(&c[2], false, context)?;
let supplies = self.money(&c[3], false, context)?;
let delivery = self.money(&c[4], false, context)?;
let refund = self.money(&c[5], false, context)?;
let balance = format!("({initial} + {sales} - {supplies} - {delivery} - {refund})");
self.engine.evaluate_money(&balance, context)?;
return Ok(Some(balance));
}
if let Some(c) = super::simple_interest_fee_request(input) {
let principal = self.money(&c[1], false, context)?;
self.rate(&c[2], false, false, context)?;
let months = self.count(&c[3], context)?;
let fee = self.money(&c[4], false, context)?;
let balance = format!(
"({principal} * (1 + ({}) / 100 * {months} / 12) - {fee})",
&c[2]
);
self.engine.evaluate_money(&balance, context)?;
return Ok(Some(balance));
}
if let Some(c) = re!(r"(?i)^a (.+?) price is reduced by (.+?)%, then the discounted price is increased by (.+?)%; what is the final price and net percentage change from (.+)$").captures(input) {
let original = self.money(&c[1], false, context)?;
let reference = self.money(&c[4], true, context)?;
self.rate(&c[2], true, false, context)?;
self.rate(&c[3], false, false, context)?;
let final_price = format!("({original} * (1 - ({})/100) * (1 + ({})/100))", &c[2], &c[3]);
return Ok(Some(summary(&[
("final price", "m", final_price.clone()),
("net change", "p", ratio_percent(&format!("({final_price} - {reference})"), &reference)),
])));
}
if let Some(c) = re!(r"(?i)^a shop[’']s gross sales were (.+?), and refunds were (.+?)% of gross sales; calculate net sales and then (.+?)% commission on net sales$").captures(input) {
let gross = self.money(&c[1], false, context)?;
self.rate(&c[2], true, false, context)?;
self.rate(&c[3], true, false, context)?;
let net = format!("({gross} * (1 - ({})/100))", &c[2]);
return Ok(Some(summary(&[
("net sales", "m", net.clone()),
("commission", "m", format!("({net} * ({})/100)", &c[3])),
])));
}
if let Some(c) = re!(r"(?i)^a (.+?) loan is repaid in (.+?) equal monthly principal payments with no interest; state each payment and the remaining principal after (.+?) payments$").captures(input) {
let principal = self.money(&c[1], false, context)?;
let payments = crate::plugins::integer_queries::value(&c[2])?;
let completed = crate::plugins::integer_queries::value(&c[3])?;
if payments <= 0.into() || completed.is_negative() || completed > payments {
return Err(Error("invalid_financial_argument".into()));
}
let payment = format!("({principal} / {payments})");
return Ok(Some(summary(&[
("payment", "m", payment.clone()),
("remaining principal", "m", format!("({principal} - {completed} * {payment})")),
])));
}
Ok(None)
}
}