nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! Complete price, net-sales and interest-free principal reports.
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)
}

/// The first n-1 installments use nearest half-up cents. The final payment
/// is the exact cent residual; both sentence families share this allocation.
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 - &regular_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 {
                &regular
            };
            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 {
                // Validate even an unrequested residual carried by this model.
                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)
    })())
}

/// Exact shared admission boundary for Business and Finance routing.
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 {
    /// Several natural clause orders carry the same complete seven roles.
    /// Only their admission differs; the typed decomposition and installment
    /// allocation below are shared with the earlier payment-schedule owner.
    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() * &cents).is_integer()
                || !(now.clone() * &cents).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(&regular), 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)?;
            // A supplied month count is a fraction of one annual simple-interest period.
            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)?;
            // Preserve the authored percentages in the typed formula, including
            // their order and the expressly supplied change denominator.
            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)
    }
}