listing_values.rs (9226B)
1 //! Shared public snapshot decoding. Private Terms never enter these JSON trees. 2 use crate::command::CommandError; 3 #[cfg(feature = "terms")] 4 use crate::command::parse_object; 5 use crate::command::required_nullable; 6 use alloc::{string::String, vec::Vec}; 7 use radroots_domain::{ 8 ContentMeasure, Decimal, DiscountBps, FixedPrice, ListingOptionId, Money, PositiveDecimal, 9 PriceTier, PublicKey, Quantity, TimeZoneId, UnixSeconds, VariableWeight, Window, listing::*, 10 }; 11 use serde::Deserialize; 12 #[cfg(feature = "terms")] 13 use serde_json::value::RawValue; 14 fn invalid<T, E>(value: Result<T, E>) -> Result<T, CommandError> { 15 value.map_err(|_| CommandError::InvalidInput) 16 } 17 #[derive(Deserialize)] 18 #[serde(deny_unknown_fields)] 19 pub(crate) struct RawProduct { 20 name: String, 21 description: String, 22 #[serde(deserialize_with = "crate::command::nullable_canonical_key")] 23 producer: Option<PublicKey>, 24 #[serde(deserialize_with = "required_nullable")] 25 origin_summary: Option<String>, 26 } 27 #[derive(Deserialize)] 28 #[serde(deny_unknown_fields)] 29 pub(crate) struct OptionInput { 30 id: ListingOptionId, 31 label: String, 32 unit: Unit, 33 increment: PositiveDecimal, 34 minimum: PositiveDecimal, 35 price: RawPrice, 36 supply: RawSupply, 37 lead_seconds: LeadSeconds, 38 } 39 #[derive(Deserialize)] 40 #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] 41 enum Unit { 42 Measured { unit: Measure }, 43 Package { label: String, contents: Contents }, 44 } 45 #[derive(Deserialize)] 46 enum Measure { 47 #[serde(rename = "g")] 48 Gram, 49 #[serde(rename = "kg")] 50 Kilogram, 51 #[serde(rename = "mL")] 52 Millilitre, 53 #[serde(rename = "L")] 54 Litre, 55 #[serde(rename = "each")] 56 Each, 57 } 58 impl Measure { 59 fn domain(self) -> MeasurementUnit { 60 match self { 61 Self::Gram => MeasurementUnit::Gram, 62 Self::Kilogram => MeasurementUnit::Kilogram, 63 Self::Millilitre => MeasurementUnit::Millilitre, 64 Self::Litre => MeasurementUnit::Litre, 65 Self::Each => MeasurementUnit::Each, 66 } 67 } 68 } 69 #[derive(Deserialize)] 70 #[serde(deny_unknown_fields)] 71 struct RawQuantity { 72 amount: Decimal, 73 unit: Measure, 74 } 75 impl RawQuantity { 76 fn domain(self) -> Result<Quantity, CommandError> { 77 invalid(Quantity::new(self.amount, self.unit.domain())) 78 } 79 } 80 #[derive(Deserialize)] 81 #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] 82 enum Contents { 83 Fixed { quantity: RawQuantity }, 84 Estimated { quantity: RawQuantity }, 85 Unspecified {}, 86 } 87 #[derive(Deserialize)] 88 #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] 89 enum RawPrice { 90 Fixed { 91 rate: Money, 92 basis: PositiveDecimal, 93 discount_bps: u16, 94 tiers: Vec<RawTier>, 95 }, 96 QuoteRequired {}, 97 VariableWeight { 98 measurement_unit: Measure, 99 minimum_per_sale_unit: PositiveDecimal, 100 maximum_per_sale_unit: PositiveDecimal, 101 rate: Money, 102 basis: PositiveDecimal, 103 maximum_per_sale_unit_total: Money, 104 }, 105 } 106 #[derive(Deserialize)] 107 #[serde(deny_unknown_fields)] 108 struct RawTier { 109 from: Decimal, 110 rate: Money, 111 } 112 impl RawPrice { 113 fn domain(self) -> Result<Price, CommandError> { 114 match self { 115 Self::QuoteRequired {} => Ok(Price::QuoteRequired), 116 Self::Fixed { 117 rate, 118 basis, 119 discount_bps, 120 tiers, 121 } => Ok(Price::Fixed(invalid(FixedPrice::new( 122 rate, 123 basis, 124 invalid(DiscountBps::new(discount_bps))?, 125 tiers 126 .into_iter() 127 .map(|tier| PriceTier::new(tier.from, tier.rate)) 128 .collect(), 129 ))?)), 130 Self::VariableWeight { 131 measurement_unit, 132 minimum_per_sale_unit, 133 maximum_per_sale_unit, 134 rate, 135 basis, 136 maximum_per_sale_unit_total, 137 } => Ok(Price::VariableWeight(invalid(VariableWeight::new( 138 measurement_unit.domain(), 139 minimum_per_sale_unit, 140 maximum_per_sale_unit, 141 rate, 142 basis, 143 maximum_per_sale_unit_total, 144 ))?)), 145 } 146 } 147 } 148 #[derive(Deserialize)] 149 #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] 150 enum RawSupply { 151 Unknown {}, 152 Available { 153 amount: Decimal, 154 }, 155 Estimated { 156 amount: Decimal, 157 #[serde(deserialize_with = "required_nullable")] 158 window: Option<RawWindow>, 159 }, 160 } 161 #[derive(Deserialize)] 162 #[serde(deny_unknown_fields)] 163 pub(crate) struct RawWindow { 164 start: UnixSeconds, 165 end: UnixSeconds, 166 timezone: String, 167 } 168 impl RawWindow { 169 fn domain(self) -> Result<Window, CommandError> { 170 invalid(Window::new( 171 self.start, 172 self.end, 173 invalid(TimeZoneId::from_name(&self.timezone))?, 174 )) 175 } 176 } 177 impl RawProduct { 178 pub(crate) fn domain(self) -> Result<Product, CommandError> { 179 invalid(Product::new( 180 &self.name, 181 &self.description, 182 self.producer, 183 self.origin_summary.as_deref(), 184 )) 185 } 186 } 187 impl OptionInput { 188 pub(crate) fn domain(self) -> Result<ListingOption, CommandError> { 189 let unit = match self.unit { 190 Unit::Measured { unit } => SaleUnit::measured(unit.domain()), 191 Unit::Package { label, contents } => { 192 let contents = match contents { 193 Contents::Fixed { quantity } => ContentMeasure::Fixed { 194 quantity: quantity.domain()?, 195 }, 196 Contents::Estimated { quantity } => ContentMeasure::Estimated { 197 quantity: quantity.domain()?, 198 }, 199 Contents::Unspecified {} => ContentMeasure::Unspecified, 200 }; 201 invalid(SaleUnit::package(&label, contents))? 202 } 203 }; 204 invalid(ListingOption::new( 205 self.id, 206 &self.label, 207 unit, 208 self.increment, 209 self.minimum, 210 self.price.domain()?, 211 match self.supply { 212 RawSupply::Unknown {} => Supply::Unknown, 213 RawSupply::Available { amount } => Supply::Available { amount }, 214 RawSupply::Estimated { amount, window } => Supply::Estimated { 215 amount, 216 window: window.map(RawWindow::domain).transpose()?, 217 }, 218 }, 219 self.lead_seconds, 220 )) 221 } 222 } 223 pub(crate) fn object(value: &serde_json::Value) -> Result<(), CommandError> { 224 if value.is_object() { 225 Ok(()) 226 } else { 227 Err(CommandError::InvalidInput) 228 } 229 } 230 pub(crate) fn option_shape(option: &serde_json::Value) -> Result<(), CommandError> { 231 object(option)?; 232 object(&option["unit"])?; 233 object(&option["price"])?; 234 object(&option["supply"])?; 235 if let Some(window) = option["supply"].get("window") 236 && !window.is_null() 237 { 238 object(window)?; 239 } 240 if let Some(contents) = option["unit"].get("contents") { 241 object(contents)?; 242 if let Some(quantity) = contents.get("quantity") { 243 object(quantity)?; 244 } 245 } 246 if let Some(tiers) = option["price"].get("tiers") { 247 let tiers = tiers.as_array().ok_or(CommandError::InvalidInput)?; 248 if tiers.len() > FixedPrice::MAX_TIERS { 249 return Err(CommandError::LimitExceeded); 250 } 251 for tier in tiers { 252 object(tier)?; 253 } 254 } 255 Ok(()) 256 } 257 258 #[cfg(feature = "terms")] 259 pub(crate) fn product(raw: &RawValue) -> Result<Product, CommandError> { 260 parse_object::<RawProduct>(raw.get().as_bytes())?.domain() 261 } 262 #[cfg(feature = "terms")] 263 pub(crate) fn option(raw: &RawValue) -> Result<ListingOption, CommandError> { 264 let value: serde_json::Value = 265 serde_json::from_str(raw.get()).map_err(|_| CommandError::InvalidInput)?; 266 option_shape(&value)?; 267 for (path, supported) in [ 268 ( 269 "/price/type", 270 &["quote_required", "fixed", "variable_weight"][..], 271 ), 272 ("/supply/type", &["unknown", "available", "estimated"][..]), 273 ("/unit/type", &["measured", "package"][..]), 274 ( 275 "/unit/contents/type", 276 &["unspecified", "fixed", "estimated"][..], 277 ), 278 ] { 279 if value 280 .pointer(path) 281 .and_then(serde_json::Value::as_str) 282 .is_some_and(|tag| !supported.contains(&tag)) 283 { 284 return Err(CommandError::UnsupportedProfile); 285 } 286 } 287 for path in [ 288 "/unit/unit", 289 "/unit/contents/quantity/unit", 290 "/price/measurement_unit", 291 ] { 292 if value 293 .pointer(path) 294 .and_then(serde_json::Value::as_str) 295 .is_some_and(|unit| !["g", "kg", "mL", "L", "each"].contains(&unit)) 296 { 297 return Err(CommandError::UnsupportedProfile); 298 } 299 } 300 parse_object::<OptionInput>(raw.get().as_bytes())?.domain() 301 }