1use rand::RngExt;
38use serde_yaml_ng::Value;
39
40use crate::diagnostic::DiagnosticBag;
41use crate::generate::registry::{
42 ArgumentSpec, Buffering, ColumnScope, CompileContext, CompiledPlanner, Determinism,
43 PlannerDescriptor, PlannerFactory, Verification,
44};
45use crate::generate::seed::{SeedRoot, StreamId};
46use crate::generate::value::{GenerateError, GeneratedValue};
47use crate::synthetic::model::PlannerConfig;
48use crate::synthetic::schema::{PortableTable, SqlTypeFamily};
49
50const RATE_DEN: i128 = 1_000_000;
54
55pub const FAMILY_FACTS_KEY: &str = "__family_facts";
60
61pub static COMMERCE_ORDER_FAMILY_DESCRIPTOR: PlannerDescriptor = PlannerDescriptor {
63 kind: "commerce.order_family",
64 aliases: &[],
65 summary: "Coordinates an orders/order_items parent-child family with exact minor-unit money.",
66 arguments: &[
67 ArgumentSpec {
68 name: "children",
69 required: true,
70 summary: "Name of the line-item table coordinated by this parent planner.",
71 },
72 ArgumentSpec {
73 name: "relationship",
74 required: true,
75 summary: "Relationship on the child table that references the parent table.",
76 },
77 ArgumentSpec {
78 name: "columns",
79 required: true,
80 summary: "Maps parent subtotal, total, and optional discount, tax, and shipping roles.",
81 },
82 ArgumentSpec {
83 name: "child_columns",
84 required: true,
85 summary:
86 "Maps child quantity, unit price, line total, and optional discount and tax roles.",
87 },
88 ArgumentSpec {
89 name: "currency_scale",
90 required: true,
91 summary: "Decimal scale shared by every parent and child money column.",
92 },
93 ArgumentSpec {
94 name: "rounding",
95 required: true,
96 summary: "Exact residual allocation mode: largest_remainder, last_line, or bankers.",
97 },
98 ArgumentSpec {
99 name: "quantity",
100 required: false,
101 summary: "Per-line integer quantity range.",
102 },
103 ArgumentSpec {
104 name: "unit_price",
105 required: false,
106 summary: "Per-line unit-price range in minor or major currency units.",
107 },
108 ArgumentSpec {
109 name: "tax",
110 required: false,
111 summary: "Fixed or weighted tax-rate configuration.",
112 },
113 ArgumentSpec {
114 name: "discount",
115 required: false,
116 summary: "Fixed or weighted discount-rate configuration.",
117 },
118 ArgumentSpec {
119 name: "shipping",
120 required: false,
121 summary: "Fixed shipping amount in minor or major currency units.",
122 },
123 ],
124 writes: ColumnScope::Configured,
125 reads: ColumnScope::None,
126 determinism: Determinism::Deterministic,
127 buffering: Buffering::Buffered,
128 verification: Verification::Unsupported,
129 cross_table: true,
130};
131
132pub struct OrderFamilyFactory;
134
135impl PlannerFactory for OrderFamilyFactory {
136 fn descriptor(&self) -> &'static PlannerDescriptor {
137 &COMMERCE_ORDER_FAMILY_DESCRIPTOR
138 }
139
140 fn compile(
141 &self,
142 config: &PlannerConfig,
143 context: &CompileContext<'_>,
144 ) -> Result<Box<dyn CompiledPlanner>, DiagnosticBag> {
145 compile_order_family(config, context)
146 .map(|planner| Box::new(planner) as Box<dyn CompiledPlanner>)
147 }
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum Rounding {
156 LargestRemainder,
159 LastLine,
161 Bankers,
164}
165
166impl Rounding {
167 fn parse(name: &str) -> Option<Self> {
168 match name {
169 "largest_remainder" => Some(Rounding::LargestRemainder),
170 "last_line" => Some(Rounding::LastLine),
171 "bankers" => Some(Rounding::Bankers),
172 _ => None,
173 }
174 }
175}
176
177#[cfg(test)]
185fn apportion(total: i128, weights: &[i128], mode: Rounding) -> Vec<i128> {
186 let count = weights.len();
187 let weight_total: i128 = weights.iter().sum();
188 if count == 0 || total == 0 {
189 return vec![0; count];
190 }
191 if weight_total <= 0 {
192 let mut parts = vec![0i128; count];
195 parts[count - 1] = total;
196 return parts;
197 }
198
199 let mut parts = Vec::with_capacity(count);
200 let mut remainders = Vec::with_capacity(count);
201 let mut allocated: i128 = 0;
202 for &weight in weights {
203 let numerator = total * weight;
204 let floor = numerator.div_euclid(weight_total);
205 parts.push(floor);
206 remainders.push(numerator.rem_euclid(weight_total));
207 allocated += floor;
208 }
209
210 let mut leftover = total - allocated;
211 match mode {
212 Rounding::LastLine => {
213 parts[count - 1] += leftover;
215 }
216 Rounding::LargestRemainder | Rounding::Bankers => {
217 let mut order: Vec<usize> = (0..count).collect();
218 order.sort_by(|&a, &b| {
219 remainders[b]
220 .cmp(&remainders[a])
221 .then_with(|| tie_break(mode, &parts, a, b))
222 });
223 for &index in order.iter().take(leftover.max(0) as usize) {
224 parts[index] += 1;
225 }
226 leftover = 0;
227 }
228 }
229 let _ = leftover;
230 parts
231}
232
233#[cfg(test)]
237fn tie_break(mode: Rounding, parts: &[i128], a: usize, b: usize) -> std::cmp::Ordering {
238 match mode {
239 Rounding::Bankers => {
240 let a_odd = parts[a].rem_euclid(2) == 1;
241 let b_odd = parts[b].rem_euclid(2) == 1;
242 b_odd.cmp(&a_odd).then(a.cmp(&b))
243 }
244 _ => a.cmp(&b),
245 }
246}
247
248#[derive(Debug, Clone)]
253struct RateChoice {
254 cumulative: Vec<(i128, f64)>,
256 total_weight: f64,
257}
258
259impl RateChoice {
260 fn zero() -> Self {
262 Self {
263 cumulative: vec![(0, 1.0)],
264 total_weight: 1.0,
265 }
266 }
267
268 fn fixed(rate_num: i128) -> Self {
270 Self {
271 cumulative: vec![(rate_num, 1.0)],
272 total_weight: 1.0,
273 }
274 }
275
276 fn weighted(rates: &[i128], weights: &[f64]) -> Self {
278 let mut cumulative = Vec::with_capacity(rates.len());
279 let mut acc = 0.0;
280 for (rate, weight) in rates.iter().zip(weights) {
281 acc += weight.max(0.0);
282 cumulative.push((*rate, acc));
283 }
284 Self {
285 total_weight: acc,
286 cumulative,
287 }
288 }
289
290 fn sample(&self, r: f64) -> i128 {
292 if self.total_weight <= 0.0 {
293 return self.cumulative.first().map_or(0, |(rate, _)| *rate);
294 }
295 let target = r * self.total_weight;
296 for (rate, cumulative) in &self.cumulative {
297 if target < *cumulative {
298 return *rate;
299 }
300 }
301 self.cumulative.last().map_or(0, |(rate, _)| *rate)
302 }
303}
304
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309enum ParentRole {
310 Subtotal,
311 Discount,
312 Tax,
313 Shipping,
314 Total,
315}
316
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319enum ChildRole {
320 Quantity,
321 UnitPrice,
322 Discount,
323 Tax,
324 LineTotal,
325}
326
327#[derive(Debug, Clone, Copy)]
329struct IntRange {
330 min: i128,
331 max: i128,
332}
333
334impl IntRange {
335 fn draw(&self, rng: &mut rand_chacha::ChaCha8Rng) -> i128 {
336 if self.max <= self.min {
337 self.min
338 } else {
339 rng.random_range(self.min..=self.max)
340 }
341 }
342}
343
344#[derive(Debug, Clone, Copy)]
349struct LineDist {
350 min: i128,
351 max: i128,
352 mean: f64,
353 kind: LineKind,
354}
355
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358enum LineKind {
359 Fixed,
361 Uniform,
363 MeanRespecting,
365}
366
367impl LineDist {
368 fn draw(&self, rng: &mut rand_chacha::ChaCha8Rng) -> i128 {
371 let raw = match self.kind {
372 LineKind::Fixed => self.mean.round() as i128,
373 LineKind::Uniform => {
374 if self.max <= self.min {
375 self.min
376 } else {
377 rng.random_range(self.min..=self.max)
378 }
379 }
380 LineKind::MeanRespecting => poisson(rng, self.mean),
381 };
382 raw.clamp(self.min, self.max.max(self.min))
383 }
384}
385
386fn poisson(rng: &mut rand_chacha::ChaCha8Rng, mean: f64) -> i128 {
391 if mean <= 0.0 {
392 return 0;
393 }
394 if mean < 30.0 {
395 let limit = (-mean).exp();
396 let mut k = 0i128;
397 let mut product = 1.0f64;
398 loop {
399 k += 1;
400 product *= rng.random::<f64>();
401 if product <= limit {
402 break;
403 }
404 }
405 k - 1
406 } else {
407 let u1 = rng.random::<f64>().max(f64::MIN_POSITIVE);
409 let u2 = rng.random::<f64>();
410 let z = (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos();
411 (mean + z * mean.sqrt()).round().max(0.0) as i128
412 }
413}
414
415pub struct OrderFamilyPlanner {
417 parent_table: String,
419 child_table: String,
421 relationship: String,
423 parent_writes: Vec<String>,
425 parent_roles: Vec<ParentRole>,
427 child_writes: Vec<String>,
429 child_roles: Vec<ChildRole>,
431 scale: u32,
433 parent_families: Vec<SqlTypeFamily>,
435 child_families: Vec<SqlTypeFamily>,
437 rounding: Rounding,
438 quantity: IntRange,
439 unit_price_minor: IntRange,
440 lines: LineDist,
442 tax: RateChoice,
443 discount: RateChoice,
444 shipping_minor: i128,
446 seed: SeedRoot,
447 pending_family: Option<OrderSummary>,
450}
451
452struct OrderSummary {
457 subtotal: i128,
458 discount: i128,
459 tax: i128,
460 shipping: i128,
461 grand_total: i128,
462 line_count: usize,
463 line_rng: rand_chacha::ChaCha8Rng,
464 discount_plan: AllocationPlan,
465 tax_plan: AllocationPlan,
466}
467
468struct LineTotals {
470 quantity: i128,
471 unit_price: i128,
472 discount: i128,
473 tax: i128,
474 line_total: i128,
475}
476
477struct RawLine {
479 quantity: i128,
480 unit_price: i128,
481 subtotal: i128,
482}
483
484fn draw_raw_line(
487 rng: &mut rand_chacha::ChaCha8Rng,
488 quantity: IntRange,
489 unit_price: IntRange,
490) -> Result<RawLine, GenerateError> {
491 let quantity = quantity.draw(rng).max(0);
492 let unit_price = unit_price.draw(rng).max(0);
493 let subtotal = quantity
494 .checked_mul(unit_price)
495 .ok_or_else(|| overflow("line subtotal (quantity * unit_price)"))?;
496 Ok(RawLine {
497 quantity,
498 unit_price,
499 subtotal,
500 })
501}
502
503struct RawLines {
505 rng: rand_chacha::ChaCha8Rng,
506 remaining: usize,
507 quantity: IntRange,
508 unit_price: IntRange,
509}
510
511impl RawLines {
512 fn new(
513 rng: rand_chacha::ChaCha8Rng,
514 count: usize,
515 quantity: IntRange,
516 unit_price: IntRange,
517 ) -> Self {
518 Self {
519 rng,
520 remaining: count,
521 quantity,
522 unit_price,
523 }
524 }
525}
526
527impl Iterator for RawLines {
528 type Item = Result<RawLine, GenerateError>;
529
530 fn next(&mut self) -> Option<Self::Item> {
531 if self.remaining == 0 {
532 return None;
533 }
534 self.remaining -= 1;
535 Some(draw_raw_line(&mut self.rng, self.quantity, self.unit_price))
536 }
537}
538
539#[derive(Clone)]
546struct AllocationPlan {
547 total: i128,
548 weight_total: i128,
549 count: usize,
550 mode: Rounding,
551 leftover: i128,
552 threshold: Option<i128>,
553 tie_slots: usize,
554 odd_ties: usize,
555}
556
557impl AllocationPlan {
558 fn build<F, I>(total: i128, mode: Rounding, weights: F) -> Result<Self, GenerateError>
559 where
560 F: Fn() -> I,
561 I: Iterator<Item = Result<i128, GenerateError>>,
562 {
563 let mut count = 0usize;
564 let mut weight_total = 0i128;
565 for weight in weights() {
566 let weight = weight?.max(0);
567 weight_total = weight_total
568 .checked_add(weight)
569 .ok_or_else(|| overflow("allocation weight total"))?;
570 count += 1;
571 }
572
573 let mut plan = Self {
574 total,
575 weight_total,
576 count,
577 mode,
578 leftover: 0,
579 threshold: None,
580 tie_slots: 0,
581 odd_ties: 0,
582 };
583 if count == 0 || total == 0 || weight_total <= 0 {
584 return Ok(plan);
585 }
586
587 let mut allocated = 0i128;
588 for weight in weights() {
589 let (floor, _) = proportional_share(total, weight?.max(0), weight_total)?;
590 allocated = allocated
591 .checked_add(floor)
592 .ok_or_else(|| overflow("allocated family amount"))?;
593 }
594 plan.leftover = total
595 .checked_sub(allocated)
596 .ok_or_else(|| overflow("family allocation residual"))?;
597
598 if mode == Rounding::LastLine || plan.leftover <= 0 {
599 return Ok(plan);
600 }
601
602 let wanted = usize::try_from(plan.leftover)
603 .map_err(|_| overflow("family allocation residual count"))?;
604 let mut low = 0i128;
607 let mut high = weight_total;
608 while low + 1 < high {
609 let mid = low + (high - low) / 2;
610 let mut at_or_above = 0usize;
611 for weight in weights() {
612 let (_, remainder) = proportional_share(total, weight?.max(0), weight_total)?;
613 if remainder >= mid {
614 at_or_above += 1;
615 }
616 }
617 if at_or_above >= wanted {
618 low = mid;
619 } else {
620 high = mid;
621 }
622 }
623 plan.threshold = Some(low);
624
625 let mut greater = 0usize;
626 let mut odd_ties = 0usize;
627 for weight in weights() {
628 let (floor, remainder) = proportional_share(total, weight?.max(0), weight_total)?;
629 if remainder > low {
630 greater += 1;
631 } else if remainder == low && floor.rem_euclid(2) == 1 {
632 odd_ties += 1;
633 }
634 }
635 plan.tie_slots = wanted.saturating_sub(greater);
636 plan.odd_ties = odd_ties;
637 Ok(plan)
638 }
639
640 fn cursor(&self) -> AllocationCursor {
641 AllocationCursor {
642 plan: self.clone(),
643 tied_seen: 0,
644 odd_seen: 0,
645 even_seen: 0,
646 }
647 }
648}
649
650struct AllocationCursor {
652 plan: AllocationPlan,
653 tied_seen: usize,
654 odd_seen: usize,
655 even_seen: usize,
656}
657
658impl AllocationCursor {
659 fn part(&mut self, index: usize, weight: i128) -> Result<i128, GenerateError> {
660 if self.plan.count == 0 || self.plan.total == 0 {
661 return Ok(0);
662 }
663 if self.plan.weight_total <= 0 {
664 return Ok(if index + 1 == self.plan.count {
665 self.plan.total
666 } else {
667 0
668 });
669 }
670
671 let (floor, remainder) =
672 proportional_share(self.plan.total, weight.max(0), self.plan.weight_total)?;
673 if self.plan.mode == Rounding::LastLine {
674 return if index + 1 == self.plan.count {
675 floor
676 .checked_add(self.plan.leftover)
677 .ok_or_else(|| overflow("last-line allocation"))
678 } else {
679 Ok(floor)
680 };
681 }
682
683 let Some(threshold) = self.plan.threshold else {
684 return Ok(floor);
685 };
686 let receives_extra = if remainder > threshold {
687 true
688 } else if remainder < threshold {
689 false
690 } else {
691 match self.plan.mode {
692 Rounding::LargestRemainder => {
693 let selected = self.tied_seen < self.plan.tie_slots;
694 self.tied_seen += 1;
695 selected
696 }
697 Rounding::Bankers => {
698 let odd_slots = self.plan.tie_slots.min(self.plan.odd_ties);
699 if floor.rem_euclid(2) == 1 {
700 let selected = self.odd_seen < odd_slots;
701 self.odd_seen += 1;
702 selected
703 } else {
704 let selected = self.even_seen < self.plan.tie_slots - odd_slots;
705 self.even_seen += 1;
706 selected
707 }
708 }
709 Rounding::LastLine => false,
710 }
711 };
712 if receives_extra {
713 floor
714 .checked_add(1)
715 .ok_or_else(|| overflow("ranked allocation"))
716 } else {
717 Ok(floor)
718 }
719 }
720}
721
722fn proportional_share(
723 total: i128,
724 weight: i128,
725 weight_total: i128,
726) -> Result<(i128, i128), GenerateError> {
727 let numerator = total
728 .checked_mul(weight)
729 .ok_or_else(|| overflow("proportional allocation"))?;
730 Ok((
731 numerator.div_euclid(weight_total),
732 numerator.rem_euclid(weight_total),
733 ))
734}
735
736struct TaxWeights {
738 raw: RawLines,
739 discount: AllocationCursor,
740 index: usize,
741}
742
743impl Iterator for TaxWeights {
744 type Item = Result<i128, GenerateError>;
745
746 fn next(&mut self) -> Option<Self::Item> {
747 let raw = self.raw.next()?;
748 Some(raw.and_then(|raw| {
749 let discount = self.discount.part(self.index, raw.subtotal)?;
750 self.index += 1;
751 raw.subtotal
752 .checked_sub(discount)
753 .ok_or_else(|| overflow("taxable line amount"))
754 }))
755 }
756}
757
758impl OrderFamilyPlanner {
759 fn compute(&self, order_index: u64) -> Result<OrderSummary, GenerateError> {
762 let mut rng = self.seed.stream(StreamId::operator(
763 self.parent_table.clone(),
764 "commerce.order_family",
765 format!("family.{order_index}"),
766 ));
767
768 let line_count = usize::try_from(self.lines.draw(&mut rng).max(0))
769 .map_err(|_| overflow("order-family line count"))?;
770 let line_rng = rng.clone();
771
772 let mut subtotal: i128 = 0;
775 for _ in 0..line_count {
776 let raw = draw_raw_line(&mut rng, self.quantity, self.unit_price_minor)?;
777 subtotal = subtotal
778 .checked_add(raw.subtotal)
779 .ok_or_else(|| overflow("order subtotal"))?;
780 }
781
782 let discount_rate = self.discount.sample(rng.random::<f64>());
783 let tax_rate = self.tax.sample(rng.random::<f64>());
784
785 let discount_total = rounded_rate(subtotal, discount_rate)?;
786 let discount_plan = AllocationPlan::build(discount_total, self.rounding, || {
787 RawLines::new(
788 line_rng.clone(),
789 line_count,
790 self.quantity,
791 self.unit_price_minor,
792 )
793 .map(|raw| raw.map(|line| line.subtotal))
794 })?;
795
796 let order_taxable = subtotal
797 .checked_sub(discount_total)
798 .ok_or_else(|| overflow("order taxable amount"))?;
799 let tax_total = rounded_rate(order_taxable, tax_rate)?;
800 let tax_plan = AllocationPlan::build(tax_total, self.rounding, || TaxWeights {
801 raw: RawLines::new(
802 line_rng.clone(),
803 line_count,
804 self.quantity,
805 self.unit_price_minor,
806 ),
807 discount: discount_plan.cursor(),
808 index: 0,
809 })?;
810
811 let shipping = self.shipping_minor;
812 let grand_total = subtotal
813 .checked_sub(discount_total)
814 .and_then(|value| value.checked_add(tax_total))
815 .and_then(|value| value.checked_add(shipping))
816 .ok_or_else(|| overflow("order grand total"))?;
817
818 Ok(OrderSummary {
819 subtotal,
820 discount: discount_total,
821 tax: tax_total,
822 shipping,
823 grand_total,
824 line_count,
825 line_rng,
826 discount_plan,
827 tax_plan,
828 })
829 }
830
831 fn render_money(&self, minor: i128, family: &SqlTypeFamily) -> GeneratedValue {
833 match family {
834 SqlTypeFamily::Decimal => GeneratedValue::Decimal {
835 minor,
836 scale: self.scale,
837 },
838 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(minor),
839 _ => GeneratedValue::Text(format_minor(minor, self.scale)),
840 }
841 }
842
843 fn parent_value(
845 &self,
846 role: ParentRole,
847 totals: &OrderSummary,
848 family: &SqlTypeFamily,
849 ) -> GeneratedValue {
850 let minor = match role {
851 ParentRole::Subtotal => totals.subtotal,
852 ParentRole::Discount => totals.discount,
853 ParentRole::Tax => totals.tax,
854 ParentRole::Shipping => totals.shipping,
855 ParentRole::Total => totals.grand_total,
856 };
857 self.render_money(minor, family)
858 }
859
860 fn child_value(
862 &self,
863 role: ChildRole,
864 line: &LineTotals,
865 family: &SqlTypeFamily,
866 ) -> GeneratedValue {
867 match role {
868 ChildRole::Quantity => match family {
869 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => {
870 GeneratedValue::Integer(line.quantity)
871 }
872 _ => GeneratedValue::Text(line.quantity.to_string()),
873 },
874 ChildRole::UnitPrice => self.render_money(line.unit_price, family),
875 ChildRole::Discount => self.render_money(line.discount, family),
876 ChildRole::Tax => self.render_money(line.tax, family),
877 ChildRole::LineTotal => self.render_money(line.line_total, family),
878 }
879 }
880}
881
882struct OrderFamilyChildRows<'a> {
884 planner: &'a OrderFamilyPlanner,
885 raw: RawLines,
886 discount: AllocationCursor,
887 tax: AllocationCursor,
888 index: usize,
889}
890
891impl<'a> OrderFamilyChildRows<'a> {
892 fn new(planner: &'a OrderFamilyPlanner, summary: OrderSummary) -> Self {
893 Self {
894 raw: RawLines::new(
895 summary.line_rng,
896 summary.line_count,
897 planner.quantity,
898 planner.unit_price_minor,
899 ),
900 discount: summary.discount_plan.cursor(),
901 tax: summary.tax_plan.cursor(),
902 planner,
903 index: 0,
904 }
905 }
906}
907
908impl Iterator for OrderFamilyChildRows<'_> {
909 type Item = Result<Vec<GeneratedValue>, GenerateError>;
910
911 fn next(&mut self) -> Option<Self::Item> {
912 let raw = match self.raw.next()? {
913 Ok(raw) => raw,
914 Err(error) => return Some(Err(error)),
915 };
916 let result = (|| {
917 let discount = self.discount.part(self.index, raw.subtotal)?;
918 let taxable = raw
919 .subtotal
920 .checked_sub(discount)
921 .ok_or_else(|| overflow("taxable line amount"))?;
922 let tax = self.tax.part(self.index, taxable)?;
923 let line_total = taxable
924 .checked_add(tax)
925 .ok_or_else(|| overflow("child line total"))?;
926 self.index += 1;
927
928 let line = LineTotals {
929 quantity: raw.quantity,
930 unit_price: raw.unit_price,
931 discount,
932 tax,
933 line_total,
934 };
935 let mut values = Vec::with_capacity(self.planner.child_writes.len());
936 for (role, family) in self
937 .planner
938 .child_roles
939 .iter()
940 .zip(&self.planner.child_families)
941 {
942 values.push(self.planner.child_value(*role, &line, family));
943 }
944 Ok(values)
945 })();
946 Some(result)
947 }
948}
949
950impl CompiledPlanner for OrderFamilyPlanner {
951 fn writes(&self) -> &[String] {
952 &self.parent_writes
953 }
954
955 fn generate_row(
956 &mut self,
957 row_index: u64,
958 output: &mut [GeneratedValue],
959 ) -> Result<(), GenerateError> {
960 let totals = self.compute(row_index)?;
961
962 for (slot, role) in output.iter_mut().zip(&self.parent_roles) {
963 let family = self.parent_family_for(*role);
964 *slot = self.parent_value(*role, &totals, family);
965 }
966
967 self.pending_family = Some(totals);
968 Ok(())
969 }
970
971 fn family_child_table(&self) -> Option<&str> {
972 Some(&self.child_table)
973 }
974
975 fn family_relationship(&self) -> Option<&str> {
976 Some(&self.relationship)
977 }
978
979 fn child_writes(&self) -> &[String] {
980 &self.child_writes
981 }
982
983 fn take_family_children(
984 &mut self,
985 ) -> Box<dyn Iterator<Item = Result<Vec<GeneratedValue>, GenerateError>> + '_> {
986 match self.pending_family.take() {
987 Some(summary) => Box::new(OrderFamilyChildRows::new(self, summary)),
988 None => Box::new(std::iter::empty()),
989 }
990 }
991
992 fn family_sum_checks(&self) -> Vec<crate::generate::registry::FamilySumCheck> {
993 use crate::generate::registry::FamilySumCheck;
994
995 let pure_sum_roles = [ParentRole::Discount, ParentRole::Tax];
1002 let child_role_of = |parent: ParentRole| match parent {
1003 ParentRole::Discount => Some(ChildRole::Discount),
1004 ParentRole::Tax => Some(ChildRole::Tax),
1005 _ => None,
1006 };
1007
1008 pure_sum_roles
1009 .into_iter()
1010 .filter_map(|parent_role| {
1011 let child_role = child_role_of(parent_role)?;
1012 let parent_column = self.column_for_parent_role(parent_role)?;
1013 let child_column = self.column_for_child_role(child_role)?;
1014 Some(FamilySumCheck {
1015 relationship: self.relationship.clone(),
1016 parent_column,
1017 child_column,
1018 })
1019 })
1020 .collect()
1021 }
1022}
1023
1024impl OrderFamilyPlanner {
1025 fn column_for_parent_role(&self, role: ParentRole) -> Option<String> {
1028 self.parent_roles
1029 .iter()
1030 .position(|candidate| *candidate == role)
1031 .map(|index| self.parent_writes[index].clone())
1032 }
1033
1034 fn column_for_child_role(&self, role: ChildRole) -> Option<String> {
1037 self.child_roles
1038 .iter()
1039 .position(|candidate| *candidate == role)
1040 .map(|index| self.child_writes[index].clone())
1041 }
1042
1043 fn parent_family_for(&self, role: ParentRole) -> &SqlTypeFamily {
1044 let index = self
1045 .parent_roles
1046 .iter()
1047 .position(|candidate| *candidate == role)
1048 .expect("role is in parent_roles");
1049 &self.parent_families[index]
1050 }
1051}
1052
1053fn rounded_rate(amount: i128, rate_num: i128) -> Result<i128, GenerateError> {
1055 if rate_num == 0 || amount == 0 {
1056 return Ok(0);
1057 }
1058 let numerator = amount
1059 .checked_mul(rate_num)
1060 .ok_or_else(|| overflow("rate * amount"))?;
1061 Ok((numerator + RATE_DEN / 2).div_euclid(RATE_DEN))
1063}
1064
1065fn format_minor(minor: i128, scale: u32) -> String {
1068 if scale == 0 {
1069 return minor.to_string();
1070 }
1071 let divisor = 10i128.pow(scale);
1072 let sign = if minor < 0 { "-" } else { "" };
1073 let magnitude = minor.abs();
1074 let whole = magnitude / divisor;
1075 let frac = magnitude % divisor;
1076 format!("{sign}{whole}.{frac:0width$}", width = scale as usize)
1077}
1078
1079fn overflow(what: &str) -> GenerateError {
1081 GenerateError::Overflow(format!(
1082 "commerce.order_family: {what} overflows the representable minor-unit range"
1083 ))
1084}
1085
1086fn compile_order_family(
1091 config: &PlannerConfig,
1092 context: &CompileContext<'_>,
1093) -> Result<OrderFamilyPlanner, DiagnosticBag> {
1094 let mut bag = DiagnosticBag::default();
1095 let parent = context.table();
1096 let path = context.path();
1097
1098 reject_flat_form(config, path, &mut bag);
1099
1100 let facts = config.args.get(FAMILY_FACTS_KEY);
1101 let child_found = facts
1102 .and_then(|f| f.get("child_found"))
1103 .and_then(Value::as_bool)
1104 .unwrap_or(false);
1105 let child_name = string_arg(config, "children")
1106 .unwrap_or_default()
1107 .to_string();
1108
1109 if !child_found {
1110 bag.error(
1111 crate::diagnostic::codes::ORDER_FAMILY_CHILD_UNKNOWN.code,
1112 format!("{path}.children"),
1113 format!(
1114 "commerce.order_family `children` names table `{child_name}`, which is not a table in the model"
1115 ),
1116 );
1117 }
1118
1119 let rel_name = string_arg(config, "relationship")
1120 .unwrap_or_default()
1121 .to_string();
1122 let rel_on_child = facts
1123 .and_then(|f| f.get("rel_on_child"))
1124 .and_then(Value::as_bool)
1125 .unwrap_or(false);
1126 if child_found && !rel_on_child {
1127 bag.error(
1128 crate::diagnostic::codes::ORDER_FAMILY_RELATIONSHIP.code,
1129 format!("{path}.relationship"),
1130 format!(
1131 "commerce.order_family `relationship` `{rel_name}` is not a relationship declared on child table `{child_name}` that references parent `{}`",
1132 parent.name
1133 ),
1134 );
1135 }
1136
1137 let scale = match config.args.get("currency_scale").and_then(as_u32) {
1138 Some(scale) if scale <= 18 => scale,
1141 Some(scale) => {
1142 bag.error(
1143 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1144 format!("{path}.currency_scale"),
1145 format!(
1146 "commerce.order_family `currency_scale` must be between 0 and 18 (got {scale})"
1147 ),
1148 );
1149 0
1150 }
1151 None => {
1152 bag.error(
1153 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1154 format!("{path}.currency_scale"),
1155 "commerce.order_family requires a `currency_scale`".to_string(),
1156 );
1157 0
1158 }
1159 };
1160
1161 let rounding = match config.args.get("rounding").and_then(Value::as_str) {
1162 Some(name) => match Rounding::parse(name) {
1163 Some(rounding) => rounding,
1164 None => {
1165 bag.error(
1166 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1167 format!("{path}.rounding"),
1168 format!("commerce.order_family `rounding` `{name}` is not one of `largest_remainder`, `last_line`, `bankers`"),
1169 );
1170 Rounding::LargestRemainder
1171 }
1172 },
1173 None => {
1174 bag.error(
1175 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1176 format!("{path}.rounding"),
1177 "commerce.order_family requires a `rounding` mode".to_string(),
1178 );
1179 Rounding::LargestRemainder
1180 }
1181 };
1182
1183 let (parent_writes, parent_roles, parent_families) =
1185 resolve_parent_roles(config, parent, scale, path, &mut bag);
1186
1187 let (child_writes, child_roles, child_families) =
1189 resolve_child_roles(config, facts, &child_name, scale, path, &mut bag);
1190
1191 let quantity = int_range(config.args.get("quantity"), 1, 1);
1192 let unit_price_minor = unit_price_range(config.args.get("unit_price"), scale);
1193 let lines = compile_line_range(facts, path, &mut bag);
1194 let tax = compile_rate(config.args.get("tax"), "tax", path, &mut bag);
1195 let discount = compile_rate(config.args.get("discount"), "discount", path, &mut bag);
1196 let shipping_minor = compile_shipping(config.args.get("shipping"), scale);
1197
1198 check_overflow(
1201 &lines,
1202 &quantity,
1203 &unit_price_minor,
1204 &tax,
1205 shipping_minor,
1206 &parent_writes,
1207 parent,
1208 facts,
1209 &child_writes,
1210 &child_name,
1211 path,
1212 &mut bag,
1213 );
1214
1215 if bag.has_errors() {
1216 return Err(bag);
1217 }
1218
1219 Ok(OrderFamilyPlanner {
1220 parent_table: parent.name.clone(),
1221 child_table: child_name,
1222 relationship: rel_name,
1223 parent_writes,
1224 parent_roles,
1225 child_writes,
1226 child_roles,
1227 scale,
1228 parent_families,
1229 child_families,
1230 rounding,
1231 quantity,
1232 unit_price_minor,
1233 lines,
1234 tax,
1235 discount,
1236 shipping_minor,
1237 seed: context.seed(),
1238 pending_family: None,
1239 })
1240}
1241
1242fn reject_flat_form(config: &PlannerConfig, path: &str, bag: &mut DiagnosticBag) {
1245 for key in [
1246 "subtotal",
1247 "line_total",
1248 "grand_total",
1249 "line_items",
1250 "items",
1251 ] {
1252 if config.args.contains_key(key) {
1253 bag.error(
1254 crate::diagnostic::codes::ORDER_FAMILY_UNKNOWN_FIELD.code,
1255 format!("{path}.{key}"),
1256 format!(
1257 "commerce.order_family does not accept a top-level `{key}`; map parent columns under `columns` and child columns under `child_columns` (the old flat form is not supported)"
1258 ),
1259 );
1260 }
1261 }
1262}
1263
1264const PARENT_ROLE_ORDER: [(&str, ParentRole, bool); 5] = [
1266 ("subtotal", ParentRole::Subtotal, true),
1267 ("discount", ParentRole::Discount, false),
1268 ("tax", ParentRole::Tax, false),
1269 ("shipping", ParentRole::Shipping, false),
1270 ("total", ParentRole::Total, true),
1271];
1272
1273const CHILD_ROLE_ORDER: [(&str, ChildRole, bool); 5] = [
1276 ("quantity", ChildRole::Quantity, true),
1277 ("unit_price", ChildRole::UnitPrice, true),
1278 ("discount", ChildRole::Discount, false),
1279 ("tax", ChildRole::Tax, false),
1280 ("line_total", ChildRole::LineTotal, true),
1281];
1282
1283fn resolve_parent_roles(
1287 config: &PlannerConfig,
1288 parent: &PortableTable,
1289 scale: u32,
1290 path: &str,
1291 bag: &mut DiagnosticBag,
1292) -> (Vec<String>, Vec<ParentRole>, Vec<SqlTypeFamily>) {
1293 let columns = config.args.get("columns");
1294 let mut writes = Vec::new();
1295 let mut roles = Vec::new();
1296 let mut families = Vec::new();
1297 for (key, role, required) in PARENT_ROLE_ORDER {
1298 let Some(name) = role_name(columns, key) else {
1299 if required {
1300 bag.error(
1301 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1302 format!("{path}.columns.{key}"),
1303 format!("commerce.order_family requires a `{key}` column under `columns`"),
1304 );
1305 }
1306 continue;
1307 };
1308 match parent.columns.iter().find(|column| column.name == name) {
1309 Some(column) => {
1310 check_money_scale(
1311 &column.source_type,
1312 &column.family,
1313 scale,
1314 &format!("{path}.columns.{key}"),
1315 &column.name,
1316 bag,
1317 );
1318 writes.push(column.name.clone());
1319 roles.push(role);
1320 families.push(column.family.clone());
1321 }
1322 None => {
1323 bag.error(
1324 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1325 format!("{path}.columns.{key}"),
1326 format!(
1327 "commerce.order_family `{key}` column `{name}` does not exist on parent table `{}`",
1328 parent.name
1329 ),
1330 );
1331 }
1332 }
1333 }
1334 (writes, roles, families)
1335}
1336
1337fn resolve_child_roles(
1339 config: &PlannerConfig,
1340 facts: Option<&Value>,
1341 child_name: &str,
1342 scale: u32,
1343 path: &str,
1344 bag: &mut DiagnosticBag,
1345) -> (Vec<String>, Vec<ChildRole>, Vec<SqlTypeFamily>) {
1346 let columns = config.args.get("child_columns");
1347 let child_types = facts.and_then(|f| f.get("child_columns"));
1348 let mut writes = Vec::new();
1349 let mut roles = Vec::new();
1350 let mut families = Vec::new();
1351 for (key, role, required) in CHILD_ROLE_ORDER {
1352 let Some(name) = role_name(columns, key) else {
1353 if required {
1354 bag.error(
1355 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1356 format!("{path}.child_columns.{key}"),
1357 format!(
1358 "commerce.order_family requires a `{key}` column under `child_columns`"
1359 ),
1360 );
1361 }
1362 continue;
1363 };
1364 let source_type = child_types
1367 .and_then(|types| types.get(name))
1368 .and_then(Value::as_str);
1369 match source_type {
1370 Some(source_type) => {
1371 let family = family_of_source_type(source_type);
1372 if role != ChildRole::Quantity {
1373 check_money_scale(
1374 source_type,
1375 &family,
1376 scale,
1377 &format!("{path}.child_columns.{key}"),
1378 name,
1379 bag,
1380 );
1381 }
1382 writes.push(name.to_string());
1383 roles.push(role);
1384 families.push(family);
1385 }
1386 None => {
1387 bag.error(
1388 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1389 format!("{path}.child_columns.{key}"),
1390 format!(
1391 "commerce.order_family `{key}` column `{name}` does not exist on child table `{child_name}`"
1392 ),
1393 );
1394 }
1395 }
1396 }
1397 (writes, roles, families)
1398}
1399
1400fn check_money_scale(
1404 source_type: &str,
1405 family: &SqlTypeFamily,
1406 scale: u32,
1407 path: &str,
1408 column: &str,
1409 bag: &mut DiagnosticBag,
1410) {
1411 if *family != SqlTypeFamily::Decimal {
1412 return;
1413 }
1414 if let Some((_, declared_scale)) = decimal_precision_scale(source_type) {
1415 if declared_scale != scale {
1416 bag.error(
1417 crate::diagnostic::codes::ORDER_FAMILY_SCALE.code,
1418 path.to_string(),
1419 format!(
1420 "commerce.order_family `currency_scale` is {scale}, but money column `{column}` is declared `{source_type}` with scale {declared_scale}; the currency scale is ambiguous"
1421 ),
1422 );
1423 }
1424 }
1425}
1426
1427fn compile_line_range(facts: Option<&Value>, path: &str, bag: &mut DiagnosticBag) -> LineDist {
1431 let min = facts
1432 .and_then(|f| f.get("dist_min"))
1433 .and_then(as_f64)
1434 .unwrap_or(1.0);
1435 let max = facts
1436 .and_then(|f| f.get("dist_max"))
1437 .and_then(as_f64)
1438 .unwrap_or(min);
1439 let mean = facts.and_then(|f| f.get("dist_mean")).and_then(as_f64);
1440 let kind = match facts
1441 .and_then(|f| f.get("dist_kind"))
1442 .and_then(Value::as_str)
1443 {
1444 Some("fixed") => LineKind::Fixed,
1445 Some("uniform") => LineKind::Uniform,
1446 _ => LineKind::MeanRespecting,
1450 };
1451 let min_lines = min.max(0.0).ceil() as i128;
1452 let max_lines = max.max(0.0).floor() as i128;
1453 if max_lines < min_lines || (max_lines == 0 && min_lines > 0) {
1454 bag.error(
1455 crate::diagnostic::codes::ORDER_FAMILY_ZERO_LINES.code,
1456 path.to_string(),
1457 format!(
1458 "commerce.order_family child distribution allows at most {max_lines} line(s) but requires at least {min_lines}; no order could satisfy the minimum"
1459 ),
1460 );
1461 }
1462 let min_lines = min_lines.max(0);
1463 let max_lines = max_lines.max(min_lines);
1464 let mean = mean
1467 .unwrap_or(min_lines.max(1) as f64)
1468 .clamp(min_lines as f64, max_lines as f64);
1469 LineDist {
1470 min: min_lines,
1471 max: max_lines,
1472 mean,
1473 kind,
1474 }
1475}
1476
1477fn compile_rate(
1479 value: Option<&Value>,
1480 what: &str,
1481 path: &str,
1482 bag: &mut DiagnosticBag,
1483) -> RateChoice {
1484 let Some(value) = value else {
1485 return RateChoice::zero();
1486 };
1487 match value.get("kind").and_then(Value::as_str) {
1488 Some("weighted_choice") | None if value.get("rates").is_some() => {
1489 let rates = number_list(value.get("rates"));
1490 let weights = number_list(value.get("weights"));
1491 if rates.is_empty() || weights.len() != rates.len() {
1492 bag.error(
1493 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1494 format!("{path}.{what}"),
1495 format!("commerce.order_family `{what}` weighted_choice needs matching `rates` and `weights` lists"),
1496 );
1497 return RateChoice::zero();
1498 }
1499 let nums: Vec<i128> = rates.iter().map(|rate| rate_to_num(*rate)).collect();
1500 RateChoice::weighted(&nums, &weights)
1501 }
1502 Some("fixed") | Some("fixed_rate") => {
1503 let rate = value.get("rate").and_then(as_f64).unwrap_or(0.0);
1504 RateChoice::fixed(rate_to_num(rate))
1505 }
1506 _ => {
1507 if let Some(rate) = value.get("rate").and_then(as_f64) {
1509 RateChoice::fixed(rate_to_num(rate))
1510 } else {
1511 RateChoice::zero()
1512 }
1513 }
1514 }
1515}
1516
1517fn compile_shipping(value: Option<&Value>, scale: u32) -> i128 {
1519 let Some(value) = value else {
1520 return 0;
1521 };
1522 if let Some(minor) = value.get("amount_minor").and_then(as_i128) {
1523 return minor.max(0);
1524 }
1525 if let Some(amount) = value.get("amount").and_then(as_f64) {
1526 return to_minor(amount, scale).max(0);
1527 }
1528 0
1529}
1530
1531#[allow(clippy::too_many_arguments)]
1534fn check_overflow(
1535 lines: &LineDist,
1536 quantity: &IntRange,
1537 unit_price: &IntRange,
1538 tax: &RateChoice,
1539 shipping_minor: i128,
1540 parent_writes: &[String],
1541 parent: &PortableTable,
1542 facts: Option<&Value>,
1543 child_writes: &[String],
1544 child_name: &str,
1545 path: &str,
1546 bag: &mut DiagnosticBag,
1547) {
1548 let max_rate = tax
1549 .cumulative
1550 .iter()
1551 .map(|(rate, _)| *rate)
1552 .max()
1553 .unwrap_or(0);
1554 let per_line = match quantity.max.checked_mul(unit_price.max) {
1555 Some(value) => value,
1556 None => {
1557 bag.error(
1558 crate::diagnostic::codes::ORDER_FAMILY_OVERFLOW.code,
1559 path.to_string(),
1560 "commerce.order_family maximum line subtotal (quantity * unit_price) overflows i128".to_string(),
1561 );
1562 return;
1563 }
1564 };
1565 let subtotal_max = per_line.saturating_mul(lines.max.max(0));
1566 let tax_max = subtotal_max.saturating_mul(max_rate) / RATE_DEN;
1567 let grand_max = subtotal_max
1570 .saturating_add(tax_max)
1571 .saturating_add(shipping_minor.max(0));
1572 let per_line_tax_max = per_line.saturating_mul(max_rate) / RATE_DEN;
1576 let child_max = per_line.saturating_add(per_line_tax_max);
1577
1578 for name in parent_writes {
1580 if let Some(column) = parent.columns.iter().find(|column| &column.name == name) {
1581 report_capacity(
1582 &column.source_type,
1583 grand_max,
1584 name,
1585 &parent.name,
1586 path,
1587 bag,
1588 );
1589 }
1590 }
1591 let child_types = facts.and_then(|f| f.get("child_columns"));
1593 for name in child_writes {
1594 if let Some(source_type) = child_types
1595 .and_then(|types| types.get(name))
1596 .and_then(Value::as_str)
1597 {
1598 report_capacity(source_type, child_max, name, child_name, path, bag);
1599 }
1600 }
1601}
1602
1603fn report_capacity(
1606 source_type: &str,
1607 max_minor: i128,
1608 column: &str,
1609 table: &str,
1610 path: &str,
1611 bag: &mut DiagnosticBag,
1612) {
1613 if let Some((precision, _)) = decimal_precision_scale(source_type) {
1614 let capacity = 10i128
1615 .checked_pow(precision)
1616 .map(|v| v - 1)
1617 .unwrap_or(i128::MAX);
1618 if max_minor > capacity {
1619 bag.error(
1620 crate::diagnostic::codes::ORDER_FAMILY_OVERFLOW.code,
1621 path.to_string(),
1622 format!(
1623 "commerce.order_family can reach {max_minor} minor units, exceeding the capacity {capacity} of money column `{column}` on table `{table}` (declared `{source_type}`)"
1624 ),
1625 );
1626 }
1627 }
1628}
1629
1630fn rate_to_num(rate: f64) -> i128 {
1634 (rate * RATE_DEN as f64).round() as i128
1635}
1636
1637fn to_minor(amount: f64, scale: u32) -> i128 {
1639 (amount * 10f64.powi(scale as i32)).round() as i128
1640}
1641
1642fn decimal_precision_scale(source_type: &str) -> Option<(u32, u32)> {
1644 let open = source_type.find('(')?;
1645 let close = source_type.find(')')?;
1646 let inner = source_type.get(open + 1..close)?;
1647 let mut parts = inner.split(',');
1648 let precision = parts.next()?.trim().parse::<u32>().ok()?;
1649 let scale = parts
1650 .next()
1651 .and_then(|s| s.trim().parse::<u32>().ok())
1652 .unwrap_or(0);
1653 Some((precision, scale))
1654}
1655
1656fn family_of_source_type(source_type: &str) -> SqlTypeFamily {
1658 let lower = source_type.to_lowercase();
1659 if lower.starts_with("decimal") || lower.starts_with("numeric") {
1660 SqlTypeFamily::Decimal
1661 } else if lower.starts_with("bigint") {
1662 SqlTypeFamily::BigInteger
1663 } else if lower.starts_with("int")
1664 || lower.starts_with("smallint")
1665 || lower.starts_with("tinyint")
1666 {
1667 SqlTypeFamily::Integer
1668 } else {
1669 SqlTypeFamily::Other
1670 }
1671}
1672
1673fn int_range(value: Option<&Value>, default_min: i128, default_max: i128) -> IntRange {
1675 let min = value
1676 .and_then(|v| v.get("min"))
1677 .and_then(as_i128)
1678 .unwrap_or(default_min);
1679 let max = value
1680 .and_then(|v| v.get("max"))
1681 .and_then(as_i128)
1682 .unwrap_or(default_max.max(min));
1683 IntRange {
1684 min: min.max(0),
1685 max: max.max(min).max(0),
1686 }
1687}
1688
1689fn unit_price_range(value: Option<&Value>, scale: u32) -> IntRange {
1692 let Some(value) = value else {
1693 return IntRange {
1694 min: 100,
1695 max: 10_000,
1696 };
1697 };
1698 if let (Some(min), Some(max)) = (
1699 value.get("min_minor").and_then(as_i128),
1700 value.get("max_minor").and_then(as_i128),
1701 ) {
1702 return IntRange {
1703 min: min.max(0),
1704 max: max.max(min).max(0),
1705 };
1706 }
1707 let min = value
1708 .get("min")
1709 .and_then(as_f64)
1710 .map(|v| to_minor(v, scale))
1711 .unwrap_or(100);
1712 let max = value
1713 .get("max")
1714 .and_then(as_f64)
1715 .map(|v| to_minor(v, scale))
1716 .unwrap_or(min.max(10_000));
1717 IntRange {
1718 min: min.max(0),
1719 max: max.max(min).max(0),
1720 }
1721}
1722
1723fn role_name<'a>(columns: Option<&'a Value>, role: &str) -> Option<&'a str> {
1724 columns?.get(role).and_then(Value::as_str)
1725}
1726
1727fn string_arg<'a>(config: &'a PlannerConfig, key: &str) -> Option<&'a str> {
1728 config.args.get(key).and_then(Value::as_str)
1729}
1730
1731fn number_list(value: Option<&Value>) -> Vec<f64> {
1732 match value {
1733 Some(Value::Sequence(items)) => items.iter().filter_map(as_f64).collect(),
1734 _ => Vec::new(),
1735 }
1736}
1737
1738fn as_u32(value: &Value) -> Option<u32> {
1739 as_i128(value).and_then(|v| u32::try_from(v).ok())
1740}
1741
1742fn as_i128(value: &Value) -> Option<i128> {
1743 match value {
1744 Value::Number(number) => number
1745 .as_i64()
1746 .map(i128::from)
1747 .or_else(|| number.as_u64().map(i128::from))
1748 .or_else(|| number.as_f64().map(|float| float as i128)),
1749 Value::String(text) => text.trim().parse::<i128>().ok(),
1750 _ => None,
1751 }
1752}
1753
1754fn as_f64(value: &Value) -> Option<f64> {
1755 match value {
1756 Value::Number(number) => number.as_f64(),
1757 Value::String(text) => text.trim().parse::<f64>().ok(),
1758 _ => None,
1759 }
1760}
1761
1762#[cfg(test)]
1763mod tests {
1764 use super::*;
1765
1766 #[test]
1767 fn apportion_sums_exactly_for_every_mode() {
1768 let weights = [300i128, 500, 200];
1769 for mode in [
1770 Rounding::LargestRemainder,
1771 Rounding::LastLine,
1772 Rounding::Bankers,
1773 ] {
1774 for total in [0i128, 1, 7, 100, 999, 1_000_000] {
1775 let parts = apportion(total, &weights, mode);
1776 assert_eq!(
1777 parts.iter().sum::<i128>(),
1778 total,
1779 "mode {mode:?} total {total}"
1780 );
1781 assert!(parts.iter().all(|&p| p >= 0));
1782 }
1783 }
1784 }
1785
1786 #[test]
1787 fn apportion_last_line_dumps_residual_on_the_last_line() {
1788 let parts = apportion(10, &[1, 1, 1], Rounding::LastLine);
1790 assert_eq!(parts, vec![3, 3, 4]);
1791 }
1792
1793 #[test]
1794 fn bounded_allocation_matches_the_reference_algorithms() {
1795 let cases: &[&[i128]] = &[
1796 &[],
1797 &[0],
1798 &[0, 0, 0],
1799 &[1, 1, 1],
1800 &[300, 500, 200],
1801 &[7, 2, 13, 13, 1],
1802 ];
1803 for mode in [
1804 Rounding::LargestRemainder,
1805 Rounding::LastLine,
1806 Rounding::Bankers,
1807 ] {
1808 for &weights in cases {
1809 for total in [0, 1, 7, 10, 100, 999] {
1810 let plan =
1811 AllocationPlan::build(total, mode, || weights.iter().copied().map(Ok))
1812 .unwrap();
1813 let mut cursor = plan.cursor();
1814 let actual: Vec<i128> = weights
1815 .iter()
1816 .copied()
1817 .enumerate()
1818 .map(|(index, weight)| cursor.part(index, weight).unwrap())
1819 .collect();
1820 assert_eq!(actual, apportion(total, weights, mode));
1821 }
1822 }
1823 }
1824 }
1825
1826 #[test]
1827 fn rate_conversion_is_exact_for_common_rates() {
1828 assert_eq!(rate_to_num(0.0), 0);
1829 assert_eq!(rate_to_num(0.08), 80_000);
1830 assert_eq!(rate_to_num(0.25), 250_000);
1831 assert_eq!(rounded_rate(10_000, 80_000).unwrap(), 800);
1833 assert_eq!(rounded_rate(10_000, 250_000).unwrap(), 2_500);
1835 }
1836
1837 #[test]
1838 fn format_minor_renders_fixed_point() {
1839 assert_eq!(format_minor(1050, 2), "10.50");
1840 assert_eq!(format_minor(5, 2), "0.05");
1841 assert_eq!(format_minor(-1234, 2), "-12.34");
1842 assert_eq!(format_minor(42, 0), "42");
1843 }
1844
1845 #[test]
1846 fn decimal_precision_scale_parses_declarations() {
1847 assert_eq!(decimal_precision_scale("decimal(12,2)"), Some((12, 2)));
1848 assert_eq!(decimal_precision_scale("numeric(10, 3)"), Some((10, 3)));
1849 assert_eq!(decimal_precision_scale("bigint"), None);
1850 }
1851}