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 child_row_limit: Option<u64>,
445 parent_rows: u64,
448 child_rows_generated: u64,
450 tax: RateChoice,
451 discount: RateChoice,
452 shipping_minor: i128,
454 seed: SeedRoot,
455 pending_family: Option<OrderSummary>,
458}
459
460struct OrderSummary {
465 subtotal: i128,
466 discount: i128,
467 tax: i128,
468 shipping: i128,
469 grand_total: i128,
470 line_count: usize,
471 line_rng: rand_chacha::ChaCha8Rng,
472 discount_plan: AllocationPlan,
473 tax_plan: AllocationPlan,
474}
475
476struct LineTotals {
478 quantity: i128,
479 unit_price: i128,
480 discount: i128,
481 tax: i128,
482 line_total: i128,
483}
484
485struct RawLine {
487 quantity: i128,
488 unit_price: i128,
489 subtotal: i128,
490}
491
492fn draw_raw_line(
495 rng: &mut rand_chacha::ChaCha8Rng,
496 quantity: IntRange,
497 unit_price: IntRange,
498) -> Result<RawLine, GenerateError> {
499 let quantity = quantity.draw(rng).max(0);
500 let unit_price = unit_price.draw(rng).max(0);
501 let subtotal = quantity
502 .checked_mul(unit_price)
503 .ok_or_else(|| overflow("line subtotal (quantity * unit_price)"))?;
504 Ok(RawLine {
505 quantity,
506 unit_price,
507 subtotal,
508 })
509}
510
511struct RawLines {
513 rng: rand_chacha::ChaCha8Rng,
514 remaining: usize,
515 quantity: IntRange,
516 unit_price: IntRange,
517}
518
519impl RawLines {
520 fn new(
521 rng: rand_chacha::ChaCha8Rng,
522 count: usize,
523 quantity: IntRange,
524 unit_price: IntRange,
525 ) -> Self {
526 Self {
527 rng,
528 remaining: count,
529 quantity,
530 unit_price,
531 }
532 }
533}
534
535impl Iterator for RawLines {
536 type Item = Result<RawLine, GenerateError>;
537
538 fn next(&mut self) -> Option<Self::Item> {
539 if self.remaining == 0 {
540 return None;
541 }
542 self.remaining -= 1;
543 Some(draw_raw_line(&mut self.rng, self.quantity, self.unit_price))
544 }
545}
546
547#[derive(Clone)]
554struct AllocationPlan {
555 total: i128,
556 weight_total: i128,
557 count: usize,
558 mode: Rounding,
559 leftover: i128,
560 threshold: Option<i128>,
561 tie_slots: usize,
562 odd_ties: usize,
563}
564
565impl AllocationPlan {
566 fn build<F, I>(total: i128, mode: Rounding, weights: F) -> Result<Self, GenerateError>
567 where
568 F: Fn() -> I,
569 I: Iterator<Item = Result<i128, GenerateError>>,
570 {
571 let mut count = 0usize;
572 let mut weight_total = 0i128;
573 for weight in weights() {
574 let weight = weight?.max(0);
575 weight_total = weight_total
576 .checked_add(weight)
577 .ok_or_else(|| overflow("allocation weight total"))?;
578 count += 1;
579 }
580
581 let mut plan = Self {
582 total,
583 weight_total,
584 count,
585 mode,
586 leftover: 0,
587 threshold: None,
588 tie_slots: 0,
589 odd_ties: 0,
590 };
591 if count == 0 || total == 0 || weight_total <= 0 {
592 return Ok(plan);
593 }
594
595 let mut allocated = 0i128;
596 for weight in weights() {
597 let (floor, _) = proportional_share(total, weight?.max(0), weight_total)?;
598 allocated = allocated
599 .checked_add(floor)
600 .ok_or_else(|| overflow("allocated family amount"))?;
601 }
602 plan.leftover = total
603 .checked_sub(allocated)
604 .ok_or_else(|| overflow("family allocation residual"))?;
605
606 if mode == Rounding::LastLine || plan.leftover <= 0 {
607 return Ok(plan);
608 }
609
610 let wanted = usize::try_from(plan.leftover)
611 .map_err(|_| overflow("family allocation residual count"))?;
612 let mut low = 0i128;
615 let mut high = weight_total;
616 while low + 1 < high {
617 let mid = low + (high - low) / 2;
618 let mut at_or_above = 0usize;
619 for weight in weights() {
620 let (_, remainder) = proportional_share(total, weight?.max(0), weight_total)?;
621 if remainder >= mid {
622 at_or_above += 1;
623 }
624 }
625 if at_or_above >= wanted {
626 low = mid;
627 } else {
628 high = mid;
629 }
630 }
631 plan.threshold = Some(low);
632
633 let mut greater = 0usize;
634 let mut odd_ties = 0usize;
635 for weight in weights() {
636 let (floor, remainder) = proportional_share(total, weight?.max(0), weight_total)?;
637 if remainder > low {
638 greater += 1;
639 } else if remainder == low && floor.rem_euclid(2) == 1 {
640 odd_ties += 1;
641 }
642 }
643 plan.tie_slots = wanted.saturating_sub(greater);
644 plan.odd_ties = odd_ties;
645 Ok(plan)
646 }
647
648 fn cursor(&self) -> AllocationCursor {
649 AllocationCursor {
650 plan: self.clone(),
651 tied_seen: 0,
652 odd_seen: 0,
653 even_seen: 0,
654 }
655 }
656}
657
658struct AllocationCursor {
660 plan: AllocationPlan,
661 tied_seen: usize,
662 odd_seen: usize,
663 even_seen: usize,
664}
665
666impl AllocationCursor {
667 fn part(&mut self, index: usize, weight: i128) -> Result<i128, GenerateError> {
668 if self.plan.count == 0 || self.plan.total == 0 {
669 return Ok(0);
670 }
671 if self.plan.weight_total <= 0 {
672 return Ok(if index + 1 == self.plan.count {
673 self.plan.total
674 } else {
675 0
676 });
677 }
678
679 let (floor, remainder) =
680 proportional_share(self.plan.total, weight.max(0), self.plan.weight_total)?;
681 if self.plan.mode == Rounding::LastLine {
682 return if index + 1 == self.plan.count {
683 floor
684 .checked_add(self.plan.leftover)
685 .ok_or_else(|| overflow("last-line allocation"))
686 } else {
687 Ok(floor)
688 };
689 }
690
691 let Some(threshold) = self.plan.threshold else {
692 return Ok(floor);
693 };
694 let receives_extra = if remainder > threshold {
695 true
696 } else if remainder < threshold {
697 false
698 } else {
699 match self.plan.mode {
700 Rounding::LargestRemainder => {
701 let selected = self.tied_seen < self.plan.tie_slots;
702 self.tied_seen += 1;
703 selected
704 }
705 Rounding::Bankers => {
706 let odd_slots = self.plan.tie_slots.min(self.plan.odd_ties);
707 if floor.rem_euclid(2) == 1 {
708 let selected = self.odd_seen < odd_slots;
709 self.odd_seen += 1;
710 selected
711 } else {
712 let selected = self.even_seen < self.plan.tie_slots - odd_slots;
713 self.even_seen += 1;
714 selected
715 }
716 }
717 Rounding::LastLine => false,
718 }
719 };
720 if receives_extra {
721 floor
722 .checked_add(1)
723 .ok_or_else(|| overflow("ranked allocation"))
724 } else {
725 Ok(floor)
726 }
727 }
728}
729
730fn proportional_share(
731 total: i128,
732 weight: i128,
733 weight_total: i128,
734) -> Result<(i128, i128), GenerateError> {
735 let numerator = total
736 .checked_mul(weight)
737 .ok_or_else(|| overflow("proportional allocation"))?;
738 Ok((
739 numerator.div_euclid(weight_total),
740 numerator.rem_euclid(weight_total),
741 ))
742}
743
744struct TaxWeights {
746 raw: RawLines,
747 discount: AllocationCursor,
748 index: usize,
749}
750
751impl Iterator for TaxWeights {
752 type Item = Result<i128, GenerateError>;
753
754 fn next(&mut self) -> Option<Self::Item> {
755 let raw = self.raw.next()?;
756 Some(raw.and_then(|raw| {
757 let discount = self.discount.part(self.index, raw.subtotal)?;
758 self.index += 1;
759 raw.subtotal
760 .checked_sub(discount)
761 .ok_or_else(|| overflow("taxable line amount"))
762 }))
763 }
764}
765
766impl OrderFamilyPlanner {
767 fn compute(&mut self, order_index: u64) -> Result<OrderSummary, GenerateError> {
770 let mut rng = self.seed.stream(StreamId::operator(
771 self.parent_table.clone(),
772 "commerce.order_family",
773 format!("family.{order_index}"),
774 ));
775
776 let drawn_line_count = self.lines.draw(&mut rng).max(0);
777 let bounded_line_count = self.child_row_limit.map_or(drawn_line_count, |limit| {
778 let remaining = limit.saturating_sub(self.child_rows_generated);
779 let later_parents = self.parent_rows.saturating_sub(order_index + 1);
780 let minimum_per_parent = u64::try_from(self.lines.min).unwrap_or(u64::MAX);
781 let reserved = later_parents.saturating_mul(minimum_per_parent);
782 let available = remaining.saturating_sub(reserved);
783 drawn_line_count.min(i128::from(available))
784 });
785 let line_count =
786 usize::try_from(bounded_line_count).map_err(|_| overflow("order-family line count"))?;
787 let line_rng = rng.clone();
788
789 let mut subtotal: i128 = 0;
792 for _ in 0..line_count {
793 let raw = draw_raw_line(&mut rng, self.quantity, self.unit_price_minor)?;
794 subtotal = subtotal
795 .checked_add(raw.subtotal)
796 .ok_or_else(|| overflow("order subtotal"))?;
797 }
798
799 let discount_rate = self.discount.sample(rng.random::<f64>());
800 let tax_rate = self.tax.sample(rng.random::<f64>());
801
802 let discount_total = rounded_rate(subtotal, discount_rate)?;
803 let discount_plan = AllocationPlan::build(discount_total, self.rounding, || {
804 RawLines::new(
805 line_rng.clone(),
806 line_count,
807 self.quantity,
808 self.unit_price_minor,
809 )
810 .map(|raw| raw.map(|line| line.subtotal))
811 })?;
812
813 let order_taxable = subtotal
814 .checked_sub(discount_total)
815 .ok_or_else(|| overflow("order taxable amount"))?;
816 let tax_total = rounded_rate(order_taxable, tax_rate)?;
817 let tax_plan = AllocationPlan::build(tax_total, self.rounding, || TaxWeights {
818 raw: RawLines::new(
819 line_rng.clone(),
820 line_count,
821 self.quantity,
822 self.unit_price_minor,
823 ),
824 discount: discount_plan.cursor(),
825 index: 0,
826 })?;
827
828 let shipping = self.shipping_minor;
829 let grand_total = subtotal
830 .checked_sub(discount_total)
831 .and_then(|value| value.checked_add(tax_total))
832 .and_then(|value| value.checked_add(shipping))
833 .ok_or_else(|| overflow("order grand total"))?;
834
835 let summary = OrderSummary {
836 subtotal,
837 discount: discount_total,
838 tax: tax_total,
839 shipping,
840 grand_total,
841 line_count,
842 line_rng,
843 discount_plan,
844 tax_plan,
845 };
846 let generated =
847 u64::try_from(line_count).map_err(|_| overflow("realized child row count"))?;
848 self.child_rows_generated = self
849 .child_rows_generated
850 .checked_add(generated)
851 .ok_or_else(|| overflow("realized child row total"))?;
852 Ok(summary)
853 }
854
855 fn render_money(&self, minor: i128, family: &SqlTypeFamily) -> GeneratedValue {
857 match family {
858 SqlTypeFamily::Decimal => GeneratedValue::Decimal {
859 minor,
860 scale: self.scale,
861 },
862 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => GeneratedValue::Integer(minor),
863 _ => GeneratedValue::Text(format_minor(minor, self.scale)),
864 }
865 }
866
867 fn parent_value(
869 &self,
870 role: ParentRole,
871 totals: &OrderSummary,
872 family: &SqlTypeFamily,
873 ) -> GeneratedValue {
874 let minor = match role {
875 ParentRole::Subtotal => totals.subtotal,
876 ParentRole::Discount => totals.discount,
877 ParentRole::Tax => totals.tax,
878 ParentRole::Shipping => totals.shipping,
879 ParentRole::Total => totals.grand_total,
880 };
881 self.render_money(minor, family)
882 }
883
884 fn child_value(
886 &self,
887 role: ChildRole,
888 line: &LineTotals,
889 family: &SqlTypeFamily,
890 ) -> GeneratedValue {
891 match role {
892 ChildRole::Quantity => match family {
893 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => {
894 GeneratedValue::Integer(line.quantity)
895 }
896 _ => GeneratedValue::Text(line.quantity.to_string()),
897 },
898 ChildRole::UnitPrice => self.render_money(line.unit_price, family),
899 ChildRole::Discount => self.render_money(line.discount, family),
900 ChildRole::Tax => self.render_money(line.tax, family),
901 ChildRole::LineTotal => self.render_money(line.line_total, family),
902 }
903 }
904}
905
906struct OrderFamilyChildRows<'a> {
908 planner: &'a OrderFamilyPlanner,
909 raw: RawLines,
910 discount: AllocationCursor,
911 tax: AllocationCursor,
912 index: usize,
913}
914
915impl<'a> OrderFamilyChildRows<'a> {
916 fn new(planner: &'a OrderFamilyPlanner, summary: OrderSummary) -> Self {
917 Self {
918 raw: RawLines::new(
919 summary.line_rng,
920 summary.line_count,
921 planner.quantity,
922 planner.unit_price_minor,
923 ),
924 discount: summary.discount_plan.cursor(),
925 tax: summary.tax_plan.cursor(),
926 planner,
927 index: 0,
928 }
929 }
930}
931
932impl Iterator for OrderFamilyChildRows<'_> {
933 type Item = Result<Vec<GeneratedValue>, GenerateError>;
934
935 fn next(&mut self) -> Option<Self::Item> {
936 let raw = match self.raw.next()? {
937 Ok(raw) => raw,
938 Err(error) => return Some(Err(error)),
939 };
940 let result = (|| {
941 let discount = self.discount.part(self.index, raw.subtotal)?;
942 let taxable = raw
943 .subtotal
944 .checked_sub(discount)
945 .ok_or_else(|| overflow("taxable line amount"))?;
946 let tax = self.tax.part(self.index, taxable)?;
947 let line_total = taxable
948 .checked_add(tax)
949 .ok_or_else(|| overflow("child line total"))?;
950 self.index += 1;
951
952 let line = LineTotals {
953 quantity: raw.quantity,
954 unit_price: raw.unit_price,
955 discount,
956 tax,
957 line_total,
958 };
959 let mut values = Vec::with_capacity(self.planner.child_writes.len());
960 for (role, family) in self
961 .planner
962 .child_roles
963 .iter()
964 .zip(&self.planner.child_families)
965 {
966 values.push(self.planner.child_value(*role, &line, family));
967 }
968 Ok(values)
969 })();
970 Some(result)
971 }
972}
973
974impl CompiledPlanner for OrderFamilyPlanner {
975 fn writes(&self) -> &[String] {
976 &self.parent_writes
977 }
978
979 fn generate_row(
980 &mut self,
981 row_index: u64,
982 output: &mut [GeneratedValue],
983 ) -> Result<(), GenerateError> {
984 let totals = self.compute(row_index)?;
985
986 for (slot, role) in output.iter_mut().zip(&self.parent_roles) {
987 let family = self.parent_family_for(*role);
988 *slot = self.parent_value(*role, &totals, family);
989 }
990
991 self.pending_family = Some(totals);
992 Ok(())
993 }
994
995 fn family_child_table(&self) -> Option<&str> {
996 Some(&self.child_table)
997 }
998
999 fn family_relationship(&self) -> Option<&str> {
1000 Some(&self.relationship)
1001 }
1002
1003 fn child_writes(&self) -> &[String] {
1004 &self.child_writes
1005 }
1006
1007 fn take_family_children(
1008 &mut self,
1009 ) -> Box<dyn Iterator<Item = Result<Vec<GeneratedValue>, GenerateError>> + '_> {
1010 match self.pending_family.take() {
1011 Some(summary) => Box::new(OrderFamilyChildRows::new(self, summary)),
1012 None => Box::new(std::iter::empty()),
1013 }
1014 }
1015
1016 fn family_sum_checks(&self) -> Vec<crate::generate::registry::FamilySumCheck> {
1017 use crate::generate::registry::FamilySumCheck;
1018
1019 let pure_sum_roles = [ParentRole::Discount, ParentRole::Tax];
1026 let child_role_of = |parent: ParentRole| match parent {
1027 ParentRole::Discount => Some(ChildRole::Discount),
1028 ParentRole::Tax => Some(ChildRole::Tax),
1029 _ => None,
1030 };
1031
1032 pure_sum_roles
1033 .into_iter()
1034 .filter_map(|parent_role| {
1035 let child_role = child_role_of(parent_role)?;
1036 let parent_column = self.column_for_parent_role(parent_role)?;
1037 let child_column = self.column_for_child_role(child_role)?;
1038 Some(FamilySumCheck {
1039 relationship: self.relationship.clone(),
1040 parent_column,
1041 child_column,
1042 })
1043 })
1044 .collect()
1045 }
1046}
1047
1048impl OrderFamilyPlanner {
1049 fn column_for_parent_role(&self, role: ParentRole) -> Option<String> {
1052 self.parent_roles
1053 .iter()
1054 .position(|candidate| *candidate == role)
1055 .map(|index| self.parent_writes[index].clone())
1056 }
1057
1058 fn column_for_child_role(&self, role: ChildRole) -> Option<String> {
1061 self.child_roles
1062 .iter()
1063 .position(|candidate| *candidate == role)
1064 .map(|index| self.child_writes[index].clone())
1065 }
1066
1067 fn parent_family_for(&self, role: ParentRole) -> &SqlTypeFamily {
1068 let index = self
1069 .parent_roles
1070 .iter()
1071 .position(|candidate| *candidate == role)
1072 .expect("role is in parent_roles");
1073 &self.parent_families[index]
1074 }
1075}
1076
1077fn rounded_rate(amount: i128, rate_num: i128) -> Result<i128, GenerateError> {
1079 if rate_num == 0 || amount == 0 {
1080 return Ok(0);
1081 }
1082 let numerator = amount
1083 .checked_mul(rate_num)
1084 .ok_or_else(|| overflow("rate * amount"))?;
1085 Ok((numerator + RATE_DEN / 2).div_euclid(RATE_DEN))
1087}
1088
1089fn format_minor(minor: i128, scale: u32) -> String {
1092 if scale == 0 {
1093 return minor.to_string();
1094 }
1095 let divisor = 10i128.pow(scale);
1096 let sign = if minor < 0 { "-" } else { "" };
1097 let magnitude = minor.abs();
1098 let whole = magnitude / divisor;
1099 let frac = magnitude % divisor;
1100 format!("{sign}{whole}.{frac:0width$}", width = scale as usize)
1101}
1102
1103fn overflow(what: &str) -> GenerateError {
1105 GenerateError::Overflow(format!(
1106 "commerce.order_family: {what} overflows the representable minor-unit range"
1107 ))
1108}
1109
1110fn compile_order_family(
1115 config: &PlannerConfig,
1116 context: &CompileContext<'_>,
1117) -> Result<OrderFamilyPlanner, DiagnosticBag> {
1118 let mut bag = DiagnosticBag::default();
1119 let parent = context.table();
1120 let path = context.path();
1121
1122 reject_flat_form(config, path, &mut bag);
1123
1124 let facts = config.args.get(FAMILY_FACTS_KEY);
1125 let child_found = facts
1126 .and_then(|f| f.get("child_found"))
1127 .and_then(Value::as_bool)
1128 .unwrap_or(false);
1129 let child_name = string_arg(config, "children")
1130 .unwrap_or_default()
1131 .to_string();
1132
1133 if !child_found {
1134 bag.error(
1135 crate::diagnostic::codes::ORDER_FAMILY_CHILD_UNKNOWN.code,
1136 format!("{path}.children"),
1137 format!(
1138 "commerce.order_family `children` names table `{child_name}`, which is not a table in the model"
1139 ),
1140 );
1141 }
1142
1143 let rel_name = string_arg(config, "relationship")
1144 .unwrap_or_default()
1145 .to_string();
1146 let rel_on_child = facts
1147 .and_then(|f| f.get("rel_on_child"))
1148 .and_then(Value::as_bool)
1149 .unwrap_or(false);
1150 if child_found && !rel_on_child {
1151 bag.error(
1152 crate::diagnostic::codes::ORDER_FAMILY_RELATIONSHIP.code,
1153 format!("{path}.relationship"),
1154 format!(
1155 "commerce.order_family `relationship` `{rel_name}` is not a relationship declared on child table `{child_name}` that references parent `{}`",
1156 parent.name
1157 ),
1158 );
1159 }
1160
1161 let scale = match config.args.get("currency_scale").and_then(as_u32) {
1162 Some(scale) if scale <= 18 => scale,
1165 Some(scale) => {
1166 bag.error(
1167 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1168 format!("{path}.currency_scale"),
1169 format!(
1170 "commerce.order_family `currency_scale` must be between 0 and 18 (got {scale})"
1171 ),
1172 );
1173 0
1174 }
1175 None => {
1176 bag.error(
1177 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1178 format!("{path}.currency_scale"),
1179 "commerce.order_family requires a `currency_scale`".to_string(),
1180 );
1181 0
1182 }
1183 };
1184
1185 let rounding = match config.args.get("rounding").and_then(Value::as_str) {
1186 Some(name) => match Rounding::parse(name) {
1187 Some(rounding) => rounding,
1188 None => {
1189 bag.error(
1190 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1191 format!("{path}.rounding"),
1192 format!("commerce.order_family `rounding` `{name}` is not one of `largest_remainder`, `last_line`, `bankers`"),
1193 );
1194 Rounding::LargestRemainder
1195 }
1196 },
1197 None => {
1198 bag.error(
1199 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1200 format!("{path}.rounding"),
1201 "commerce.order_family requires a `rounding` mode".to_string(),
1202 );
1203 Rounding::LargestRemainder
1204 }
1205 };
1206
1207 let (parent_writes, parent_roles, parent_families) =
1209 resolve_parent_roles(config, parent, scale, path, &mut bag);
1210
1211 let (child_writes, child_roles, child_families) =
1213 resolve_child_roles(config, facts, &child_name, scale, path, &mut bag);
1214
1215 let quantity = int_range(config.args.get("quantity"), 1, 1);
1216 let unit_price_minor = unit_price_range(config.args.get("unit_price"), scale);
1217 let lines = compile_line_range(facts, path, &mut bag);
1218 let child_row_limit = facts
1219 .and_then(|facts| facts.get("child_row_limit"))
1220 .and_then(Value::as_u64);
1221 let parent_rows = facts
1222 .and_then(|facts| facts.get("parent_rows"))
1223 .and_then(Value::as_u64)
1224 .unwrap_or(0);
1225 let tax = compile_rate(config.args.get("tax"), "tax", path, &mut bag);
1226 let discount = compile_rate(config.args.get("discount"), "discount", path, &mut bag);
1227 let shipping_minor = compile_shipping(config.args.get("shipping"), scale);
1228
1229 check_overflow(
1232 &lines,
1233 &quantity,
1234 &unit_price_minor,
1235 &tax,
1236 shipping_minor,
1237 &parent_writes,
1238 parent,
1239 facts,
1240 &child_writes,
1241 &child_name,
1242 path,
1243 &mut bag,
1244 );
1245
1246 if bag.has_errors() {
1247 return Err(bag);
1248 }
1249
1250 Ok(OrderFamilyPlanner {
1251 parent_table: parent.name.clone(),
1252 child_table: child_name,
1253 relationship: rel_name,
1254 parent_writes,
1255 parent_roles,
1256 child_writes,
1257 child_roles,
1258 scale,
1259 parent_families,
1260 child_families,
1261 rounding,
1262 quantity,
1263 unit_price_minor,
1264 lines,
1265 child_row_limit,
1266 parent_rows,
1267 child_rows_generated: 0,
1268 tax,
1269 discount,
1270 shipping_minor,
1271 seed: context.seed(),
1272 pending_family: None,
1273 })
1274}
1275
1276fn reject_flat_form(config: &PlannerConfig, path: &str, bag: &mut DiagnosticBag) {
1279 for key in [
1280 "subtotal",
1281 "line_total",
1282 "grand_total",
1283 "line_items",
1284 "items",
1285 ] {
1286 if config.args.contains_key(key) {
1287 bag.error(
1288 crate::diagnostic::codes::ORDER_FAMILY_UNKNOWN_FIELD.code,
1289 format!("{path}.{key}"),
1290 format!(
1291 "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)"
1292 ),
1293 );
1294 }
1295 }
1296}
1297
1298const PARENT_ROLE_ORDER: [(&str, ParentRole, bool); 5] = [
1300 ("subtotal", ParentRole::Subtotal, true),
1301 ("discount", ParentRole::Discount, false),
1302 ("tax", ParentRole::Tax, false),
1303 ("shipping", ParentRole::Shipping, false),
1304 ("total", ParentRole::Total, true),
1305];
1306
1307const CHILD_ROLE_ORDER: [(&str, ChildRole, bool); 5] = [
1310 ("quantity", ChildRole::Quantity, true),
1311 ("unit_price", ChildRole::UnitPrice, true),
1312 ("discount", ChildRole::Discount, false),
1313 ("tax", ChildRole::Tax, false),
1314 ("line_total", ChildRole::LineTotal, true),
1315];
1316
1317fn resolve_parent_roles(
1321 config: &PlannerConfig,
1322 parent: &PortableTable,
1323 scale: u32,
1324 path: &str,
1325 bag: &mut DiagnosticBag,
1326) -> (Vec<String>, Vec<ParentRole>, Vec<SqlTypeFamily>) {
1327 let columns = config.args.get("columns");
1328 let mut writes = Vec::new();
1329 let mut roles = Vec::new();
1330 let mut families = Vec::new();
1331 for (key, role, required) in PARENT_ROLE_ORDER {
1332 let Some(name) = role_name(columns, key) else {
1333 if required {
1334 bag.error(
1335 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1336 format!("{path}.columns.{key}"),
1337 format!("commerce.order_family requires a `{key}` column under `columns`"),
1338 );
1339 }
1340 continue;
1341 };
1342 match parent.columns.iter().find(|column| column.name == name) {
1343 Some(column) => {
1344 check_money_scale(
1345 &column.source_type,
1346 &column.family,
1347 scale,
1348 &format!("{path}.columns.{key}"),
1349 &column.name,
1350 bag,
1351 );
1352 writes.push(column.name.clone());
1353 roles.push(role);
1354 families.push(column.family.clone());
1355 }
1356 None => {
1357 bag.error(
1358 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1359 format!("{path}.columns.{key}"),
1360 format!(
1361 "commerce.order_family `{key}` column `{name}` does not exist on parent table `{}`",
1362 parent.name
1363 ),
1364 );
1365 }
1366 }
1367 }
1368 (writes, roles, families)
1369}
1370
1371fn resolve_child_roles(
1373 config: &PlannerConfig,
1374 facts: Option<&Value>,
1375 child_name: &str,
1376 scale: u32,
1377 path: &str,
1378 bag: &mut DiagnosticBag,
1379) -> (Vec<String>, Vec<ChildRole>, Vec<SqlTypeFamily>) {
1380 let columns = config.args.get("child_columns");
1381 let child_types = facts.and_then(|f| f.get("child_columns"));
1382 let mut writes = Vec::new();
1383 let mut roles = Vec::new();
1384 let mut families = Vec::new();
1385 for (key, role, required) in CHILD_ROLE_ORDER {
1386 let Some(name) = role_name(columns, key) else {
1387 if required {
1388 bag.error(
1389 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1390 format!("{path}.child_columns.{key}"),
1391 format!(
1392 "commerce.order_family requires a `{key}` column under `child_columns`"
1393 ),
1394 );
1395 }
1396 continue;
1397 };
1398 let source_type = child_types
1401 .and_then(|types| types.get(name))
1402 .and_then(Value::as_str);
1403 match source_type {
1404 Some(source_type) => {
1405 let family = family_of_source_type(source_type);
1406 if role != ChildRole::Quantity {
1407 check_money_scale(
1408 source_type,
1409 &family,
1410 scale,
1411 &format!("{path}.child_columns.{key}"),
1412 name,
1413 bag,
1414 );
1415 }
1416 writes.push(name.to_string());
1417 roles.push(role);
1418 families.push(family);
1419 }
1420 None => {
1421 bag.error(
1422 crate::diagnostic::codes::ORDER_FAMILY_COLUMN_MISSING.code,
1423 format!("{path}.child_columns.{key}"),
1424 format!(
1425 "commerce.order_family `{key}` column `{name}` does not exist on child table `{child_name}`"
1426 ),
1427 );
1428 }
1429 }
1430 }
1431 (writes, roles, families)
1432}
1433
1434fn check_money_scale(
1438 source_type: &str,
1439 family: &SqlTypeFamily,
1440 scale: u32,
1441 path: &str,
1442 column: &str,
1443 bag: &mut DiagnosticBag,
1444) {
1445 if *family != SqlTypeFamily::Decimal {
1446 return;
1447 }
1448 if let Some((_, declared_scale)) = decimal_precision_scale(source_type) {
1449 if declared_scale != scale {
1450 bag.error(
1451 crate::diagnostic::codes::ORDER_FAMILY_SCALE.code,
1452 path.to_string(),
1453 format!(
1454 "commerce.order_family `currency_scale` is {scale}, but money column `{column}` is declared `{source_type}` with scale {declared_scale}; the currency scale is ambiguous"
1455 ),
1456 );
1457 }
1458 }
1459}
1460
1461fn compile_line_range(facts: Option<&Value>, path: &str, bag: &mut DiagnosticBag) -> LineDist {
1465 let min = facts
1466 .and_then(|f| f.get("dist_min"))
1467 .and_then(as_f64)
1468 .unwrap_or(1.0);
1469 let max = facts
1470 .and_then(|f| f.get("dist_max"))
1471 .and_then(as_f64)
1472 .unwrap_or(min);
1473 let mean = facts.and_then(|f| f.get("dist_mean")).and_then(as_f64);
1474 let kind = match facts
1475 .and_then(|f| f.get("dist_kind"))
1476 .and_then(Value::as_str)
1477 {
1478 Some("fixed") => LineKind::Fixed,
1479 Some("uniform") => LineKind::Uniform,
1480 _ => LineKind::MeanRespecting,
1484 };
1485 let min_lines = min.max(0.0).ceil() as i128;
1486 let max_lines = max.max(0.0).floor() as i128;
1487 if max_lines < min_lines || (max_lines == 0 && min_lines > 0) {
1488 bag.error(
1489 crate::diagnostic::codes::ORDER_FAMILY_ZERO_LINES.code,
1490 path.to_string(),
1491 format!(
1492 "commerce.order_family child distribution allows at most {max_lines} line(s) but requires at least {min_lines}; no order could satisfy the minimum"
1493 ),
1494 );
1495 }
1496 let min_lines = min_lines.max(0);
1497 let max_lines = max_lines.max(min_lines);
1498 let mean = mean
1501 .unwrap_or(min_lines.max(1) as f64)
1502 .clamp(min_lines as f64, max_lines as f64);
1503 LineDist {
1504 min: min_lines,
1505 max: max_lines,
1506 mean,
1507 kind,
1508 }
1509}
1510
1511fn compile_rate(
1513 value: Option<&Value>,
1514 what: &str,
1515 path: &str,
1516 bag: &mut DiagnosticBag,
1517) -> RateChoice {
1518 let Some(value) = value else {
1519 return RateChoice::zero();
1520 };
1521 match value.get("kind").and_then(Value::as_str) {
1522 Some("weighted_choice") | None if value.get("rates").is_some() => {
1523 let rates = number_list(value.get("rates"));
1524 let weights = number_list(value.get("weights"));
1525 if rates.is_empty() || weights.len() != rates.len() {
1526 bag.error(
1527 crate::diagnostic::codes::ORDER_FAMILY_CONFIG.code,
1528 format!("{path}.{what}"),
1529 format!("commerce.order_family `{what}` weighted_choice needs matching `rates` and `weights` lists"),
1530 );
1531 return RateChoice::zero();
1532 }
1533 let nums: Vec<i128> = rates.iter().map(|rate| rate_to_num(*rate)).collect();
1534 RateChoice::weighted(&nums, &weights)
1535 }
1536 Some("fixed") | Some("fixed_rate") => {
1537 let rate = value.get("rate").and_then(as_f64).unwrap_or(0.0);
1538 RateChoice::fixed(rate_to_num(rate))
1539 }
1540 _ => {
1541 if let Some(rate) = value.get("rate").and_then(as_f64) {
1543 RateChoice::fixed(rate_to_num(rate))
1544 } else {
1545 RateChoice::zero()
1546 }
1547 }
1548 }
1549}
1550
1551fn compile_shipping(value: Option<&Value>, scale: u32) -> i128 {
1553 let Some(value) = value else {
1554 return 0;
1555 };
1556 if let Some(minor) = value.get("amount_minor").and_then(as_i128) {
1557 return minor.max(0);
1558 }
1559 if let Some(amount) = value.get("amount").and_then(as_f64) {
1560 return to_minor(amount, scale).max(0);
1561 }
1562 0
1563}
1564
1565#[allow(clippy::too_many_arguments)]
1568fn check_overflow(
1569 lines: &LineDist,
1570 quantity: &IntRange,
1571 unit_price: &IntRange,
1572 tax: &RateChoice,
1573 shipping_minor: i128,
1574 parent_writes: &[String],
1575 parent: &PortableTable,
1576 facts: Option<&Value>,
1577 child_writes: &[String],
1578 child_name: &str,
1579 path: &str,
1580 bag: &mut DiagnosticBag,
1581) {
1582 let max_rate = tax
1583 .cumulative
1584 .iter()
1585 .map(|(rate, _)| *rate)
1586 .max()
1587 .unwrap_or(0);
1588 let per_line = match quantity.max.checked_mul(unit_price.max) {
1589 Some(value) => value,
1590 None => {
1591 bag.error(
1592 crate::diagnostic::codes::ORDER_FAMILY_OVERFLOW.code,
1593 path.to_string(),
1594 "commerce.order_family maximum line subtotal (quantity * unit_price) overflows i128".to_string(),
1595 );
1596 return;
1597 }
1598 };
1599 let subtotal_max = per_line.saturating_mul(lines.max.max(0));
1600 let tax_max = subtotal_max.saturating_mul(max_rate) / RATE_DEN;
1601 let grand_max = subtotal_max
1604 .saturating_add(tax_max)
1605 .saturating_add(shipping_minor.max(0));
1606 let per_line_tax_max = per_line.saturating_mul(max_rate) / RATE_DEN;
1610 let child_max = per_line.saturating_add(per_line_tax_max);
1611
1612 for name in parent_writes {
1614 if let Some(column) = parent.columns.iter().find(|column| &column.name == name) {
1615 report_capacity(
1616 &column.source_type,
1617 grand_max,
1618 name,
1619 &parent.name,
1620 path,
1621 bag,
1622 );
1623 }
1624 }
1625 let child_types = facts.and_then(|f| f.get("child_columns"));
1627 for name in child_writes {
1628 if let Some(source_type) = child_types
1629 .and_then(|types| types.get(name))
1630 .and_then(Value::as_str)
1631 {
1632 report_capacity(source_type, child_max, name, child_name, path, bag);
1633 }
1634 }
1635}
1636
1637fn report_capacity(
1640 source_type: &str,
1641 max_minor: i128,
1642 column: &str,
1643 table: &str,
1644 path: &str,
1645 bag: &mut DiagnosticBag,
1646) {
1647 if let Some((precision, _)) = decimal_precision_scale(source_type) {
1648 let capacity = 10i128
1649 .checked_pow(precision)
1650 .map(|v| v - 1)
1651 .unwrap_or(i128::MAX);
1652 if max_minor > capacity {
1653 bag.error(
1654 crate::diagnostic::codes::ORDER_FAMILY_OVERFLOW.code,
1655 path.to_string(),
1656 format!(
1657 "commerce.order_family can reach {max_minor} minor units, exceeding the capacity {capacity} of money column `{column}` on table `{table}` (declared `{source_type}`)"
1658 ),
1659 );
1660 }
1661 }
1662}
1663
1664fn rate_to_num(rate: f64) -> i128 {
1668 (rate * RATE_DEN as f64).round() as i128
1669}
1670
1671fn to_minor(amount: f64, scale: u32) -> i128 {
1673 (amount * 10f64.powi(scale as i32)).round() as i128
1674}
1675
1676fn decimal_precision_scale(source_type: &str) -> Option<(u32, u32)> {
1678 let open = source_type.find('(')?;
1679 let close = source_type.find(')')?;
1680 let inner = source_type.get(open + 1..close)?;
1681 let mut parts = inner.split(',');
1682 let precision = parts.next()?.trim().parse::<u32>().ok()?;
1683 let scale = parts
1684 .next()
1685 .and_then(|s| s.trim().parse::<u32>().ok())
1686 .unwrap_or(0);
1687 Some((precision, scale))
1688}
1689
1690fn family_of_source_type(source_type: &str) -> SqlTypeFamily {
1692 let lower = source_type.to_lowercase();
1693 if lower.starts_with("decimal") || lower.starts_with("numeric") {
1694 SqlTypeFamily::Decimal
1695 } else if lower.starts_with("bigint") {
1696 SqlTypeFamily::BigInteger
1697 } else if lower.starts_with("int")
1698 || lower.starts_with("smallint")
1699 || lower.starts_with("tinyint")
1700 {
1701 SqlTypeFamily::Integer
1702 } else {
1703 SqlTypeFamily::Other
1704 }
1705}
1706
1707fn int_range(value: Option<&Value>, default_min: i128, default_max: i128) -> IntRange {
1709 let min = value
1710 .and_then(|v| v.get("min"))
1711 .and_then(as_i128)
1712 .unwrap_or(default_min);
1713 let max = value
1714 .and_then(|v| v.get("max"))
1715 .and_then(as_i128)
1716 .unwrap_or(default_max.max(min));
1717 IntRange {
1718 min: min.max(0),
1719 max: max.max(min).max(0),
1720 }
1721}
1722
1723fn unit_price_range(value: Option<&Value>, scale: u32) -> IntRange {
1726 let Some(value) = value else {
1727 return IntRange {
1728 min: 100,
1729 max: 10_000,
1730 };
1731 };
1732 if let (Some(min), Some(max)) = (
1733 value.get("min_minor").and_then(as_i128),
1734 value.get("max_minor").and_then(as_i128),
1735 ) {
1736 return IntRange {
1737 min: min.max(0),
1738 max: max.max(min).max(0),
1739 };
1740 }
1741 let min = value
1742 .get("min")
1743 .and_then(as_f64)
1744 .map(|v| to_minor(v, scale))
1745 .unwrap_or(100);
1746 let max = value
1747 .get("max")
1748 .and_then(as_f64)
1749 .map(|v| to_minor(v, scale))
1750 .unwrap_or(min.max(10_000));
1751 IntRange {
1752 min: min.max(0),
1753 max: max.max(min).max(0),
1754 }
1755}
1756
1757fn role_name<'a>(columns: Option<&'a Value>, role: &str) -> Option<&'a str> {
1758 columns?.get(role).and_then(Value::as_str)
1759}
1760
1761fn string_arg<'a>(config: &'a PlannerConfig, key: &str) -> Option<&'a str> {
1762 config.args.get(key).and_then(Value::as_str)
1763}
1764
1765fn number_list(value: Option<&Value>) -> Vec<f64> {
1766 match value {
1767 Some(Value::Sequence(items)) => items.iter().filter_map(as_f64).collect(),
1768 _ => Vec::new(),
1769 }
1770}
1771
1772fn as_u32(value: &Value) -> Option<u32> {
1773 as_i128(value).and_then(|v| u32::try_from(v).ok())
1774}
1775
1776fn as_i128(value: &Value) -> Option<i128> {
1777 match value {
1778 Value::Number(number) => number
1779 .as_i64()
1780 .map(i128::from)
1781 .or_else(|| number.as_u64().map(i128::from))
1782 .or_else(|| number.as_f64().map(|float| float as i128)),
1783 Value::String(text) => text.trim().parse::<i128>().ok(),
1784 _ => None,
1785 }
1786}
1787
1788fn as_f64(value: &Value) -> Option<f64> {
1789 match value {
1790 Value::Number(number) => number.as_f64(),
1791 Value::String(text) => text.trim().parse::<f64>().ok(),
1792 _ => None,
1793 }
1794}
1795
1796#[cfg(test)]
1797mod tests {
1798 use super::*;
1799
1800 #[test]
1801 fn apportion_sums_exactly_for_every_mode() {
1802 let weights = [300i128, 500, 200];
1803 for mode in [
1804 Rounding::LargestRemainder,
1805 Rounding::LastLine,
1806 Rounding::Bankers,
1807 ] {
1808 for total in [0i128, 1, 7, 100, 999, 1_000_000] {
1809 let parts = apportion(total, &weights, mode);
1810 assert_eq!(
1811 parts.iter().sum::<i128>(),
1812 total,
1813 "mode {mode:?} total {total}"
1814 );
1815 assert!(parts.iter().all(|&p| p >= 0));
1816 }
1817 }
1818 }
1819
1820 #[test]
1821 fn apportion_last_line_dumps_residual_on_the_last_line() {
1822 let parts = apportion(10, &[1, 1, 1], Rounding::LastLine);
1824 assert_eq!(parts, vec![3, 3, 4]);
1825 }
1826
1827 #[test]
1828 fn bounded_allocation_matches_the_reference_algorithms() {
1829 let cases: &[&[i128]] = &[
1830 &[],
1831 &[0],
1832 &[0, 0, 0],
1833 &[1, 1, 1],
1834 &[300, 500, 200],
1835 &[7, 2, 13, 13, 1],
1836 ];
1837 for mode in [
1838 Rounding::LargestRemainder,
1839 Rounding::LastLine,
1840 Rounding::Bankers,
1841 ] {
1842 for &weights in cases {
1843 for total in [0, 1, 7, 10, 100, 999] {
1844 let plan =
1845 AllocationPlan::build(total, mode, || weights.iter().copied().map(Ok))
1846 .unwrap();
1847 let mut cursor = plan.cursor();
1848 let actual: Vec<i128> = weights
1849 .iter()
1850 .copied()
1851 .enumerate()
1852 .map(|(index, weight)| cursor.part(index, weight).unwrap())
1853 .collect();
1854 assert_eq!(actual, apportion(total, weights, mode));
1855 }
1856 }
1857 }
1858 }
1859
1860 #[test]
1861 fn rate_conversion_is_exact_for_common_rates() {
1862 assert_eq!(rate_to_num(0.0), 0);
1863 assert_eq!(rate_to_num(0.08), 80_000);
1864 assert_eq!(rate_to_num(0.25), 250_000);
1865 assert_eq!(rounded_rate(10_000, 80_000).unwrap(), 800);
1867 assert_eq!(rounded_rate(10_000, 250_000).unwrap(), 2_500);
1869 }
1870
1871 #[test]
1872 fn format_minor_renders_fixed_point() {
1873 assert_eq!(format_minor(1050, 2), "10.50");
1874 assert_eq!(format_minor(5, 2), "0.05");
1875 assert_eq!(format_minor(-1234, 2), "-12.34");
1876 assert_eq!(format_minor(42, 0), "42");
1877 }
1878
1879 #[test]
1880 fn decimal_precision_scale_parses_declarations() {
1881 assert_eq!(decimal_precision_scale("decimal(12,2)"), Some((12, 2)));
1882 assert_eq!(decimal_precision_scale("numeric(10, 3)"), Some((10, 3)));
1883 assert_eq!(decimal_precision_scale("bigint"), None);
1884 }
1885}