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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
//! Complete price and charge stages reuse the parent's typed money/rate roles.
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,
}

/// The priced rows, separate charge, optional count policy, tax stage and
/// requested report must exhaust this closed invoice family in that order.
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())
}

/// The Finance and Business owners share this complete sentence admission.
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]))
    }

    /// These sentence layouts bind the same five economic roles. Their goals
    /// are parsed separately so spelling and order remain the caller's own.
    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)
    }

    /// A coupon changes the taxable base; a gift card pays the rounded tax-
    /// inclusive bill and cannot create a cash refund.
    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))
    }

    /// Apply an authored discount, round the merchandise base, then tax it.
    /// The closed report keeps each requested money stage in its own slot.
    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))
    }

    /// Shared typed energy/tariff/fixed/credit roles. The new taxed bill asks
    /// for component cent rounding; the old untaxed report retains its stages.
    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;
        // Checking the unit against kWh makes zero consumption no exception to
        // the dimensional validation of the supplied tariff denominator.
        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]))
    }

    /// A billed energy quantity and monetary tariff form one typed product;
    /// the credit is an explicit subtractive money role, not a negative charge.
    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))
    }

    /// The tax base is the rounded energy charge plus rounded service fee,
    /// less the rounded credit; the authored tariff is never rounded first.
    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))
    }

    /// Count priced product entries, then apply tax only to explicitly taxable
    /// entries and charges. Shipping is a charge, never an item line.
    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());
        }
        // Match the complete count token. A word-boundary match could start at
        // the 5 in 1.5 and silently turn a fractional count into five items.
        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()));
                }
            }
            // Multiplying by one energy unit validates a complete currency/energy
            // tariff. Keep its original expression for the actual consumption.
            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()));
                }
            }
            // Both percentage factors cancel. Keep authored midpoints and signed
            // differences in typed arithmetic, rounding only the final scalar.
            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}))");
            // Derive the charge directly: subtracting rounded balances loses tiny taxes.
            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()));
            }
            // The requested discount remains representable even if the original rounds to net.
            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);
            // F=aT,T=bF is uniquely zero for bounded a,b unless both equal one.
            // Exact complements retain this distinction even immediately below100%.
            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);
            // 'Instead' selects an alternative base; it need not equal conventional tax.
            return Ok(Some(format!("{total} * {selected_rate}")));
        }
        Ok(None)
    }
}