use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::to_json_vec;
use crate::core::error::{DelopayError, Result};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct ThreeDsRules {
inner: Arc<Inner>,
}
impl ThreeDsRules {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn execute(&self, params: &ThreeDsRuleExecuteRequest) -> Result<Value> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/three-ds-decision/execute",
Some(&body),
&[],
None,
)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ThreeDsRuleExecuteRequest {
pub routing_id: String,
pub payment: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_device: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub issuer: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub acquirer: Option<Value>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const THREE_DS_RULE_EXECUTE_REQUEST_NAMED: &[&str] = &[
"routing_id",
"payment",
"payment_method",
"customer_device",
"issuer",
"acquirer",
];
impl ValidateRequest for ThreeDsRuleExecuteRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if THREE_DS_RULE_EXECUTE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ThreeDsRuleExecuteRequest"
)));
}
}
Ok(())
}
}
impl ThreeDsRuleExecuteRequest {
pub fn new(routing_id: impl Into<String>, payment: Value) -> Self {
Self {
routing_id: routing_id.into(),
payment,
..Default::default()
}
}
pub fn payment_method(mut self, payment_method: Value) -> Self {
self.payment_method = Some(payment_method);
self
}
pub fn customer_device(mut self, customer_device: Value) -> Self {
self.customer_device = Some(customer_device);
self
}
pub fn issuer(mut self, issuer: Value) -> Self {
self.issuer = Some(issuer);
self
}
pub fn acquirer(mut self, acquirer: Value) -> Self {
self.acquirer = Some(acquirer);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
#[tokio::test]
async fn execute_posts_the_context_to_the_decision_path() {
let (client, mock) = client_with(vec![Step::ok(r#"{"decision":"challenge"}"#)]);
let req =
ThreeDsRuleExecuteRequest::new("rou_1", json!({"amount": 1000, "currency": "EUR"}))
.payment_method(json!({"payment_method": "card"}))
.customer_device(json!({"platform": "web"}))
.issuer(json!({"name": "issuer_bank"}))
.acquirer(json!({"country": "DE"}));
let out = client.three_ds_rules().execute(&req).await.unwrap();
assert_eq!(out["decision"], "challenge");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/three-ds-decision/execute");
let body = seen[0].body_json();
assert_eq!(body["routing_id"], "rou_1");
assert_eq!(body["payment"]["currency"], "EUR");
assert_eq!(body["payment_method"]["payment_method"], "card");
assert_eq!(body["customer_device"]["platform"], "web");
assert_eq!(body["issuer"]["name"], "issuer_bank");
assert_eq!(body["acquirer"]["country"], "DE");
}
#[tokio::test]
async fn execute_omits_absent_context_blocks() {
let (client, mock) = client_with(vec![Step::ok(r#"{"decision":"no_three_ds"}"#)]);
let req = ThreeDsRuleExecuteRequest::new("rou_1", json!({"amount": 1000}));
client.three_ds_rules().execute(&req).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].body_json(),
json!({"routing_id": "rou_1", "payment": {"amount": 1000}})
);
}
#[test]
fn three_ds_rule_execute_request_named_fields_are_complete() {
let req = ThreeDsRuleExecuteRequest::new("rou_1", json!({}))
.payment_method(json!({}))
.customer_device(json!({}))
.issuer(json!({}))
.acquirer(json!({}));
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
THREE_DS_RULE_EXECUTE_REQUEST_NAMED.contains(&key.as_str()),
"THREE_DS_RULE_EXECUTE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn validate_rejects_extra_key_colliding_with_named_field() {
let mut req = ThreeDsRuleExecuteRequest::new("rou_1", json!({}));
req.extra.insert("payment".to_string(), json!({}));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("payment")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}