use serde::{Deserialize, Serialize};
use serde_json::{Map, Number, Value};
use crate::core::error::{DelopayError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EuclidComparisonType {
Equal,
NotEqual,
LessThan,
LessThanEqual,
GreaterThan,
GreaterThanEqual,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NumberComparison {
#[serde(rename = "comparisonType")]
pub comparison_type: EuclidComparisonType,
pub number: Number,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MetadataVariant {
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum EuclidValue {
Number(Number),
EnumVariant(String),
StrValue(String),
NumberArray(Vec<Number>),
EnumVariantArray(Vec<String>),
MetadataVariant(MetadataVariant),
NumberComparisonArray(Vec<NumberComparison>),
}
impl From<i64> for EuclidValue {
fn from(value: i64) -> Self {
EuclidValue::Number(Number::from(value))
}
}
impl From<String> for EuclidValue {
fn from(value: String) -> Self {
EuclidValue::EnumVariant(value)
}
}
impl From<&str> for EuclidValue {
fn from(value: &str) -> Self {
EuclidValue::EnumVariant(value.to_string())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EuclidComparison {
pub lhs: String,
pub comparison: EuclidComparisonType,
pub value: EuclidValue,
#[serde(default)]
pub metadata: Map<String, Value>,
}
impl EuclidComparison {
pub fn new(
lhs: impl Into<String>,
comparison: EuclidComparisonType,
value: impl Into<EuclidValue>,
) -> Self {
Self {
lhs: lhs.into(),
comparison,
value: value.into(),
metadata: Map::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct EuclidIfStatement {
pub condition: Vec<EuclidComparison>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nested: Option<Vec<EuclidIfStatement>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformFeeKind {
Percentage,
Flat,
Combined,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PlatformFeeOutput {
pub fee_type: PlatformFeeKind,
pub percentage_fee: Option<f64>,
pub flat_fee_amount: Option<i64>,
pub flat_fee_currency: Option<String>,
pub min_fee_amount: Option<i64>,
pub max_fee_amount: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PlatformFeeRuleOutput {
#[serde(default)]
pub fee: Option<PlatformFeeOutput>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformFeeRule {
pub name: String,
pub connector_selection: PlatformFeeRuleOutput,
pub statements: Vec<EuclidIfStatement>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformFeeProgram {
pub default_selection: PlatformFeeRuleOutput,
pub rules: Vec<PlatformFeeRule>,
#[serde(default)]
pub metadata: Map<String, Value>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LeafNode {
pub lhs: String,
pub comparison: EuclidComparisonType,
pub value: EuclidValue,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ConditionNode {
Leaf(LeafNode),
All(Vec<ConditionNode>),
Any(Vec<ConditionNode>),
}
pub fn leaf(
lhs: impl Into<String>,
comparison: EuclidComparisonType,
value: impl Into<EuclidValue>,
) -> ConditionNode {
ConditionNode::Leaf(LeafNode {
lhs: lhs.into(),
comparison,
value: value.into(),
})
}
pub fn all_of(children: impl IntoIterator<Item = ConditionNode>) -> ConditionNode {
ConditionNode::All(children.into_iter().collect())
}
pub fn any_of(children: impl IntoIterator<Item = ConditionNode>) -> ConditionNode {
ConditionNode::Any(children.into_iter().collect())
}
pub fn normalize_node(node: &ConditionNode) -> ConditionNode {
let (is_any, children) = match node {
ConditionNode::Leaf(_) => return node.clone(),
ConditionNode::All(children) => (false, children),
ConditionNode::Any(children) => (true, children),
};
let mut flat: Vec<ConditionNode> = Vec::with_capacity(children.len());
for child in children.iter().map(normalize_node) {
match (&child, is_any) {
(ConditionNode::All(inner), false) | (ConditionNode::Any(inner), true) => {
flat.extend(inner.iter().cloned());
}
_ => flat.push(child),
}
}
if flat.len() == 1 {
return flat.remove(0);
}
if is_any {
ConditionNode::Any(flat)
} else {
ConditionNode::All(flat)
}
}
fn leaf_to_comparison(node: &LeafNode) -> EuclidComparison {
EuclidComparison {
lhs: node.lhs.clone(),
comparison: node.comparison,
value: node.value.clone(),
metadata: Map::new(),
}
}
fn to_statement(node: &ConditionNode) -> EuclidIfStatement {
let children = match node {
ConditionNode::Leaf(l) => {
return EuclidIfStatement {
condition: vec![leaf_to_comparison(l)],
nested: None,
};
}
ConditionNode::Any(children) => {
return EuclidIfStatement {
condition: Vec::new(),
nested: Some(children.iter().map(to_statement).collect()),
};
}
ConditionNode::All(children) => children,
};
let condition: Vec<EuclidComparison> = children
.iter()
.filter_map(|c| match c {
ConditionNode::Leaf(l) => Some(leaf_to_comparison(l)),
_ => None,
})
.collect();
let groups: Vec<&ConditionNode> = children
.iter()
.filter(|c| !matches!(c, ConditionNode::Leaf(_)))
.collect();
let Some((first, rest)) = groups.split_first() else {
return EuclidIfStatement {
condition,
nested: None,
};
};
let branches = match first {
ConditionNode::All(inner) | ConditionNode::Any(inner) => inner,
ConditionNode::Leaf(_) => unreachable!("groups excludes leaves"),
};
let nested = branches
.iter()
.map(|branch| {
let mut anded = Vec::with_capacity(rest.len() + 1);
anded.push(branch.clone());
anded.extend(rest.iter().map(|g| (*g).clone()));
to_statement(&normalize_node(&ConditionNode::All(anded)))
})
.collect();
EuclidIfStatement {
condition,
nested: Some(nested),
}
}
pub fn encode_statements(node: &ConditionNode) -> Vec<EuclidIfStatement> {
match normalize_node(node) {
ConditionNode::Any(children) => children.iter().map(to_statement).collect(),
other => vec![to_statement(&other)],
}
}
fn comparison_to_leaf(c: &EuclidComparison) -> ConditionNode {
ConditionNode::Leaf(LeafNode {
lhs: c.lhs.clone(),
comparison: c.comparison,
value: c.value.clone(),
})
}
fn statement_to_node(stmt: &EuclidIfStatement) -> ConditionNode {
let leaves: Vec<ConditionNode> = stmt.condition.iter().map(comparison_to_leaf).collect();
match &stmt.nested {
Some(nested) if !nested.is_empty() => {
let or_node = any_of(nested.iter().map(statement_to_node));
if leaves.is_empty() {
or_node
} else {
let mut anded = leaves;
anded.push(or_node);
ConditionNode::All(anded)
}
}
_ => {
if leaves.len() == 1 {
leaves.into_iter().next().expect("length checked")
} else {
ConditionNode::All(leaves)
}
}
}
}
pub fn rule_match_to_tree(statements: &[EuclidIfStatement]) -> ConditionNode {
if statements.len() == 1 {
return normalize_node(&statement_to_node(&statements[0]));
}
normalize_node(&any_of(statements.iter().map(statement_to_node)))
}
#[derive(Debug, Clone, PartialEq)]
pub struct FeeRuleTree {
pub name: String,
pub match_tree: ConditionNode,
pub fee: Option<PlatformFeeOutput>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FeeProgramTree {
pub rules: Vec<FeeRuleTree>,
pub otherwise: Option<PlatformFeeOutput>,
}
pub fn program_to_tree(program: &PlatformFeeProgram) -> FeeProgramTree {
FeeProgramTree {
rules: program
.rules
.iter()
.map(|r| FeeRuleTree {
name: r.name.clone(),
match_tree: rule_match_to_tree(&r.statements),
fee: r.connector_selection.fee.clone(),
})
.collect(),
otherwise: program.default_selection.fee.clone(),
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FeeSpecInput {
pub percentage: Option<f64>,
pub flat: Option<i64>,
pub flat_currency: Option<String>,
pub min: Option<i64>,
pub max: Option<i64>,
}
impl FeeSpecInput {
pub fn new() -> Self {
Self::default()
}
pub fn percentage(mut self, percentage: f64) -> Self {
self.percentage = Some(percentage);
self
}
pub fn flat(mut self, amount: i64, currency: impl Into<String>) -> Self {
self.flat = Some(amount);
self.flat_currency = Some(currency.into());
self
}
pub fn flat_amount(mut self, amount: i64) -> Self {
self.flat = Some(amount);
self
}
pub fn min(mut self, min: i64) -> Self {
self.min = Some(min);
self
}
pub fn max(mut self, max: i64) -> Self {
self.max = Some(max);
self
}
}
impl From<&FeeSpecInput> for PlatformFeeOutput {
fn from(spec: &FeeSpecInput) -> Self {
let fee_type = match (spec.percentage.is_some(), spec.flat.is_some()) {
(true, true) => PlatformFeeKind::Combined,
(false, true) => PlatformFeeKind::Flat,
_ => PlatformFeeKind::Percentage,
};
PlatformFeeOutput {
fee_type,
percentage_fee: spec.percentage,
flat_fee_amount: spec.flat,
flat_fee_currency: spec.flat_currency.clone(),
min_fee_amount: spec.min,
max_fee_amount: spec.max,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FeeRuleConditions {
pub payment_method: Option<String>,
pub connector: Option<String>,
pub currency: Option<String>,
pub card_network: Option<String>,
pub billing_country: Option<String>,
pub amount_equals: Option<i64>,
pub amount_greater_than: Option<i64>,
pub amount_less_than: Option<i64>,
pub merchant_volume_equals: Option<i64>,
pub merchant_volume_greater_than: Option<i64>,
pub merchant_volume_less_than: Option<i64>,
}
impl FeeRuleConditions {
pub fn new() -> Self {
Self::default()
}
pub fn payment_method(mut self, value: impl Into<String>) -> Self {
self.payment_method = Some(value.into());
self
}
pub fn connector(mut self, value: impl Into<String>) -> Self {
self.connector = Some(value.into());
self
}
pub fn currency(mut self, value: impl Into<String>) -> Self {
self.currency = Some(value.into());
self
}
pub fn card_network(mut self, value: impl Into<String>) -> Self {
self.card_network = Some(value.into());
self
}
pub fn billing_country(mut self, value: impl Into<String>) -> Self {
self.billing_country = Some(value.into());
self
}
pub fn amount_equals(mut self, value: i64) -> Self {
self.amount_equals = Some(value);
self
}
pub fn amount_greater_than(mut self, value: i64) -> Self {
self.amount_greater_than = Some(value);
self
}
pub fn amount_less_than(mut self, value: i64) -> Self {
self.amount_less_than = Some(value);
self
}
pub fn merchant_volume_equals(mut self, value: i64) -> Self {
self.merchant_volume_equals = Some(value);
self
}
pub fn merchant_volume_greater_than(mut self, value: i64) -> Self {
self.merchant_volume_greater_than = Some(value);
self
}
pub fn merchant_volume_less_than(mut self, value: i64) -> Self {
self.merchant_volume_less_than = Some(value);
self
}
fn to_comparisons(&self) -> Vec<EuclidComparison> {
use EuclidComparisonType::{Equal, GreaterThan, LessThan};
let enums: [(&str, &Option<String>); 5] = [
("payment_method", &self.payment_method),
("connector", &self.connector),
("currency", &self.currency),
("card_network", &self.card_network),
("billing_country", &self.billing_country),
];
let numbers: [(&str, EuclidComparisonType, Option<i64>); 6] = [
("amount", Equal, self.amount_equals),
("amount", GreaterThan, self.amount_greater_than),
("amount", LessThan, self.amount_less_than),
("merchant_volume", Equal, self.merchant_volume_equals),
(
"merchant_volume",
GreaterThan,
self.merchant_volume_greater_than,
),
("merchant_volume", LessThan, self.merchant_volume_less_than),
];
let mut out = Vec::new();
for (lhs, value) in enums {
if let Some(v) = value {
out.push(EuclidComparison::new(lhs, Equal, v.as_str()));
}
}
for (lhs, comparison, value) in numbers {
if let Some(v) = value {
out.push(EuclidComparison::new(lhs, comparison, v));
}
}
out
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FeeRuleInput {
pub name: String,
pub when: FeeRuleConditions,
pub raw_conditions: Vec<EuclidComparison>,
pub match_tree: Option<ConditionNode>,
pub fee: FeeSpecInput,
}
impl FeeRuleInput {
pub fn new(name: impl Into<String>, fee: FeeSpecInput) -> Self {
Self {
name: name.into(),
when: FeeRuleConditions::new(),
raw_conditions: Vec::new(),
match_tree: None,
fee,
}
}
pub fn when(mut self, when: FeeRuleConditions) -> Self {
self.when = when;
self
}
pub fn raw_conditions(mut self, raw: impl IntoIterator<Item = EuclidComparison>) -> Self {
self.raw_conditions.extend(raw);
self
}
pub fn match_tree(mut self, node: ConditionNode) -> Self {
self.match_tree = Some(node);
self
}
}
fn check_no_empty_any(node: &ConditionNode) -> std::result::Result<(), String> {
let children = match node {
ConditionNode::Leaf(_) => return Ok(()),
ConditionNode::Any(children) => {
if children.is_empty() {
return Err(
"fee program: an any_of() group must have at least one condition".to_string(),
);
}
children
}
ConditionNode::All(children) => children,
};
children.iter().try_for_each(check_no_empty_any)
}
#[derive(Debug, Clone, Default)]
pub struct FeeProgramBuilder {
rules: Vec<PlatformFeeRule>,
default_fee: Option<PlatformFeeOutput>,
error: Option<String>,
}
impl FeeProgramBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn rule(mut self, input: FeeRuleInput) -> Self {
let statements = match &input.match_tree {
Some(node) => {
if let Err(e) = check_no_empty_any(node) {
if self.error.is_none() {
self.error = Some(e);
}
return self;
}
encode_statements(node)
}
None => {
let mut condition = input.when.to_comparisons();
condition.extend(input.raw_conditions.iter().cloned());
vec![EuclidIfStatement {
condition,
nested: None,
}]
}
};
self.rules.push(PlatformFeeRule {
name: input.name,
connector_selection: PlatformFeeRuleOutput {
fee: Some((&input.fee).into()),
},
statements,
});
self
}
pub fn otherwise(mut self, fee: FeeSpecInput) -> Self {
self.default_fee = Some((&fee).into());
self
}
pub fn build(self) -> Result<PlatformFeeProgram> {
if let Some(message) = self.error {
return Err(DelopayError::InvalidRequest(message));
}
Ok(PlatformFeeProgram {
default_selection: PlatformFeeRuleOutput {
fee: self.default_fee,
},
rules: self.rules,
metadata: Map::new(),
})
}
}
pub fn fee_program() -> FeeProgramBuilder {
FeeProgramBuilder::new()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use EuclidComparisonType::{Equal, GreaterThan, LessThan};
fn pm(v: &str) -> ConditionNode {
leaf("payment_method", Equal, v)
}
fn vol(n: i64) -> ConditionNode {
leaf("merchant_volume", GreaterThan, n)
}
fn full_fee(percentage: f64) -> Value {
json!({
"fee_type": "percentage",
"percentage_fee": percentage,
"flat_fee_amount": null,
"flat_fee_currency": null,
"min_fee_amount": null,
"max_fee_amount": null,
})
}
#[test]
fn emits_the_exact_euclid_program() {
let program = fee_program()
.rule(
FeeRuleInput::new("crypto", FeeSpecInput::new().percentage(1.0))
.when(FeeRuleConditions::new().payment_method("crypto")),
)
.rule(
FeeRuleInput::new("card_on_cryptomus", FeeSpecInput::new().percentage(2.0)).when(
FeeRuleConditions::new()
.payment_method("card")
.connector("cryptomus"),
),
)
.otherwise(FeeSpecInput::new().percentage(3.0))
.build()
.unwrap();
assert_eq!(
serde_json::to_value(&program).unwrap(),
json!({
"defaultSelection": { "fee": full_fee(3.0) },
"rules": [
{
"name": "crypto",
"connectorSelection": { "fee": full_fee(1.0) },
"statements": [{
"condition": [{
"lhs": "payment_method",
"comparison": "equal",
"value": { "type": "enum_variant", "value": "crypto" },
"metadata": {},
}],
}],
},
{
"name": "card_on_cryptomus",
"connectorSelection": { "fee": full_fee(2.0) },
"statements": [{
"condition": [
{
"lhs": "payment_method",
"comparison": "equal",
"value": { "type": "enum_variant", "value": "card" },
"metadata": {},
},
{
"lhs": "connector",
"comparison": "equal",
"value": { "type": "enum_variant", "value": "cryptomus" },
"metadata": {},
},
],
}],
},
],
"metadata": {},
})
);
}
#[test]
fn serializes_camel_case_keys_and_tagged_values() {
let program = fee_program()
.rule(
FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0))
.when(FeeRuleConditions::new().payment_method("card")),
)
.build()
.unwrap();
let json = serde_json::to_string(&program).unwrap();
assert!(json.contains(r#""defaultSelection""#), "{json}");
assert!(json.contains(r#""connectorSelection""#), "{json}");
assert!(json.contains(r#""type":"enum_variant""#), "{json}");
assert!(!json.contains(r#""default_selection""#), "{json}");
assert!(!json.contains(r#""connector_selection""#), "{json}");
}
#[test]
fn numeric_conditions_serialize_as_integers_not_floats() {
let program = fee_program()
.rule(
FeeRuleInput::new("big", FeeSpecInput::new().percentage(2.0))
.when(FeeRuleConditions::new().amount_greater_than(500_000)),
)
.build()
.unwrap();
let json = serde_json::to_string(&program).unwrap();
assert!(json.contains(r#""value":500000"#), "{json}");
}
#[test]
fn infers_fee_type_percentage_flat_combined() {
let program = fee_program()
.rule(
FeeRuleInput::new("flat", FeeSpecInput::new().flat(30, "USD"))
.when(FeeRuleConditions::new().connector("stripe")),
)
.rule(
FeeRuleInput::new(
"combined",
FeeSpecInput::new().percentage(2.0).flat_amount(30),
)
.when(FeeRuleConditions::new().currency("USD")),
)
.otherwise(FeeSpecInput::new().percentage(1.0))
.build()
.unwrap();
let first = program.rules[0].connector_selection.fee.as_ref().unwrap();
assert_eq!(first.fee_type, PlatformFeeKind::Flat);
assert_eq!(first.flat_fee_amount, Some(30));
assert_eq!(first.flat_fee_currency.as_deref(), Some("USD"));
assert_eq!(
program.rules[1]
.connector_selection
.fee
.as_ref()
.unwrap()
.fee_type,
PlatformFeeKind::Combined
);
assert_eq!(
PlatformFeeOutput::from(&FeeSpecInput::new()).fee_type,
PlatformFeeKind::Percentage
);
}
#[test]
fn maps_amount_conditions_to_numeric_comparisons() {
let program = fee_program()
.rule(
FeeRuleInput::new("big", FeeSpecInput::new().percentage(2.0))
.when(FeeRuleConditions::new().amount_greater_than(500_000)),
)
.build()
.unwrap();
assert_eq!(
program.rules[0].statements[0].condition[0],
EuclidComparison {
lhs: "amount".to_string(),
comparison: GreaterThan,
value: EuclidValue::Number(500_000.into()),
metadata: Map::new(),
}
);
}
#[test]
fn maps_merchant_volume_conditions_combinable_with_method() {
let program = fee_program()
.rule(
FeeRuleInput::new("crypto_high_volume", FeeSpecInput::new().percentage(1.0)).when(
FeeRuleConditions::new()
.payment_method("crypto")
.merchant_volume_greater_than(1_000_000),
),
)
.build()
.unwrap();
assert_eq!(
program.rules[0].statements[0].condition,
vec![
EuclidComparison::new("payment_method", Equal, "crypto"),
EuclidComparison::new("merchant_volume", GreaterThan, 1_000_000),
]
);
}
#[test]
fn ands_friendly_conditions_with_raw_conditions_after_them() {
let program = fee_program()
.rule(
FeeRuleInput::new("crypto_type", FeeSpecInput::new().percentage(1.0))
.when(FeeRuleConditions::new().payment_method("crypto"))
.raw_conditions([EuclidComparison::new("crypto", Equal, "crypto_currency")]),
)
.build()
.unwrap();
let condition = &program.rules[0].statements[0].condition;
assert_eq!(condition.len(), 2);
assert_eq!(condition[0].lhs, "payment_method");
assert_eq!(condition[1].lhs, "crypto");
}
#[test]
fn defaults_to_null_fee_when_otherwise_is_omitted() {
let program = fee_program()
.rule(
FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0))
.when(FeeRuleConditions::new().payment_method("card")),
)
.build()
.unwrap();
assert_eq!(program.default_selection.fee, None);
assert_eq!(
serde_json::to_value(&program).unwrap()["defaultSelection"],
json!({ "fee": null })
);
}
#[test]
fn leaf_tags_numbers_as_number_and_strings_as_enum_variant() {
assert_eq!(
leaf("amount", GreaterThan, 500_000),
ConditionNode::Leaf(LeafNode {
lhs: "amount".to_string(),
comparison: GreaterThan,
value: EuclidValue::Number(500_000.into()),
})
);
assert_eq!(
leaf("payment_method", Equal, "crypto"),
ConditionNode::Leaf(LeafNode {
lhs: "payment_method".to_string(),
comparison: Equal,
value: EuclidValue::EnumVariant("crypto".to_string()),
})
);
}
#[test]
fn all_of_and_any_of_are_distinct_groups() {
let a = leaf("connector", Equal, "stripe");
assert_eq!(all_of([a.clone()]), ConditionNode::All(vec![a.clone()]));
assert_eq!(any_of([a.clone()]), ConditionNode::Any(vec![a]));
}
#[test]
fn single_leaf_encodes_to_one_statement_with_no_nested() {
assert_eq!(
encode_statements(&pm("card")),
vec![EuclidIfStatement {
condition: vec![EuclidComparison::new("payment_method", Equal, "card")],
nested: None,
}]
);
}
#[test]
fn all_of_leaves_encodes_to_one_anded_statement() {
let stmts = encode_statements(&all_of([pm("card"), vol(1_000_000)]));
assert_eq!(stmts.len(), 1);
assert_eq!(
stmts[0]
.condition
.iter()
.map(|c| c.lhs.as_str())
.collect::<Vec<_>>(),
["payment_method", "merchant_volume"]
);
assert_eq!(stmts[0].nested, None);
}
#[test]
fn any_of_at_top_encodes_to_one_statement_per_branch() {
let stmts = encode_statements(&any_of([
pm("crypto"),
all_of([pm("card"), vol(1_000_000)]),
]));
assert_eq!(stmts.len(), 2);
assert_eq!(
stmts[0].condition[0].value,
EuclidValue::EnumVariant("crypto".to_string())
);
assert_eq!(
stmts[1]
.condition
.iter()
.map(|c| c.lhs.as_str())
.collect::<Vec<_>>(),
["payment_method", "merchant_volume"]
);
}
#[test]
fn all_of_leaf_and_any_of_encodes_condition_anded_with_nested_or() {
let stmts = encode_statements(&all_of([
vol(1_000_000),
any_of([pm("card"), pm("wallet")]),
]));
assert_eq!(stmts.len(), 1);
assert_eq!(
stmts[0]
.condition
.iter()
.map(|c| c.lhs.as_str())
.collect::<Vec<_>>(),
["merchant_volume"]
);
let nested = stmts[0].nested.as_ref().expect("nested OR");
assert_eq!(nested.len(), 2);
assert_eq!(
nested[0].condition[0].value,
EuclidValue::EnumVariant("card".to_string())
);
assert_eq!(
nested[1].condition[0].value,
EuclidValue::EnumVariant("wallet".to_string())
);
}
#[test]
fn normalize_collapses_single_child_groups_and_flattens_associativity() {
assert_eq!(normalize_node(&all_of([pm("card")])), pm("card"));
assert_eq!(normalize_node(&any_of([pm("card")])), pm("card"));
assert_eq!(normalize_node(&all_of([any_of([pm("card")])])), pm("card"));
assert_eq!(
normalize_node(&all_of([pm("card"), all_of([vol(1), pm("wallet")])])),
all_of([pm("card"), vol(1), pm("wallet")])
);
assert_eq!(
normalize_node(&any_of([pm("card"), any_of([pm("wallet"), pm("crypto")])])),
any_of([pm("card"), pm("wallet"), pm("crypto")])
);
assert_eq!(
normalize_node(&all_of([pm("card"), any_of([pm("wallet"), pm("crypto")])])),
all_of([pm("card"), any_of([pm("wallet"), pm("crypto")])])
);
}
#[test]
fn flattens_nested_all_and_collapses_single_child_groups() {
assert_eq!(
encode_statements(&all_of([all_of([pm("card")])])),
encode_statements(&pm("card"))
);
assert_eq!(
encode_statements(&any_of([any_of([pm("card"), pm("wallet")])])),
encode_statements(&any_of([pm("card"), pm("wallet")]))
);
}
#[test]
fn preserves_an_and_inside_an_or_branch_that_is_anded_with_another_condition() {
let stmts = encode_statements(&all_of([
any_of([
all_of([
leaf("payment_method", Equal, "card"),
leaf("connector", Equal, "stripe"),
]),
leaf("payment_method", Equal, "wallet"),
]),
leaf("currency", Equal, "USD"),
]));
assert_eq!(stmts.len(), 1);
assert_eq!(
stmts[0]
.condition
.iter()
.map(|c| c.lhs.as_str())
.collect::<Vec<_>>(),
["currency"]
);
let nested = stmts[0].nested.as_ref().expect("nested OR");
assert_eq!(nested.len(), 2);
assert_eq!(
nested[0]
.condition
.iter()
.map(|c| c.lhs.as_str())
.collect::<Vec<_>>(),
["payment_method", "connector"]
);
assert_eq!(nested[0].nested, None);
}
#[test]
fn emits_multi_statement_or_rules_from_a_match_tree() {
let program = fee_program()
.rule(
FeeRuleInput::new("crypto_or_big_card", FeeSpecInput::new().percentage(1.5))
.match_tree(any_of([pm("crypto"), all_of([pm("card"), vol(1_000_000)])])),
)
.otherwise(FeeSpecInput::new().percentage(3.0))
.build()
.unwrap();
assert_eq!(program.rules[0].statements.len(), 2);
assert_eq!(
program.rules[0]
.connector_selection
.fee
.as_ref()
.unwrap()
.percentage_fee,
Some(1.5)
);
}
#[test]
fn still_supports_the_flat_when_sugar_as_a_single_statement() {
let program = fee_program()
.rule(
FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0))
.when(FeeRuleConditions::new().payment_method("card")),
)
.build()
.unwrap();
assert_eq!(program.rules[0].statements.len(), 1);
}
#[test]
fn rejects_an_empty_any_of_in_a_match_tree() {
let err = fee_program()
.rule(
FeeRuleInput::new("bad", FeeSpecInput::new().percentage(1.0))
.match_tree(any_of([])),
)
.build()
.unwrap_err();
match err {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("any_of"), "{msg}"),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[test]
fn rejects_a_nested_empty_any_of() {
let err = fee_program()
.rule(
FeeRuleInput::new("bad", FeeSpecInput::new().percentage(1.0))
.match_tree(all_of([pm("card"), any_of([])])),
)
.build()
.unwrap_err();
assert!(matches!(err, DelopayError::InvalidRequest(_)));
}
#[test]
fn still_allows_an_empty_all_of_as_an_always_match() {
let program = fee_program()
.rule(
FeeRuleInput::new("always", FeeSpecInput::new().percentage(1.0))
.match_tree(all_of([])),
)
.build()
.unwrap();
assert_eq!(program.rules.len(), 1);
assert!(program.rules[0].statements[0].condition.is_empty());
}
#[test]
fn a_rejected_rule_is_not_appended() {
let builder = fee_program()
.rule(
FeeRuleInput::new("ok", FeeSpecInput::new().percentage(1.0))
.when(FeeRuleConditions::new().payment_method("card")),
)
.rule(
FeeRuleInput::new("bad", FeeSpecInput::new().percentage(1.0))
.match_tree(any_of([])),
);
assert_eq!(builder.rules.len(), 1);
assert!(builder.build().is_err());
}
#[test]
fn decode_of_encode_is_structurally_equal_to_normalize() {
let cases = [
pm("card"),
all_of([pm("card"), vol(1_000_000)]),
any_of([pm("crypto"), all_of([pm("card"), vol(1_000_000)])]),
];
for tree in cases {
assert_eq!(
rule_match_to_tree(&encode_statements(&tree)),
normalize_node(&tree),
"round-trip changed {tree:?}"
);
}
}
#[test]
fn round_trips_a_leaf_anded_with_an_or() {
let t = all_of([
pm("card"),
any_of([
leaf("amount", GreaterThan, 500_000),
leaf("amount", LessThan, 1_000_000),
]),
]);
assert_eq!(
rule_match_to_tree(&encode_statements(&t)),
normalize_node(&t)
);
}
#[test]
fn decodes_an_and_of_two_ors_to_the_distributed_form() {
let a = pm("card");
let b = pm("wallet");
let c = leaf("currency", Equal, "USD");
let d = leaf("currency", Equal, "EUR");
let decoded = rule_match_to_tree(&encode_statements(&all_of([
any_of([a.clone(), b.clone()]),
any_of([c.clone(), d.clone()]),
])));
assert_eq!(
decoded,
any_of([
all_of([a, any_of([c.clone(), d.clone()])]),
all_of([b, any_of([c, d])]),
])
);
}
#[test]
fn program_to_tree_decodes_names_fees_and_the_default() {
let program = fee_program()
.rule(
FeeRuleInput::new("crypto", FeeSpecInput::new().percentage(1.0))
.when(FeeRuleConditions::new().payment_method("crypto")),
)
.otherwise(FeeSpecInput::new().flat(30, "USD"))
.build()
.unwrap();
let tree = program_to_tree(&program);
assert_eq!(tree.rules.len(), 1);
assert_eq!(tree.rules[0].name, "crypto");
assert_eq!(tree.rules[0].match_tree, pm("crypto"));
assert_eq!(
tree.rules[0].fee.as_ref().unwrap().percentage_fee,
Some(1.0)
);
let otherwise = tree.otherwise.as_ref().expect("default fee");
assert_eq!(otherwise.fee_type, PlatformFeeKind::Flat);
assert_eq!(otherwise.flat_fee_amount, Some(30));
}
#[test]
fn program_round_trips_through_json() {
let program = fee_program()
.rule(
FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0).min(50).max(900))
.match_tree(all_of([vol(1_000_000), any_of([pm("card"), pm("wallet")])])),
)
.otherwise(FeeSpecInput::new().percentage(3.0))
.build()
.unwrap();
let encoded = serde_json::to_string(&program).unwrap();
let decoded: PlatformFeeProgram = serde_json::from_str(&encoded).unwrap();
assert_eq!(decoded, program);
}
}