use serde::{Deserialize, Serialize};
use serde_json::Value;
pub type TransactionType = String;
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutableConnectorChoice {
pub connector: String,
#[serde(default)]
pub merchant_connector_id: Option<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingDictionaryRecord {
pub id: String,
pub profile_id: String,
pub name: String,
pub kind: String,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub created_at: Option<i64>,
#[serde(default)]
pub modified_at: Option<i64>,
#[serde(default)]
pub algorithm_for: Option<TransactionType>,
#[serde(default)]
pub decision_engine_routing_id: Option<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MerchantRoutingAlgorithm {
pub id: String,
pub profile_id: String,
pub name: String,
pub algorithm: Value,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub created_at: Option<i64>,
#[serde(default)]
pub modified_at: Option<i64>,
#[serde(default)]
pub algorithm_for: Option<TransactionType>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RoutingDictionary {
pub merchant_id: String,
#[serde(default)]
pub active_id: Option<String>,
#[serde(default = "Vec::new")]
pub records: Vec<RoutingDictionaryRecord>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ActiveRoutingAlgorithm {
#[serde(default)]
pub algorithm: Option<MerchantRoutingAlgorithm>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ActiveRoutingConfig {
Envelope(Box<ActiveRoutingAlgorithm>),
Records(Vec<RoutingDictionaryRecord>),
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfileDefaultRoutingConfig {
pub profile_id: String,
#[serde(default = "Vec::new")]
pub connectors: Vec<RoutableConnectorChoice>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum DefaultProfileRouting {
PerProfile(Vec<ProfileDefaultRoutingConfig>),
Connectors(Vec<RoutableConnectorChoice>),
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProfileDeniedConnectorsResponse {
#[serde(default = "Vec::new")]
pub denied_connectors: Vec<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MethodSurcharge {
#[serde(rename = "fixed")]
Fixed {
amount: i64,
},
#[serde(rename = "rate")]
Rate {
percent: f64,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PerMethodSurchargeItem {
pub payment_method: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub card_network: Option<String>,
pub surcharge: MethodSurcharge,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tax_on_surcharge_percent: Option<f64>,
}
impl PerMethodSurchargeItem {
pub fn new(payment_method: impl Into<String>, surcharge: MethodSurcharge) -> Self {
Self {
payment_method: payment_method.into(),
payment_method_type: None,
card_network: None,
surcharge,
tax_on_surcharge_percent: None,
}
}
#[must_use]
pub fn payment_method_type(mut self, payment_method_type: impl Into<String>) -> Self {
self.payment_method_type = Some(payment_method_type.into());
self
}
#[must_use]
pub fn card_network(mut self, card_network: impl Into<String>) -> Self {
self.card_network = Some(card_network.into());
self
}
#[must_use]
pub fn tax_on_surcharge_percent(mut self, percent: f64) -> Self {
self.tax_on_surcharge_percent = Some(percent);
self
}
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SurchargeRuleResponse {
pub name: String,
pub version: i64,
#[serde(default)]
pub profile_id: Option<String>,
#[serde(default)]
pub surcharges: Option<Vec<PerMethodSurchargeItem>>,
#[serde(default)]
pub default_surcharge: Option<MethodSurcharge>,
#[serde(default)]
pub show_surcharge_breakup_screen: Option<bool>,
#[serde(default)]
pub valid_from: Option<String>,
#[serde(default)]
pub valid_until: Option<String>,
#[serde(default = "Vec::new")]
pub warnings: Vec<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn dictionary_decodes_records_and_a_null_active_id() {
let dict: RoutingDictionary = serde_json::from_str(
r#"{
"merchant_id": "merch_1",
"active_id": null,
"records": [{
"id": "rou_1",
"profile_id": "pro_1",
"name": "EU Priority",
"kind": "priority",
"description": "EU traffic",
"created_at": 1767225600000,
"modified_at": 1767312000000,
"algorithm_for": "payment",
"brand_new_field": "keep me"
}]
}"#,
)
.unwrap();
assert_eq!(dict.active_id, None);
let record = &dict.records[0];
assert_eq!(record.kind, "priority");
assert_eq!(record.created_at, Some(1_767_225_600_000));
assert_eq!(record.algorithm_for.as_deref(), Some("payment"));
assert_eq!(record.extra["brand_new_field"], "keep me");
}
#[test]
fn merchant_routing_algorithm_keeps_the_algorithm_as_raw_json() {
let algo: MerchantRoutingAlgorithm = serde_json::from_str(
r#"{
"id": "rou_1",
"profile_id": "pro_1",
"name": "EU Priority",
"description": "",
"algorithm": {"type": "priority", "data": [{"connector": "stripe"}]},
"created_at": 1767225600000,
"modified_at": 1767225600000,
"algorithm_for": "payment"
}"#,
)
.unwrap();
assert_eq!(algo.algorithm["type"], "priority");
assert_eq!(algo.algorithm["data"][0]["connector"], "stripe");
}
#[test]
fn active_routing_config_distinguishes_the_envelope_from_a_record_list() {
let envelope: ActiveRoutingConfig = serde_json::from_str(r#"{"algorithm": null}"#).unwrap();
match envelope {
ActiveRoutingConfig::Envelope(e) => assert!(e.algorithm.is_none()),
other => panic!("expected the envelope arm, got {other:?}"),
}
let records: ActiveRoutingConfig = serde_json::from_str(
r#"[{"id":"rou_1","profile_id":"pro_1","name":"n","kind":"single"}]"#,
)
.unwrap();
match records {
ActiveRoutingConfig::Records(r) => assert_eq!(r[0].id, "rou_1"),
other => panic!("expected the records arm, got {other:?}"),
}
}
#[test]
fn default_profile_routing_prefers_the_per_profile_arm() {
let per_profile: DefaultProfileRouting = serde_json::from_str(
r#"[{"profile_id":"pro_1","connectors":[{"connector":"stripe"}]}]"#,
)
.unwrap();
match per_profile {
DefaultProfileRouting::PerProfile(p) => {
assert_eq!(p[0].profile_id, "pro_1");
assert_eq!(p[0].connectors[0].connector, "stripe");
}
other => panic!("expected the per-profile arm, got {other:?}"),
}
let connectors: DefaultProfileRouting =
serde_json::from_str(r#"[{"connector":"stripe","merchant_connector_id":"mca_1"}]"#)
.unwrap();
match connectors {
DefaultProfileRouting::Connectors(c) => {
assert_eq!(c[0].merchant_connector_id.as_deref(), Some("mca_1"));
}
other => panic!("expected the connectors arm, got {other:?}"),
}
let empty: DefaultProfileRouting = serde_json::from_str("[]").unwrap();
match empty {
DefaultProfileRouting::PerProfile(p) => assert!(p.is_empty()),
other => panic!("an empty array must take the per-profile arm, got {other:?}"),
}
}
#[test]
fn surcharge_rule_response_round_trips_the_surcharge_union() {
let rule: SurchargeRuleResponse = serde_json::from_str(
r#"{
"name": "EU surcharges",
"profile_id": null,
"version": 3,
"valid_from": "2026-01-01T00:00:00Z",
"valid_until": null,
"surcharges": [
{"payment_method": "crypto", "surcharge": {"rate": {"percent": 1.0}}},
{
"payment_method": "card",
"card_network": "Visa",
"surcharge": {"fixed": {"amount": 35}},
"tax_on_surcharge_percent": 20.0
}
],
"default_surcharge": {"fixed": {"amount": 10}},
"warnings": ["card network scoping is ignored on stripe"]
}"#,
)
.unwrap();
assert_eq!(rule.version, 3);
assert_eq!(rule.profile_id, None);
let surcharges = rule.surcharges.expect("surcharges decode");
assert_eq!(
surcharges[0].surcharge,
MethodSurcharge::Rate { percent: 1.0 }
);
assert_eq!(
surcharges[1].surcharge,
MethodSurcharge::Fixed { amount: 35 }
);
assert_eq!(surcharges[1].card_network.as_deref(), Some("Visa"));
assert_eq!(surcharges[1].tax_on_surcharge_percent, Some(20.0));
assert_eq!(
rule.default_surcharge,
Some(MethodSurcharge::Fixed { amount: 10 })
);
assert_eq!(rule.warnings.len(), 1);
}
#[test]
fn surcharge_rule_response_defaults_warnings_to_empty() {
let rule: SurchargeRuleResponse =
serde_json::from_str(r#"{"name":"n","version":1}"#).unwrap();
assert!(rule.warnings.is_empty());
assert_eq!(rule.surcharges, None);
assert_eq!(rule.valid_from, None);
}
#[test]
fn method_surcharge_serializes_with_lowercase_wire_tags() {
assert_eq!(
serde_json::to_value(MethodSurcharge::Fixed { amount: 35 }).unwrap(),
json!({"fixed": {"amount": 35}})
);
assert_eq!(
serde_json::to_value(MethodSurcharge::Rate { percent: 1.5 }).unwrap(),
json!({"rate": {"percent": 1.5}})
);
}
#[test]
fn per_method_item_omits_the_scopes_it_was_not_given() {
let item = PerMethodSurchargeItem::new("crypto", MethodSurcharge::Rate { percent: 1.0 });
assert_eq!(
serde_json::to_value(&item).unwrap(),
json!({"payment_method": "crypto", "surcharge": {"rate": {"percent": 1.0}}})
);
let scoped = PerMethodSurchargeItem::new("card", MethodSurcharge::Fixed { amount: 35 })
.card_network("Visa")
.payment_method_type("credit")
.tax_on_surcharge_percent(20.0);
let value = serde_json::to_value(&scoped).unwrap();
assert_eq!(value["card_network"], "Visa");
assert_eq!(value["payment_method_type"], "credit");
assert_eq!(value["tax_on_surcharge_percent"], 20.0);
}
#[test]
fn denied_connectors_defaults_to_empty() {
let denied: ProfileDeniedConnectorsResponse = serde_json::from_str("{}").unwrap();
assert!(denied.denied_connectors.is_empty());
let denied: ProfileDeniedConnectorsResponse =
serde_json::from_str(r#"{"denied_connectors":["paypal"]}"#).unwrap();
assert_eq!(denied.denied_connectors, vec!["paypal".to_string()]);
}
}