use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::routing::{
ActiveRoutingConfig, DefaultProfileRouting, MerchantRoutingAlgorithm,
ProfileDefaultRoutingConfig, ProfileDeniedConnectorsResponse, RoutableConnectorChoice,
RoutingDictionary, RoutingDictionaryRecord, SurchargeRuleResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
pub use crate::core::models::routing::{MethodSurcharge, PerMethodSurchargeItem};
#[derive(Debug, Clone)]
pub struct Routing {
inner: Arc<Inner>,
}
impl Routing {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub fn decision(&self) -> RoutingDecision {
RoutingDecision::new(self.inner.clone())
}
pub fn surcharge_rules(&self) -> SurchargeRules {
SurchargeRules::new(self.inner.clone())
}
pub async fn create(
&self,
params: &RoutingConfigCreateRequest,
) -> Result<RoutingDictionaryRecord> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, "/routing", Some(&body), &[], None)
.await
}
pub async fn retrieve(&self, algorithm_id: &str) -> Result<MerchantRoutingAlgorithm> {
let path = format!("/routing/{}", encode_segment(algorithm_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn activate(
&self,
algorithm_id: &str,
params: Option<&RoutingActivatePayload>,
) -> Result<RoutingDictionaryRecord> {
let path = format!("/routing/{}/activate", encode_segment(algorithm_id));
let body = body_or_empty_object(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn deactivate(
&self,
params: Option<&RoutingDeactivateRequest>,
) -> Result<RoutingDictionaryRecord> {
if let Some(p) = params {
p.validate()?;
}
let body = body_or_empty_object(params)?;
self.inner
.request(
HttpMethod::Post,
"/routing/deactivate",
Some(&body),
&[],
None,
)
.await
}
pub async fn list(&self) -> Result<RoutingDictionary> {
self.inner
.request(HttpMethod::Get, "/routing", None, &[], None)
.await
}
pub async fn connector_restrictions(
&self,
profile_id: &str,
) -> Result<ProfileDeniedConnectorsResponse> {
let path = format!(
"/routing/connector-restrictions/{}",
encode_segment(profile_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn active(&self) -> Result<ActiveRoutingConfig> {
self.inner
.request(HttpMethod::Get, "/routing/active", None, &[], None)
.await
}
pub async fn update_default(&self, params: &Value) -> Result<Vec<RoutableConnectorChoice>> {
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, "/routing/default", Some(&body), &[], None)
.await
}
pub async fn default_profile(&self) -> Result<DefaultProfileRouting> {
self.inner
.request(HttpMethod::Get, "/routing/default/profile", None, &[], None)
.await
}
pub async fn update_default_profile(
&self,
profile_id: &str,
params: &Value,
) -> Result<ProfileDefaultRoutingConfig> {
let path = format!("/routing/default/profile/{}", encode_segment(profile_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn list_for_profile(&self) -> Result<RoutingDictionary> {
self.inner
.request(HttpMethod::Get, "/routing/list/profile", None, &[], None)
.await
}
pub async fn evaluate_rule(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/routing/rule/evaluate",
Some(&body),
&[],
None,
)
.await
}
pub async fn migrate_rule(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/routing/rule/migrate",
Some(&body),
&[],
None,
)
.await
}
pub async fn evaluate(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/routing/evaluate",
Some(&body),
&[],
None,
)
.await
}
pub async fn feedback(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/routing/feedback",
Some(&body),
&[],
None,
)
.await
}
}
fn body_or_empty_object<T: Serialize>(params: Option<&T>) -> Result<Vec<u8>> {
match params {
Some(p) => to_json_vec(p),
None => Ok(b"{}".to_vec()),
}
}
#[derive(Debug, Clone)]
pub struct RoutingDecision {
inner: Arc<Inner>,
}
impl RoutingDecision {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn upsert(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Put, "/routing/decision", Some(&body), &[], None)
.await
}
pub async fn retrieve(&self) -> Result<Value> {
self.inner
.request(HttpMethod::Get, "/routing/decision", None, &[], None)
.await
}
pub async fn delete(&self) -> Result<Value> {
self.inner
.request(HttpMethod::Delete, "/routing/decision", None, &[], None)
.await
}
pub async fn upsert_surcharge(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Put,
"/routing/decision/surcharge",
Some(&body),
&[],
None,
)
.await
}
pub async fn retrieve_surcharge(&self) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/routing/decision/surcharge",
None,
&[],
None,
)
.await
}
pub async fn delete_surcharge(&self) -> Result<Value> {
self.inner
.request(
HttpMethod::Delete,
"/routing/decision/surcharge",
None,
&[],
None,
)
.await
}
}
#[derive(Debug, Clone)]
pub struct SurchargeRules {
inner: Arc<Inner>,
}
impl SurchargeRules {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn upsert(&self, params: &SurchargeRuleRequest) -> Result<SurchargeRuleResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Put,
"/routing/surcharge/rules",
Some(&body),
&[],
None,
)
.await
}
pub async fn retrieve(
&self,
profile_id: Option<&str>,
) -> Result<Option<SurchargeRuleResponse>> {
let query = profile_id_query(profile_id);
self.inner
.request(
HttpMethod::Get,
"/routing/surcharge/rules",
None,
&query,
None,
)
.await
}
pub async fn delete(&self, profile_id: Option<&str>) -> Result<()> {
let query = profile_id_query(profile_id);
self.inner
.request(
HttpMethod::Delete,
"/routing/surcharge/rules",
None,
&query,
None,
)
.await
}
}
fn profile_id_query(profile_id: Option<&str>) -> Vec<(&'static str, String)> {
match profile_id {
Some(id) => vec![("profile_id", id.to_string())],
None => Vec::new(),
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingConfigCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub algorithm: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction_type: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const ROUTING_CONFIG_CREATE_REQUEST_NAMED: &[&str] = &[
"name",
"description",
"algorithm",
"profile_id",
"transaction_type",
];
impl ValidateRequest for RoutingConfigCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if ROUTING_CONFIG_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on \
RoutingConfigCreateRequest"
)));
}
}
Ok(())
}
}
impl RoutingConfigCreateRequest {
pub fn new() -> Self {
Self::default()
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn algorithm(mut self, algorithm: Value) -> Self {
self.algorithm = Some(algorithm);
self
}
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
pub fn transaction_type(mut self, transaction_type: impl Into<String>) -> Self {
self.transaction_type = Some(transaction_type.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingActivatePayload {
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction_type: Option<String>,
}
impl RoutingActivatePayload {
pub fn new() -> Self {
Self::default()
}
pub fn transaction_type(mut self, transaction_type: impl Into<String>) -> Self {
self.transaction_type = Some(transaction_type.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingDeactivateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub algorithm: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction_type: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const ROUTING_DEACTIVATE_REQUEST_NAMED: &[&str] = &[
"name",
"description",
"algorithm",
"profile_id",
"transaction_type",
];
impl ValidateRequest for RoutingDeactivateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if ROUTING_DEACTIVATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on \
RoutingDeactivateRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SurchargeRuleRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub surcharges: Option<Vec<PerMethodSurchargeItem>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_surcharge: Option<MethodSurcharge>,
#[serde(skip_serializing_if = "Option::is_none")]
pub show_surcharge_breakup_screen: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub valid_from: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub valid_until: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const SURCHARGE_RULE_REQUEST_NAMED: &[&str] = &[
"name",
"profile_id",
"surcharges",
"default_surcharge",
"show_surcharge_breakup_screen",
"valid_from",
"valid_until",
];
impl ValidateRequest for SurchargeRuleRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SURCHARGE_RULE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on SurchargeRuleRequest"
)));
}
}
Ok(())
}
}
impl SurchargeRuleRequest {
pub fn new() -> Self {
Self::default()
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
pub fn surcharges(mut self, surcharges: Vec<PerMethodSurchargeItem>) -> Self {
self.surcharges = Some(surcharges);
self
}
pub fn default_surcharge(mut self, surcharge: MethodSurcharge) -> Self {
self.default_surcharge = Some(surcharge);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const RECORD_JSON: &str = r#"{
"id": "rou_1",
"profile_id": "pro_1",
"name": "EU Priority",
"kind": "priority",
"description": "EU traffic",
"created_at": 1767225600000,
"modified_at": 1767225600000,
"algorithm_for": "payment"
}"#;
const ALGORITHM_JSON: &str = r#"{
"id": "rou_1",
"profile_id": "pro_1",
"name": "EU Priority",
"description": "EU traffic",
"algorithm": {"type": "priority", "data": [{"connector": "stripe"}]},
"created_at": 1767225600000,
"modified_at": 1767225600000,
"algorithm_for": "payment"
}"#;
const DICTIONARY_JSON: &str = r#"{"merchant_id":"mer_1","active_id":null,"records":[]}"#;
const SURCHARGE_JSON: &str = r#"{
"name": "EU surcharges",
"profile_id": "pro_1",
"version": 2,
"valid_from": "2026-01-01T00:00:00Z",
"valid_until": null,
"surcharges": [
{"payment_method": "card", "surcharge": {"fixed": {"amount": 35}}}
],
"default_surcharge": {"fixed": {"amount": 10}}
}"#;
#[tokio::test]
async fn create_posts_the_algorithm_to_routing_root() {
let (client, mock) = client_with(vec![Step::ok(RECORD_JSON)]);
let req = RoutingConfigCreateRequest::new()
.name("EU Priority")
.profile_id("pro_1")
.algorithm(json!({"type": "priority", "data": [{"connector": "stripe"}]}));
let record = client.routing().create(&req).await.unwrap();
assert_eq!(record.id, "rou_1");
assert_eq!(record.kind, "priority");
assert_eq!(record.created_at, Some(1_767_225_600_000));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/routing");
let body = seen[0].body_json();
assert_eq!(body["name"], "EU Priority");
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["algorithm"]["type"], "priority");
}
#[tokio::test]
async fn retrieve_and_list_use_the_routing_paths() {
let (client, mock) = client_with(vec![Step::ok(ALGORITHM_JSON), Step::ok(DICTIONARY_JSON)]);
let routing = client.routing();
let algorithm = routing.retrieve("rou/1").await.unwrap();
assert_eq!(algorithm.algorithm["type"], "priority");
let dictionary = routing.list().await.unwrap();
assert_eq!(dictionary.merchant_id, "mer_1");
assert_eq!(dictionary.active_id, None);
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
("GET", "https://api.test/routing/rou%2F1")
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
("GET", "https://api.test/routing")
);
}
#[tokio::test]
async fn activate_posts_an_empty_object_body_by_default() {
let (client, mock) = client_with(vec![Step::ok(RECORD_JSON), Step::ok(RECORD_JSON)]);
let routing = client.routing();
routing.activate("rou 1", None).await.unwrap();
routing
.activate(
"rou_2",
Some(&RoutingActivatePayload::new().transaction_type("payment")),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/routing/rou%201/activate");
assert_eq!(seen[0].body_json(), json!({}));
assert_eq!(seen[1].url, "https://api.test/routing/rou_2/activate");
assert_eq!(seen[1].body_json()["transaction_type"], "payment");
}
#[tokio::test]
async fn deactivate_posts_to_the_deactivate_path() {
let (client, mock) = client_with(vec![Step::ok(RECORD_JSON), Step::ok(RECORD_JSON)]);
let routing = client.routing();
routing.deactivate(None).await.unwrap();
routing
.deactivate(Some(&RoutingDeactivateRequest {
profile_id: Some("pro_1".to_string()),
..Default::default()
}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/routing/deactivate");
assert_eq!(seen[0].body_json(), json!({}));
assert_eq!(seen[1].body_json()["profile_id"], "pro_1");
}
#[tokio::test]
async fn connector_restrictions_gets_the_profile_scoped_path() {
let (client, mock) = client_with(vec![Step::ok(r#"{"denied_connectors":["paypal"]}"#)]);
let denied = client
.routing()
.connector_restrictions("pro/1")
.await
.unwrap();
assert_eq!(denied.denied_connectors, vec!["paypal".to_string()]);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-restrictions/pro%2F1"
);
}
#[tokio::test]
async fn read_only_advanced_endpoints_hit_their_paths() {
let (client, mock) = client_with(vec![
Step::ok(r#"{"algorithm":null}"#),
Step::ok(r#"[{"profile_id":"pro_1","connectors":[{"connector":"stripe"}]}]"#),
Step::ok(DICTIONARY_JSON),
]);
let routing = client.routing();
let active = routing.active().await.unwrap();
assert!(
matches!(active, ActiveRoutingConfig::Envelope(ref e) if e.algorithm.is_none()),
"a `{{\"algorithm\": null}}` body means nothing is active: {active:?}"
);
let defaults = routing.default_profile().await.unwrap();
match defaults {
DefaultProfileRouting::PerProfile(p) => assert_eq!(p[0].profile_id, "pro_1"),
other => panic!("expected the per-profile arm, got {other:?}"),
}
routing.list_for_profile().await.unwrap();
let seen = mock.seen.lock().unwrap();
let expected = [
"https://api.test/routing/active",
"https://api.test/routing/default/profile",
"https://api.test/routing/list/profile",
];
for (i, url) in expected.iter().enumerate() {
assert_eq!(seen[i].method, "GET");
assert_eq!(seen[i].url, *url);
}
}
#[tokio::test]
async fn write_advanced_endpoints_post_their_bodies() {
let (client, mock) = client_with(vec![
Step::ok(r#"[{"connector":"stripe","merchant_connector_id":"mca_1"}]"#),
Step::ok(r#"{"profile_id":"pro/1","connectors":[]}"#),
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
]);
let routing = client.routing();
let connectors = routing
.update_default(&json!({"marker": "default"}))
.await
.unwrap();
assert_eq!(connectors[0].connector, "stripe");
assert_eq!(
connectors[0].merchant_connector_id.as_deref(),
Some("mca_1")
);
let profile_default = routing
.update_default_profile("pro/1", &json!({"marker": "default_profile"}))
.await
.unwrap();
assert_eq!(profile_default.profile_id, "pro/1");
routing
.evaluate_rule(&json!({"marker": "rule_evaluate"}))
.await
.unwrap();
routing
.migrate_rule(&json!({"marker": "rule_migrate"}))
.await
.unwrap();
routing
.evaluate(&json!({"marker": "evaluate"}))
.await
.unwrap();
routing
.feedback(&json!({"marker": "feedback"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
let expected = [
("https://api.test/routing/default", "default"),
(
"https://api.test/routing/default/profile/pro%2F1",
"default_profile",
),
("https://api.test/routing/rule/evaluate", "rule_evaluate"),
("https://api.test/routing/rule/migrate", "rule_migrate"),
("https://api.test/routing/evaluate", "evaluate"),
("https://api.test/routing/feedback", "feedback"),
];
for (i, (url, marker)) in expected.iter().enumerate() {
assert_eq!(seen[i].method, "POST");
assert_eq!(seen[i].url, *url);
assert_eq!(seen[i].body_json()["marker"], *marker);
}
}
#[tokio::test]
async fn decision_endpoints_use_their_verbs_and_paths() {
let (client, mock) = client_with(vec![
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
]);
let decision = client.routing().decision();
decision
.upsert(&json!({"marker": "decision"}))
.await
.unwrap();
decision.retrieve().await.unwrap();
decision.delete().await.unwrap();
decision
.upsert_surcharge(&json!({"marker": "decision_surcharge"}))
.await
.unwrap();
decision.retrieve_surcharge().await.unwrap();
decision.delete_surcharge().await.unwrap();
let seen = mock.seen.lock().unwrap();
let expected = [
("PUT", "https://api.test/routing/decision"),
("GET", "https://api.test/routing/decision"),
("DELETE", "https://api.test/routing/decision"),
("PUT", "https://api.test/routing/decision/surcharge"),
("GET", "https://api.test/routing/decision/surcharge"),
("DELETE", "https://api.test/routing/decision/surcharge"),
];
for (i, (method, url)) in expected.iter().enumerate() {
assert_eq!((seen[i].method, seen[i].url.as_str()), (*method, *url));
}
assert_eq!(seen[0].body_json()["marker"], "decision");
assert_eq!(seen[3].body_json()["marker"], "decision_surcharge");
}
#[tokio::test]
async fn surcharge_rules_upsert_puts_the_structured_program() {
let (client, mock) = client_with(vec![Step::ok(SURCHARGE_JSON)]);
let req = SurchargeRuleRequest::new()
.name("EU surcharges")
.profile_id("pro_1")
.surcharges(vec![
PerMethodSurchargeItem::new("crypto", MethodSurcharge::Rate { percent: 1.0 }),
PerMethodSurchargeItem::new("card", MethodSurcharge::Fixed { amount: 35 })
.card_network("Visa")
.tax_on_surcharge_percent(20.0),
])
.default_surcharge(MethodSurcharge::Fixed { amount: 10 });
let saved = client
.routing()
.surcharge_rules()
.upsert(&req)
.await
.unwrap();
assert_eq!(saved.version, 2);
assert_eq!(saved.profile_id.as_deref(), Some("pro_1"));
assert_eq!(
saved.default_surcharge,
Some(MethodSurcharge::Fixed { amount: 10 })
);
assert!(saved.warnings.is_empty());
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/routing/surcharge/rules");
let body = seen[0].body_json();
assert_eq!(body["name"], "EU surcharges");
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["surcharges"][0]["payment_method"], "crypto");
assert_eq!(body["surcharges"][0]["surcharge"]["rate"]["percent"], 1.0);
assert_eq!(body["surcharges"][1]["surcharge"]["fixed"]["amount"], 35);
assert_eq!(body["surcharges"][1]["card_network"], "Visa");
assert_eq!(body["surcharges"][1]["tax_on_surcharge_percent"], 20.0);
assert_eq!(body["default_surcharge"]["fixed"]["amount"], 10);
}
#[tokio::test]
async fn surcharge_rules_scope_the_read_and_delete_by_profile() {
let (client, mock) = client_with(vec![
Step::ok(SURCHARGE_JSON),
Step::ok("null"),
Step::ok(""),
Step::ok(""),
]);
let rules = client.routing().surcharge_rules();
let scoped = rules
.retrieve(Some("pro 1"))
.await
.unwrap()
.expect("a program body decodes to Some");
assert_eq!(scoped.name, "EU surcharges");
assert!(
rules.retrieve(None).await.unwrap().is_none(),
"a null body means no surcharge program is set for the scope"
);
rules.delete(Some("pro 1")).await.unwrap();
rules.delete(None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
(
"GET",
"https://api.test/routing/surcharge/rules?profile_id=pro 1"
)
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
("GET", "https://api.test/routing/surcharge/rules")
);
assert_eq!(
(seen[2].method, seen[2].url.as_str()),
(
"DELETE",
"https://api.test/routing/surcharge/rules?profile_id=pro 1"
)
);
assert_eq!(
(seen[3].method, seen[3].url.as_str()),
("DELETE", "https://api.test/routing/surcharge/rules")
);
}
#[test]
fn routing_config_create_request_named_fields_are_complete() {
let req = RoutingConfigCreateRequest {
name: Some("n".to_string()),
description: Some("d".to_string()),
algorithm: Some(json!({"type": "priority", "data": []})),
profile_id: Some("pro_1".to_string()),
transaction_type: Some("payment".to_string()),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
ROUTING_CONFIG_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"ROUTING_CONFIG_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn routing_deactivate_request_named_fields_are_complete() {
let req = RoutingDeactivateRequest {
name: Some("n".to_string()),
description: Some("d".to_string()),
algorithm: Some(json!({})),
profile_id: Some("pro_1".to_string()),
transaction_type: Some("payment".to_string()),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
ROUTING_DEACTIVATE_REQUEST_NAMED.contains(&key.as_str()),
"ROUTING_DEACTIVATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn surcharge_rule_request_named_fields_are_complete() {
let req = SurchargeRuleRequest {
name: Some("n".to_string()),
profile_id: Some("pro_1".to_string()),
surcharges: Some(vec![PerMethodSurchargeItem::new(
"card",
MethodSurcharge::Fixed { amount: 1 },
)]),
default_surcharge: Some(MethodSurcharge::Rate { percent: 1.0 }),
show_surcharge_breakup_screen: Some(true),
valid_from: Some("2026-01-01T00:00:00Z".to_string()),
valid_until: Some("2026-12-31T00:00:00Z".to_string()),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
SURCHARGE_RULE_REQUEST_NAMED.contains(&key.as_str()),
"SURCHARGE_RULE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn validate_rejects_extra_keys_colliding_with_named_fields() {
let mut create = RoutingConfigCreateRequest::new();
create.extra.insert("algorithm".to_string(), json!({}));
match create.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("algorithm")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
let mut deactivate = RoutingDeactivateRequest::default();
deactivate
.extra
.insert("profile_id".to_string(), json!("pro_2"));
assert!(matches!(
deactivate.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
let mut surcharge = SurchargeRuleRequest::new();
surcharge
.extra
.insert("valid_until".to_string(), json!("2026-01-01T00:00:00Z"));
assert!(matches!(
surcharge.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
}