pricing.rs (11115B)
1 use crate::{Decimal, MinorAmount, Money, MoneyError, PositiveDecimal}; 2 use alloc::{boxed::Box, vec::Vec}; 3 use core::fmt; 4 5 /// Fixed calculation rule: discount first, half-even once per net line. 6 pub const PRICING_PROFILE: &str = "half_even_net_line_v1"; 7 /// Largest supported number of rounded lines in one aggregate. 8 pub const MAX_PRICED_LINES: usize = 32; 9 10 /// Validated discount in integer basis points, without an implicit default. 11 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] 12 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 13 #[cfg_attr(feature = "serde", serde(transparent))] 14 pub struct DiscountBps(u16); 15 16 impl DiscountBps { 17 /// Explicit absence of a discount. 18 pub const NONE: Self = Self(0); 19 /// Explicit full discount; the resulting price is free, not quote-required. 20 pub const FULL: Self = Self(10_000); 21 22 /// Admits exactly 0 through 10000 basis points. 23 pub const fn new(value: u16) -> Result<Self, PricingError> { 24 if value > 10_000 { 25 Err(PricingError::InvalidDiscount) 26 } else { 27 Ok(Self(value)) 28 } 29 } 30 31 /// Returns the exact bounded integer basis points. 32 pub const fn get(self) -> u16 { 33 self.0 34 } 35 } 36 37 /// One threshold/rate pair, expressed in its enclosing price's sale-unit basis. 38 #[derive(Clone, Copy, Eq, PartialEq)] 39 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 40 pub struct PriceTier { 41 from: Decimal, 42 rate: Money, 43 } 44 45 impl PriceTier { 46 /// Captures validated values; the enclosing price checks order and currency. 47 pub const fn new(from: Decimal, rate: Money) -> Self { 48 Self { from, rate } 49 } 50 /// Returns the inclusive threshold; an explicit zero threshold is valid. 51 pub const fn from(self) -> Decimal { 52 self.from 53 } 54 /// Returns the exact tier rate, without currency conversion. 55 pub const fn rate(self) -> Money { 56 self.rate 57 } 58 } 59 60 /// Validated fixed-price calculation inputs for one selected sale unit. 61 /// 62 /// Amounts, basis and thresholds share that sale unit. This type performs no 63 /// physical conversion, option/increment admission, agreement installation or 64 /// stock operation. JSON serialization alone does not create a listing profile. 65 #[derive(Clone, Eq, PartialEq)] 66 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 67 pub struct FixedPrice { 68 rate: Money, 69 basis: PositiveDecimal, 70 discount_bps: DiscountBps, 71 tiers: Box<[PriceTier]>, 72 } 73 74 impl FixedPrice { 75 /// Maximum number of explicitly ordered price tiers. 76 pub const MAX_TIERS: usize = 8; 77 78 /// Checks tier count, strict threshold order and exact shared currency. 79 pub fn new( 80 rate: Money, 81 basis: PositiveDecimal, 82 discount_bps: DiscountBps, 83 tiers: Vec<PriceTier>, 84 ) -> Result<Self, PricingError> { 85 if tiers.len() > Self::MAX_TIERS { 86 return Err(PricingError::TooManyTiers); 87 } 88 let mut previous = None; 89 for tier in &tiers { 90 if tier.rate.currency() != rate.currency() { 91 return Err(MoneyError::CurrencyMismatch.into()); 92 } 93 if previous.is_some_and(|value| tier.from <= value) { 94 return Err(PricingError::InvalidTierOrder); 95 } 96 previous = Some(tier.from); 97 } 98 Ok(Self { 99 rate, 100 basis, 101 discount_bps, 102 tiers: tiers.into_boxed_slice(), 103 }) 104 } 105 106 /// Returns the base rate, used below the first applicable tier. 107 pub const fn rate(&self) -> Money { 108 self.rate 109 } 110 /// Returns the strictly positive common price basis. 111 pub const fn basis(&self) -> PositiveDecimal { 112 self.basis 113 } 114 /// Returns the single discount applied before line rounding. 115 pub const fn discount_bps(&self) -> DiscountBps { 116 self.discount_bps 117 } 118 /// Borrows the exact, strictly increasing tier sequence. 119 pub fn tiers(&self) -> &[PriceTier] { 120 &self.tiers 121 } 122 123 /// Resolves one tier and computes one exact discounted, half-even net line. 124 pub fn line(&self, amount: PositiveDecimal) -> Result<LinePrice, PricingError> { 125 let selected = self 126 .tiers 127 .iter() 128 .rev() 129 .find(|tier| tier.from <= amount.amount()); 130 let rate = selected.map_or(self.rate, |tier| tier.rate); 131 let total = Money::new( 132 rate.currency(), 133 net_line_minor(rate.minor(), amount, self.basis, self.discount_bps)?, 134 ); 135 Ok(LinePrice { 136 rate, 137 basis: self.basis, 138 discount_bps: self.discount_bps, 139 selected_tier_from: selected.map(|tier| tier.from), 140 total, 141 }) 142 } 143 } 144 145 /// Resolved numeric calculation, without authenticated terms or installation. 146 #[derive(Clone, Copy, Eq, PartialEq)] 147 pub struct LinePrice { 148 rate: Money, 149 basis: PositiveDecimal, 150 discount_bps: DiscountBps, 151 selected_tier_from: Option<Decimal>, 152 total: Money, 153 } 154 155 impl LinePrice { 156 /// Returns the base or selected tier rate actually used. 157 pub const fn rate(self) -> Money { 158 self.rate 159 } 160 /// Returns the exact common basis used for this line. 161 pub const fn basis(self) -> PositiveDecimal { 162 self.basis 163 } 164 /// Returns the single applied discount. 165 pub const fn discount_bps(self) -> DiscountBps { 166 self.discount_bps 167 } 168 /// Returns the selected inclusive threshold, or None for the base rate. 169 pub const fn selected_tier_from(self) -> Option<Decimal> { 170 self.selected_tier_from 171 } 172 /// Returns the once-rounded minor amount within the supported money cap. 173 pub const fn total(self) -> Money { 174 self.total 175 } 176 } 177 178 /// Sums one through 32 already-rounded net lines and an explicit fulfillment fee. 179 /// All operands must share one currency. Received totals still require the 180 /// enclosing agreement's independent recomputation and admission. 181 pub fn checked_order_total( 182 lines: &[Money], 183 fulfillment_charge: Money, 184 ) -> Result<Money, PricingError> { 185 if lines.is_empty() || lines.len() > MAX_PRICED_LINES { 186 return Err(PricingError::InvalidLineCount); 187 } 188 let mut total = fulfillment_charge; 189 for line in lines { 190 total = total.checked_add(*line)?; 191 } 192 Ok(total) 193 } 194 195 pub(crate) fn net_line_minor( 196 rate: MinorAmount, 197 amount: PositiveDecimal, 198 basis: PositiveDecimal, 199 discount: DiscountBps, 200 ) -> Result<MinorAmount, PricingError> { 201 let amount = amount.amount(); 202 let basis = basis.amount(); 203 let scale = |digits: u8| { 204 10_i128 205 .checked_pow(u32::from(digits)) 206 .ok_or(PricingError::ArithmeticOutOfRange) 207 }; 208 // Validated factors bound the numerator below 10^37 and denominator below 209 // 10^22, inside signed i128. Keep every operation checked independently. 210 let basis_scale = scale(basis.scale())?; 211 let amount_scale = scale(amount.scale())?; 212 let numerator = i128::from(rate.get()) 213 .checked_mul(i128::from(amount.coefficient())) 214 .and_then(|value| value.checked_mul(basis_scale)) 215 .and_then(|value| value.checked_mul(i128::from(10_000 - discount.get()))) 216 .ok_or(PricingError::ArithmeticOutOfRange)?; 217 let denominator = i128::from(basis.coefficient()) 218 .checked_mul(amount_scale) 219 .and_then(|value| value.checked_mul(10_000)) 220 .ok_or(PricingError::ArithmeticOutOfRange)?; 221 let quotient = numerator 222 .checked_div(denominator) 223 .ok_or(PricingError::ArithmeticOutOfRange)?; 224 let twice_remainder = numerator 225 .checked_rem(denominator) 226 .and_then(|value| value.checked_mul(2)) 227 .ok_or(PricingError::ArithmeticOutOfRange)?; 228 let odd = quotient 229 .checked_rem(2) 230 .ok_or(PricingError::ArithmeticOutOfRange)? 231 == 1; 232 let increment = twice_remainder > denominator || (twice_remainder == denominator && odd); 233 let rounded = quotient 234 .checked_add(i128::from(increment)) 235 .ok_or(PricingError::ArithmeticOutOfRange)?; 236 let rounded = u64::try_from(rounded).map_err(|_| MoneyError::MinorOutOfRange)?; 237 MinorAmount::new(rounded).map_err(Into::into) 238 } 239 240 /// Input-free fixed-price admission or exact-arithmetic failure. 241 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 242 #[non_exhaustive] 243 pub enum PricingError { 244 /// Basis points exceed the inclusive 0-10000 bound. 245 InvalidDiscount, 246 /// More than eight tiers were supplied. 247 TooManyTiers, 248 /// Thresholds are duplicate or are not strictly increasing. 249 InvalidTierOrder, 250 /// An aggregate has no lines or exceeds 32 lines. 251 InvalidLineCount, 252 /// Measurement bounds are inverted or contain fractional each counts. 253 InvalidMeasurementRange, 254 /// The final measurement uses a different explicit unit. 255 MeasurementUnitMismatch, 256 /// A final measurement is outside the authorized inclusive range. 257 MeasurementOutOfRange, 258 /// The exact recomputed price exceeds the explicit monetary cap. 259 CapExceeded, 260 /// A checked intermediate operation could not be represented. 261 ArithmeticOutOfRange, 262 /// The monetary bound or exact currency invariant was violated. 263 Money(MoneyError), 264 } 265 266 impl From<MoneyError> for PricingError { 267 fn from(value: MoneyError) -> Self { 268 Self::Money(value) 269 } 270 } 271 272 impl fmt::Display for PricingError { 273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 274 f.write_str(match self { 275 Self::InvalidDiscount => "invalid discount basis points", 276 Self::TooManyTiers => "too many price tiers", 277 Self::InvalidTierOrder => "price thresholds must strictly increase", 278 Self::InvalidLineCount => "invalid priced line count", 279 Self::InvalidMeasurementRange => "invalid measurement range", 280 Self::MeasurementUnitMismatch => "measurement unit differs from authorized unit", 281 Self::MeasurementOutOfRange => "measurement is outside authorized range", 282 Self::CapExceeded => "measurement price exceeds authorized cap", 283 Self::ArithmeticOutOfRange => "pricing arithmetic exceeds supported bounds", 284 Self::Money(error) => return error.fmt(f), 285 }) 286 } 287 } 288 289 impl core::error::Error for PricingError { 290 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { 291 match self { 292 Self::Money(error) => Some(error), 293 _ => None, 294 } 295 } 296 } 297 298 impl fmt::Debug for DiscountBps { 299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 300 f.write_str("DiscountBps(<redacted>)") 301 } 302 } 303 impl fmt::Debug for PriceTier { 304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 305 f.write_str("PriceTier(<redacted>)") 306 } 307 } 308 impl fmt::Debug for FixedPrice { 309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 310 f.write_str("FixedPrice(<redacted>)") 311 } 312 } 313 impl fmt::Debug for LinePrice { 314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 315 f.write_str("LinePrice(<redacted>)") 316 } 317 }