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, CheckoutThemeConversionResponse, CheckoutThemeProgramResponse,
ConnectorCapOverride, ConnectorCapOverrideList, ConnectorCapOverrides, DefaultProfileRouting,
MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, RoutableConnectorChoice,
RoutingConfigDeleteResponse, RoutingConfigHistoryResponse, RoutingConnectorCapReset,
RoutingDictionary, RoutingDictionaryRecord, RoutingVolumeCounters, SurchargeRuleResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
pub use crate::core::models::routing::{
MethodSurcharge, PerMethodSurchargeItem, SurchargeCondition,
};
pub use crate::core::models::routing::{
RoutingConnectorCap, RoutingConnectorCapSchedule, RoutingConnectorCapScheduleEntry,
RoutingConnectorCaps,
};
#[derive(Debug, Clone)]
pub struct Routing {
inner: Arc<Inner>,
}
impl Routing {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub fn surcharge_rules(&self) -> SurchargeRules {
SurchargeRules::new(self.inner.clone())
}
pub fn checkout_theme_rules(&self) -> CheckoutThemeRules {
CheckoutThemeRules::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 history(
&self,
algorithm_id: &str,
limit: Option<i32>,
offset: Option<i32>,
) -> Result<RoutingConfigHistoryResponse> {
let path = format!("/routing/{}/history", encode_segment(algorithm_id));
let mut query: Vec<(&str, String)> = Vec::new();
if let Some(limit) = limit {
query.push(("limit", limit.to_string()));
}
if let Some(offset) = offset {
query.push(("offset", offset.to_string()));
}
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn delete(&self, algorithm_id: &str) -> Result<RoutingConfigDeleteResponse> {
let path = format!("/routing/{}", encode_segment(algorithm_id));
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn default_for_profile(
&self,
profile_id: &str,
) -> Result<ProfileDefaultRoutingConfig> {
let path = format!("/routing/default/profile/{}", encode_segment(profile_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn volume_counters(&self, profile_id: &str) -> Result<RoutingVolumeCounters> {
let path = format!("/routing/volume-counters/{}", encode_segment(profile_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn connector_caps(&self, profile_id: &str) -> Result<RoutingConnectorCaps> {
let path = format!("/routing/connector-caps/{}", encode_segment(profile_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn set_connector_caps(
&self,
profile_id: &str,
caps: &RoutingConnectorCaps,
) -> Result<RoutingConnectorCaps> {
let path = format!("/routing/connector-caps/{}", encode_segment(profile_id));
let body = to_json_vec(caps)?;
self.inner
.request(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn reset_connector_cap_usage(
&self,
profile_id: &str,
params: &RoutingConnectorCapResetRequest,
) -> Result<RoutingConnectorCapReset> {
let path = format!(
"/routing/connector-caps/{}/reset",
encode_segment(profile_id)
);
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn connector_cap_overrides(&self) -> Result<ConnectorCapOverrideList> {
self.inner
.request(
HttpMethod::Get,
"/routing/connector-caps/overrides",
None,
&[],
None,
)
.await
}
pub async fn account_connector_cap_overrides(
&self,
merchant_connector_id: &str,
) -> Result<ConnectorCapOverrides> {
let path = format!(
"/routing/connector-caps/accounts/{}/overrides",
encode_segment(merchant_connector_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn set_connector_cap_override(
&self,
merchant_connector_id: &str,
level: &str,
scope_id: &str,
params: &ConnectorCapOverrideRequest,
) -> Result<ConnectorCapOverride> {
params.validate()?;
let path = cap_override_path(merchant_connector_id, level, scope_id);
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn delete_connector_cap_override(
&self,
merchant_connector_id: &str,
level: &str,
scope_id: &str,
) -> Result<ConnectorCapOverride> {
let path = cap_override_path(merchant_connector_id, level, scope_id);
self.inner
.request_body_keyed_with_query(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn connector_cap_schedules(
&self,
profile_id: &str,
) -> Result<RoutingConnectorCapSchedule> {
let path = cap_schedule_path(profile_id, "");
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn set_connector_cap_schedules(
&self,
profile_id: &str,
schedule: &RoutingConnectorCapSchedule,
) -> Result<RoutingConnectorCapSchedule> {
let path = cap_schedule_path(profile_id, "");
let body = to_json_vec(schedule)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn shuffle_connector_cap_schedule(
&self,
profile_id: &str,
params: &RoutingConnectorCapScheduleShuffle,
) -> Result<RoutingConnectorCaps> {
let path = cap_schedule_path(profile_id, "/shuffle");
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn checkout_theme_conversion(
&self,
params: &CheckoutThemeConversionParams,
) -> Result<CheckoutThemeConversionResponse> {
self.inner
.request(
HttpMethod::Get,
"/routing/checkout-theme/conversion",
None,
¶ms.to_query(),
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 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 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 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::<serde::de::IgnoredAny>(
HttpMethod::Delete,
"/routing/surcharge/rules",
None,
&query,
None,
)
.await
.map(|_| ())
}
}
#[derive(Debug, Clone)]
pub struct CheckoutThemeRules {
inner: Arc<Inner>,
}
impl CheckoutThemeRules {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn upsert(
&self,
params: &CheckoutThemeProgramRequest,
) -> Result<CheckoutThemeProgramResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Put,
"/routing/checkout-theme/rules",
Some(&body),
&[],
None,
)
.await
}
pub async fn retrieve(
&self,
profile_id: Option<&str>,
) -> Result<Option<CheckoutThemeProgramResponse>> {
let query = profile_id_query(profile_id);
self.inner
.request(
HttpMethod::Get,
"/routing/checkout-theme/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_body_keyed_with_query::<serde::de::IgnoredAny>(
HttpMethod::Delete,
"/routing/checkout-theme/rules",
None,
&query,
None,
)
.await
.map(|_| ())
}
}
fn cap_override_path(merchant_connector_id: &str, level: &str, scope_id: &str) -> String {
format!(
"/routing/connector-caps/accounts/{}/overrides/{}/{}",
encode_segment(merchant_connector_id),
encode_segment(level),
encode_segment(scope_id)
)
}
fn cap_schedule_path(profile_id: &str, suffix: &str) -> String {
format!(
"/routing/connector-cap-schedules/{}{suffix}",
encode_segment(profile_id)
)
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingConnectorCapResetRequest {
pub merchant_connector_id: String,
pub unit: String,
}
impl RoutingConnectorCapResetRequest {
pub fn new(merchant_connector_id: impl Into<String>, unit: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
unit: unit.into(),
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingConnectorCapScheduleShuffle {
pub revision: String,
pub id: String,
pub value: i64,
}
impl RoutingConnectorCapScheduleShuffle {
pub fn new(revision: impl Into<String>, id: impl Into<String>, value: i64) -> Self {
Self {
revision: revision.into(),
id: id.into(),
value,
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorCapOverrideRequest {
pub mode: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub caps: Option<Vec<RoutingConnectorCap>>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ConnectorCapOverrideRequest {
pub fn unlimited() -> Self {
Self {
mode: "unlimited".to_string(),
..Default::default()
}
}
pub fn own(caps: Vec<RoutingConnectorCap>) -> Self {
Self {
mode: "own".to_string(),
caps: Some(caps),
extra: serde_json::Map::new(),
}
}
}
const CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED: &[&str] = &["mode", "caps"];
impl ValidateRequest for ConnectorCapOverrideRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ConnectorCapOverrideRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CheckoutThemeProgramRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
pub algorithm: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub active: 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>,
}
impl CheckoutThemeProgramRequest {
pub fn new(algorithm: Value) -> Self {
Self {
algorithm,
..Default::default()
}
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn active(mut self, active: bool) -> Self {
self.active = Some(active);
self
}
#[must_use]
pub fn valid_from(mut self, valid_from: impl Into<String>) -> Self {
self.valid_from = Some(valid_from.into());
self
}
#[must_use]
pub fn valid_until(mut self, valid_until: impl Into<String>) -> Self {
self.valid_until = Some(valid_until.into());
self
}
}
const CHECKOUT_THEME_PROGRAM_REQUEST_NAMED: &[&str] = &[
"name",
"profile_id",
"algorithm",
"active",
"valid_from",
"valid_until",
];
impl ValidateRequest for CheckoutThemeProgramRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CHECKOUT_THEME_PROGRAM_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on CheckoutThemeProgramRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct CheckoutThemeConversionParams {
pub profile_id: Option<String>,
pub start: String,
pub end: String,
pub segment: Option<String>,
pub device_class: Option<String>,
pub country: Option<String>,
pub selection: Option<String>,
}
impl CheckoutThemeConversionParams {
pub fn new(start: impl Into<String>, end: impl Into<String>) -> Self {
Self {
start: start.into(),
end: end.into(),
..Default::default()
}
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn segment(mut self, segment: impl Into<String>) -> Self {
self.segment = Some(segment.into());
self
}
#[must_use]
pub fn device_class(mut self, device_class: impl Into<String>) -> Self {
self.device_class = Some(device_class.into());
self
}
#[must_use]
pub fn country(mut self, country: impl Into<String>) -> Self {
self.country = Some(country.into());
self
}
#[must_use]
pub fn selection(mut self, selection: impl Into<String>) -> Self {
self.selection = Some(selection.into());
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut query = Vec::new();
if let Some(v) = &self.profile_id {
query.push(("profile_id", v.clone()));
}
query.push(("start", self.start.clone()));
query.push(("end", self.end.clone()));
let optional = [
("segment", &self.segment),
("device_class", &self.device_class),
("country", &self.country),
("selection", &self.selection),
];
for (key, value) in optional {
if let Some(v) = value {
query.push((key, v.clone()));
}
}
query
}
}
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::core::models::routing::{ConnectorCapDistribution, RoutingConnectorPaymentRange};
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 HISTORY_JSON: &str = r#"{
"id": "rou_1",
"profile_id": "pro_1",
"total_count": 3,
"versions": [
{
"version": 1,
"name": "EU Priority",
"description": "EU traffic",
"kind": "priority",
"algorithm": {"type": "priority", "data": [{"connector": "stripe"}]},
"valid_from": 1718000000,
"valid_until": 1718050000
},
{
"version": 2,
"name": "EU Priority",
"description": "EU traffic, adyen first",
"kind": "priority",
"algorithm": {"type": "priority", "data": [{"connector": "adyen"}]},
"valid_from": 1718050000
}
]
}"#;
const CAPS_JSON: &str = r#"{
"profile_id": "pro_1",
"caps": [
{"merchant_connector_id": "mca_1", "limit": 1, "used": 0, "reserved": 1},
{"merchant_connector_id": "mca_2", "limit": 5, "used": 5, "reserved": 0},
{"merchant_connector_id": "mca_3", "limit": 2}
]
}"#;
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 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"}]}]"#),
]);
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:?}"),
}
let seen = mock.seen.lock().unwrap();
let expected = [
"https://api.test/routing/active",
"https://api.test/routing/default/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("{}"),
]);
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
.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/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 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(r#"{"deleted":true}"#),
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(_)
));
}
#[tokio::test]
async fn history_pages_over_the_timeline_and_marks_the_live_window() {
let (client, mock) = client_with(vec![Step::ok(HISTORY_JSON)]);
let history = client
.routing()
.history("rou_1", Some(2), Some(4))
.await
.unwrap();
assert_eq!(history.total_count, 3);
assert_eq!(history.versions.len(), 2);
assert_eq!(history.versions[0].valid_until, Some(1_718_050_000));
assert!(!history.versions[0].is_live());
assert!(history.versions[1].is_live());
assert_eq!(
history.versions[1].algorithm["data"][0]["connector"],
"adyen"
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/routing/rou_1/history?limit=2&offset=4"
);
}
#[tokio::test]
async fn history_survives_a_window_with_no_description() {
const NO_DESCRIPTION: &str = r#"{
"id": "rou_1",
"profile_id": "pro_1",
"total_count": 1,
"versions": [
{
"version": 1,
"name": "EU Priority",
"kind": "priority",
"algorithm": {"type": "priority", "data": []},
"valid_from": 1718000000
}
]
}"#;
let (client, _mock) = client_with(vec![Step::ok(NO_DESCRIPTION)]);
let history = client.routing().history("rou_1", None, None).await.unwrap();
assert_eq!(
history.versions.first().map(|v| v.description.as_str()),
Some("")
);
}
#[tokio::test]
async fn history_omits_paging_it_was_not_given() {
let (client, mock) = client_with(vec![Step::ok(HISTORY_JSON)]);
client.routing().history("rou/1", None, None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/routing/rou%2F1/history");
}
#[tokio::test]
async fn connector_caps_reads_capacity_and_keeps_unknown_unknown() {
let (client, mock) = client_with(vec![Step::ok(CAPS_JSON)]);
let caps = client.routing().connector_caps("pro_1").await.unwrap();
assert_eq!(caps.profile_id.as_deref(), Some("pro_1"));
assert_eq!(caps.caps[0].has_capacity(), Some(false));
assert_eq!(caps.caps[1].has_capacity(), Some(false));
assert_eq!(caps.caps[2].used, None);
assert_eq!(caps.caps[2].has_capacity(), None);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/routing/connector-caps/pro_1");
}
#[tokio::test]
async fn set_connector_caps_puts_the_whole_set() {
let (client, mock) = client_with(vec![Step::ok(CAPS_JSON)]);
let caps = RoutingConnectorCaps::new(vec![RoutingConnectorCap::new("mca_1", 1)]);
client
.routing()
.set_connector_caps("pro_1", &caps)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/routing/connector-caps/pro_1");
let body = seen[0].body_json();
assert_eq!(body["caps"][0]["merchant_connector_id"], "mca_1");
assert_eq!(body["caps"][0]["limit"], 1);
assert!(body["caps"][0].get("used").is_none());
assert!(body["caps"][0].get("reserved").is_none());
assert!(body.get("profile_id").is_none());
}
#[tokio::test]
async fn connector_caps_decode_ranges_amounts_and_features() {
let (client, _mock) = client_with(vec![Step::ok(
r#"{"profile_id":"pro_1","caps":[
{"merchant_connector_id":"mca_1","limit":10,"limit_max":20,"unit":"payments",
"window":"daily","used":11,"reserved":0,"current_limit":15,
"current_limit_source":"reset","current_limit_drawn_at":"2026-09-01T00:00:00Z",
"distribution":{"kind":"normal","mean":15,"std_dev":2},
"current_limit_drawn_from":{"limit":10,"limit_max":20,
"distribution":{"kind":"normal","mean":15,"std_dev":2}}},
{"merchant_connector_id":"mca_1","limit":500000,"unit":"amount",
"currency":"EUR","window":"monthly","used":100,
"distribution":{"kind":"weighted","bands":[{"min":1,"max":2,"weight":3}]}}],
"active_caps":[],"scheduled_account_ids":["mca_2"],
"features":["dual_limits","limit_ranges","payment_ranges"],
"payment_ranges":[{"merchant_connector_id":"mca_1","currency":"EUR",
"min_amount":100,"max_amount":50000}]}"#,
)]);
let caps = client.routing().connector_caps("pro_1").await.unwrap();
let ranged = &caps.caps[0];
assert_eq!(ranged.limit_max, Some(20));
assert_eq!(ranged.current_limit, Some(15));
assert_eq!(ranged.has_capacity(), Some(true));
assert_eq!(ranged.distribution.as_ref().unwrap().std_dev, Some(2));
assert_eq!(
ranged.current_limit_drawn_from.as_ref().unwrap().limit_max,
20
);
let amount = &caps.caps[1];
assert_eq!(amount.unit.as_deref(), Some("amount"));
assert_eq!(amount.currency.as_deref(), Some("EUR"));
assert_eq!(
amount
.distribution
.as_ref()
.unwrap()
.bands
.as_ref()
.unwrap()[0]
.weight,
3
);
assert_eq!(
caps.features,
["dual_limits", "limit_ranges", "payment_ranges"]
);
assert_eq!(caps.scheduled_account_ids, ["mca_2"]);
assert!(caps.active_caps.as_ref().unwrap().is_empty());
assert_eq!(
caps.payment_ranges.as_ref().unwrap()[0].max_amount,
Some(50000)
);
}
#[tokio::test]
async fn set_connector_caps_sends_amount_caps_ranges_and_payment_ranges() {
let (client, mock) = client_with(vec![Step::ok(CAPS_JSON)]);
let caps = RoutingConnectorCaps::new(vec![
RoutingConnectorCap::new("mca_1", 10)
.window("daily")
.limit_max(20)
.distribution(ConnectorCapDistribution::triangular(12))
.set_current_limit(14),
RoutingConnectorCap::amount("mca_1", 500_000, "EUR", "monthly"),
])
.payment_ranges(vec![RoutingConnectorPaymentRange::new("mca_1", "EUR")]);
client
.routing()
.set_connector_caps("pro_1", &caps)
.await
.unwrap();
let body = mock.seen.lock().unwrap()[0].body_json();
assert_eq!(
body["caps"][0],
json!({"merchant_connector_id": "mca_1", "limit": 10, "window": "daily",
"limit_max": 20, "set_current_limit": 14,
"distribution": {"kind": "triangular", "mode": 12}})
);
assert_eq!(
body["caps"][1],
json!({"merchant_connector_id": "mca_1", "limit": 500000, "unit": "amount",
"currency": "EUR", "window": "monthly"})
);
assert_eq!(
body["payment_ranges"],
json!([{"merchant_connector_id": "mca_1", "currency": "EUR"}])
);
assert!(body.get("features").is_none());
assert!(body.get("scheduled_account_ids").is_none());
}
#[tokio::test]
async fn set_connector_caps_clears_every_cap_with_an_empty_list() {
let (client, mock) = client_with(vec![Step::ok(r#"{"profile_id":"pro_1","caps":[]}"#)]);
let caps = RoutingConnectorCaps::new(Vec::new());
let out = client
.routing()
.set_connector_caps("pro_1", &caps)
.await
.unwrap();
assert!(out.caps.is_empty());
let seen = mock.seen.lock().unwrap();
let body = seen[0].body_json();
assert_eq!(body["caps"], json!([]));
}
const OVERRIDE_JSON: &str = r#"{
"merchant_connector_id": "mca_1",
"level": "shop",
"scope_id": "pro_1",
"scope_name": "Main shop",
"mode": "own",
"caps": [{"merchant_connector_id": "mca_1", "limit": 10, "unit": "payments", "used": 2}],
"modified_at": "2026-01-01T00:00:00Z",
"surprise_field": 1
}"#;
const SCHEDULE_JSON: &str = r#"{
"revision": "rev_2",
"entries": [{
"id": "e1",
"starts_at": "2026-01-01T00:00:00Z",
"ends_at": "2026-02-01T00:00:00Z",
"cap": {"merchant_connector_id": "mca_1", "limit": 5, "unit": "payments",
"cap_surprise": true}
}],
"timezone": "UTC",
"observed_at": "2026-01-15T00:00:00Z",
"next_change_at": "2026-02-01T00:00:00Z",
"surprise_field": 1
}"#;
const THEME_PROGRAM_JSON: &str = r#"{
"id": "thm_1",
"name": "Autumn targeting",
"profile_id": "pro_1",
"algorithm": {"rules": [], "defaultSelection": {"theme": {"variant": "house"}}, "metadata": {}},
"version": 3,
"is_active": true,
"valid_from": "2026-01-01T00:00:00Z",
"warnings": ["variant `compact` is not defined"],
"surprise_field": 1
}"#;
#[tokio::test]
async fn reset_connector_cap_usage_posts_the_unit() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"merchant_connector_id":"mca_1","unit":"amount","window":"month","currency":"EUR",
"cleared":12000,"reserved":500,"reset_at":"2026-01-01T00:00:00Z","surprise_field":1}"#,
)]);
let out = client
.routing()
.reset_connector_cap_usage(
"pro/1",
&RoutingConnectorCapResetRequest::new("mca_1", "amount"),
)
.await
.unwrap();
assert_eq!(out.cleared, Some(12000));
assert_eq!(out.currency.as_deref(), Some("EUR"));
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-caps/pro%2F1/reset"
);
assert_eq!(
seen[0].body_json(),
json!({"merchant_connector_id": "mca_1", "unit": "amount"})
);
}
#[tokio::test]
async fn reset_connector_cap_usage_is_not_retried_on_a_server_error() {
let (client, mock) = crate::http::mock::client_with_retries(
vec![Step::status(503, "{}"), Step::ok("{}")],
2,
);
assert!(
client
.routing()
.reset_connector_cap_usage(
"pro_1",
&RoutingConnectorCapResetRequest::new("mca_1", "payments"),
)
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
}
#[tokio::test]
async fn connector_cap_overrides_gets_the_merchant_list() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"overrides":[{OVERRIDE_JSON}],"surprise_field":1}}"#
))]);
let out = client.routing().connector_cap_overrides().await.unwrap();
assert_eq!(out.overrides[0].mode, "own");
assert_eq!(out.overrides[0].caps[0].used, Some(2));
assert_eq!(out.overrides[0].extra["surprise_field"], 1);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-caps/overrides"
);
}
#[tokio::test]
async fn account_connector_cap_overrides_gets_the_account_path() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"merchant_connector_id":"mca_1","account_scope":"pro_1",
"overrides":[{OVERRIDE_JSON}],
"shops":[{{"profile_id":"pro_1","source":"shop","source_id":"pro_1","mode":"own"}}],
"surprise_field":1}}"#
))]);
let out = client
.routing()
.account_connector_cap_overrides("mca/1")
.await
.unwrap();
assert_eq!(out.account_scope, "pro_1");
assert_eq!(out.shops[0].source, "shop");
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-caps/accounts/mca%2F1/overrides"
);
}
#[tokio::test]
async fn set_connector_cap_override_puts_the_target_path() {
let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
let params = ConnectorCapOverrideRequest::own(vec![RoutingConnectorCap::new("mca_1", 10)]);
let out = client
.routing()
.set_connector_cap_override("mca_1", "shop", "pro/1", ¶ms)
.await
.unwrap();
assert_eq!(out.scope_name.as_deref(), Some("Main shop"));
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-caps/accounts/mca_1/overrides/shop/pro%2F1"
);
assert_eq!(
seen[0].body_json(),
json!({"mode": "own", "caps": [{"merchant_connector_id": "mca_1", "limit": 10}]})
);
}
#[tokio::test]
async fn set_connector_cap_override_unlimited_sends_no_caps() {
let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
client
.routing()
.set_connector_cap_override(
"mca_1",
"project",
"prj_1",
&ConnectorCapOverrideRequest::unlimited(),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].body_json(), json!({"mode": "unlimited"}));
}
#[tokio::test]
async fn delete_connector_cap_override_deletes_the_target_path() {
let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
let out = client
.routing()
.delete_connector_cap_override("mca_1", "project", "prj_1")
.await
.unwrap();
assert_eq!(out.level, "shop");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-caps/accounts/mca_1/overrides/project/prj_1"
);
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn connector_cap_schedules_gets_and_decodes_the_schedule() {
let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
let out = client
.routing()
.connector_cap_schedules("pro/1")
.await
.unwrap();
assert_eq!(out.revision.as_deref(), Some("rev_2"));
assert_eq!(out.entries[0].cap.limit, 5);
assert_eq!(out.entries[0].cap.unit.as_deref(), Some("payments"));
assert_eq!(out.entries[0].cap.extra["cap_surprise"], true);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-cap-schedules/pro%2F1"
);
}
#[tokio::test]
async fn set_connector_cap_schedules_puts_the_complete_schedule() {
let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
let schedule = RoutingConnectorCapSchedule::new(
None,
vec![RoutingConnectorCapScheduleEntry::new(
"e1",
"2026-01-01T00:00:00Z",
"2026-02-01T00:00:00Z",
RoutingConnectorCap::new("mca_1", 5),
)],
);
client
.routing()
.set_connector_cap_schedules("pro_1", &schedule)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-cap-schedules/pro_1"
);
assert_eq!(
seen[0].body_json(),
json!({
"revision": null,
"entries": [{
"id": "e1",
"starts_at": "2026-01-01T00:00:00Z",
"ends_at": "2026-02-01T00:00:00Z",
"cap": {"merchant_connector_id": "mca_1", "limit": 5}
}]
})
);
}
#[tokio::test]
async fn shuffle_connector_cap_schedule_posts_to_the_shuffle_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"profile_id":"pro_1","caps":[{"merchant_connector_id":"mca_1","limit":7}],
"features":["limit_schedules"],"surprise_field":1}"#,
)]);
let out = client
.routing()
.shuffle_connector_cap_schedule(
"pro_1",
&RoutingConnectorCapScheduleShuffle::new("rev_2", "e1", 7),
)
.await
.unwrap();
assert_eq!(out.caps[0].limit, 7);
assert_eq!(out.features, ["limit_schedules"]);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/routing/connector-cap-schedules/pro_1/shuffle"
);
assert_eq!(
seen[0].body_json(),
json!({"revision": "rev_2", "id": "e1", "value": 7})
);
}
#[tokio::test]
async fn checkout_theme_conversion_sends_the_window_and_filters() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"segment":"device","filters":{"device_class":"phone","country":null},
"cells":[{"variant":"compact","segment":"phone","rendered":100,"paid":12,
"rate":0.12,"interval_low":0.07,"interval_high":0.2,"verdict":"enough"}],
"comparisons":[{"variant":"compact","segment":"phone","variant_rate":0.12,
"baseline_rate":0.08,"separates":true,"higher":"variant"}],
"denominator":"deduplicated_checkout_opens","caveats":["automated_traffic_excluded"],
"surprise_field":1}"#,
)]);
let params =
CheckoutThemeConversionParams::new("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z")
.profile_id("pro_1")
.segment("device")
.device_class("phone");
let out = client
.routing()
.checkout_theme_conversion(¶ms)
.await
.unwrap();
assert_eq!(out.cells[0].paid, 12);
assert_eq!(out.cells[0].rate, Some(0.12));
assert!(out.comparisons[0].separates);
assert_eq!(out.filters.device_class.as_deref(), Some("phone"));
assert_eq!(out.caveats, ["automated_traffic_excluded"]);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/routing/checkout-theme/conversion?profile_id=pro_1&start=2026-01-01T00:00:00Z&end=2026-02-01T00:00:00Z&segment=device&device_class=phone"
);
}
#[tokio::test]
async fn checkout_theme_rules_upsert_puts_the_program() {
let (client, mock) = client_with(vec![Step::ok(THEME_PROGRAM_JSON)]);
let algorithm = json!({
"rules": [],
"defaultSelection": {"theme": {"variant": "house"}},
"metadata": {}
});
let params = CheckoutThemeProgramRequest::new(algorithm.clone())
.name("Autumn targeting")
.profile_id("pro_1")
.active(false);
let out = client
.routing()
.checkout_theme_rules()
.upsert(¶ms)
.await
.unwrap();
assert_eq!(out.version, 3);
assert_eq!(out.warnings.len(), 1);
assert_eq!(
out.algorithm["defaultSelection"]["theme"]["variant"],
"house"
);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/routing/checkout-theme/rules");
assert_eq!(
seen[0].body_json(),
json!({
"name": "Autumn targeting",
"profile_id": "pro_1",
"algorithm": algorithm,
"active": false
})
);
}
#[tokio::test]
async fn checkout_theme_rules_retrieve_scopes_and_decodes_null() {
let (client, mock) = client_with(vec![Step::ok(THEME_PROGRAM_JSON), Step::ok("null")]);
let rules = client.routing().checkout_theme_rules();
let found = rules.retrieve(Some("pro_1")).await.unwrap();
assert_eq!(found.unwrap().id, "thm_1");
assert!(rules.retrieve(None).await.unwrap().is_none());
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/routing/checkout-theme/rules?profile_id=pro_1"
);
assert_eq!(seen[1].url, "https://api.test/routing/checkout-theme/rules");
}
#[tokio::test]
async fn checkout_theme_rules_delete_scopes_the_deactivation() {
let (client, mock) = client_with(vec![Step::ok("")]);
client
.routing()
.checkout_theme_rules()
.delete(Some("pro_1"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/routing/checkout-theme/rules?profile_id=pro_1"
);
}
#[tokio::test]
async fn checkout_theme_rules_delete_accepts_a_json_success_body() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"deactivated":true,"profile_id":"pro_1"}"#,
)]);
let out = client.routing().checkout_theme_rules().delete(None).await;
assert!(out.is_ok(), "{out:?}");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/routing/checkout-theme/rules");
}
#[test]
fn connector_cap_override_request_named_fields_are_complete() {
let req = ConnectorCapOverrideRequest::own(vec![RoutingConnectorCap::new("mca_1", 1)]);
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED.contains(&key.as_str()),
"CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn checkout_theme_program_request_named_fields_are_complete() {
let req = CheckoutThemeProgramRequest::new(json!({}))
.name("n")
.profile_id("pro_1")
.active(true)
.valid_from("2026-01-01T00:00:00Z")
.valid_until("2026-02-01T00:00:00Z");
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
CHECKOUT_THEME_PROGRAM_REQUEST_NAMED.contains(&key.as_str()),
"CHECKOUT_THEME_PROGRAM_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn override_and_theme_requests_reject_colliding_extra_keys() {
let mut a = ConnectorCapOverrideRequest::unlimited();
a.extra.insert("mode".to_string(), json!("own"));
match a.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("mode")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
let mut b = CheckoutThemeProgramRequest::new(json!({}));
b.extra.insert("algorithm".to_string(), json!({}));
match b.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("algorithm")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
fn keyed_client_over_503s() -> (
crate::Delopay,
std::sync::Arc<crate::http::mock::MockTransport>,
) {
let (client, mock) = crate::http::mock::client_with_retries(
vec![Step::status(503, "{}"), Step::status(503, "{}")],
2,
);
(client.with_idempotency_key("client-wide-key"), mock)
}
fn assert_sent_once_unkeyed(mock: &crate::http::mock::MockTransport) {
assert_eq!(mock.call_count(), 1, "a 503 was replayed");
assert!(
!mock.seen.lock().unwrap()[0].had_idempotency_key(),
"the client-wide key was inherited"
);
}
#[tokio::test]
async fn new_writes_do_not_inherit_the_client_key() {
let (client, mock) = keyed_client_over_503s();
let params = RoutingConnectorCapResetRequest::new("mca_1", "amount");
assert!(
client
.routing()
.reset_connector_cap_usage("pro_1", ¶ms)
.await
.is_err()
);
assert_sent_once_unkeyed(&mock);
let (client, mock) = keyed_client_over_503s();
assert!(
client
.routing()
.checkout_theme_rules()
.delete(None)
.await
.is_err()
);
assert_sent_once_unkeyed(&mock);
}
}