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::profile::ProfileAcquirerResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct ProfileAcquirers {
inner: Arc<Inner>,
}
impl ProfileAcquirers {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(
&self,
params: &ProfileAcquirerCreateRequest,
) -> Result<ProfileAcquirerResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/profile-acquirer",
Some(&body),
&[],
None,
)
.await
}
pub async fn update(
&self,
profile_id: &str,
profile_acquirer_id: &str,
params: &ProfileAcquirerUpdateRequest,
) -> Result<ProfileAcquirerResponse> {
params.validate()?;
let path = format!(
"/profile-acquirer/{}/{}",
encode_segment(profile_id),
encode_segment(profile_acquirer_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProfileAcquirerCreateRequest {
pub acquirer_assigned_merchant_id: String,
pub merchant_name: String,
pub network: String,
pub acquirer_bin: String,
pub acquirer_fraud_rate: f64,
pub profile_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub acquirer_ica: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const PROFILE_ACQUIRER_CREATE_REQUEST_NAMED: &[&str] = &[
"acquirer_assigned_merchant_id",
"merchant_name",
"network",
"acquirer_bin",
"acquirer_fraud_rate",
"profile_id",
"acquirer_ica",
];
impl ValidateRequest for ProfileAcquirerCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PROFILE_ACQUIRER_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on \
ProfileAcquirerCreateRequest"
)));
}
}
Ok(())
}
}
impl ProfileAcquirerCreateRequest {
pub fn new(
profile_id: impl Into<String>,
network: impl Into<String>,
acquirer_bin: impl Into<String>,
acquirer_assigned_merchant_id: impl Into<String>,
merchant_name: impl Into<String>,
acquirer_fraud_rate: f64,
) -> Self {
Self {
acquirer_assigned_merchant_id: acquirer_assigned_merchant_id.into(),
merchant_name: merchant_name.into(),
network: network.into(),
acquirer_bin: acquirer_bin.into(),
acquirer_fraud_rate,
profile_id: profile_id.into(),
acquirer_ica: None,
extra: serde_json::Map::new(),
}
}
#[must_use]
pub fn acquirer_ica(mut self, ica: impl Into<String>) -> Self {
self.acquirer_ica = Some(ica.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProfileAcquirerUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub acquirer_assigned_merchant_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub network: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub acquirer_bin: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub acquirer_ica: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub acquirer_fraud_rate: Option<f64>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED: &[&str] = &[
"acquirer_assigned_merchant_id",
"merchant_name",
"network",
"acquirer_bin",
"acquirer_ica",
"acquirer_fraud_rate",
];
impl ValidateRequest for ProfileAcquirerUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on \
ProfileAcquirerUpdateRequest"
)));
}
}
Ok(())
}
}
impl ProfileAcquirerUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn acquirer_fraud_rate(mut self, rate: f64) -> Self {
self.acquirer_fraud_rate = Some(rate);
self
}
#[must_use]
pub fn merchant_name(mut self, name: impl Into<String>) -> Self {
self.merchant_name = Some(name.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const ACQUIRER_JSON: &str = r#"{
"profile_acquirer_id": "pa_1",
"profile_id": "pro_1",
"acquirer_assigned_merchant_id": "acq_mid_1",
"merchant_name": "Acme",
"network": "Visa",
"acquirer_bin": "412345",
"acquirer_fraud_rate": 0.01
}"#;
fn full_create_request() -> ProfileAcquirerCreateRequest {
ProfileAcquirerCreateRequest::new("pro_1", "Visa", "412345", "acq_mid_1", "Acme", 0.01)
.acquirer_ica("1234")
}
fn full_update_request() -> ProfileAcquirerUpdateRequest {
ProfileAcquirerUpdateRequest {
acquirer_assigned_merchant_id: Some("acq_mid_1".to_string()),
merchant_name: Some("Acme".to_string()),
network: Some("Visa".to_string()),
acquirer_bin: Some("412345".to_string()),
acquirer_ica: Some("1234".to_string()),
acquirer_fraud_rate: Some(0.02),
extra: serde_json::Map::new(),
}
}
#[test]
fn profile_acquirer_create_request_named_fields_are_complete() {
let value = serde_json::to_value(full_create_request()).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
PROFILE_ACQUIRER_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"PROFILE_ACQUIRER_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn profile_acquirer_update_request_named_fields_are_complete() {
let value = serde_json::to_value(full_update_request()).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"PROFILE_ACQUIRER_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn validate_rejects_colliding_extra_keys() {
let mut create = full_create_request();
create.extra.insert("network".to_string(), json!("Amex"));
match create.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("network")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
let mut update = ProfileAcquirerUpdateRequest::new();
update.extra.insert("acquirer_bin".to_string(), json!("1"));
assert!(matches!(
update.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
#[tokio::test]
async fn create_posts_the_acquirer_identity() {
let (client, mock) = client_with(vec![Step::ok(ACQUIRER_JSON)]);
let created = client
.profile_acquirers()
.create(&full_create_request())
.await
.unwrap();
assert_eq!(created.profile_acquirer_id, "pa_1");
assert_eq!(created.acquirer_fraud_rate, Some(0.01));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/profile-acquirer");
let body = seen[0].body_json();
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["acquirer_bin"], "412345");
assert_eq!(body["acquirer_ica"], "1234");
}
#[tokio::test]
async fn update_posts_to_the_profile_and_acquirer_path() {
let (client, mock) = client_with(vec![Step::ok(ACQUIRER_JSON)]);
let req = ProfileAcquirerUpdateRequest::new()
.acquirer_fraud_rate(0.02)
.merchant_name("Acme Ltd");
let updated = client
.profile_acquirers()
.update("pro/1", "pa_1", &req)
.await
.unwrap();
assert_eq!(updated.network.as_deref(), Some("Visa"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/profile-acquirer/pro%2F1/pa_1"
);
let body = seen[0].body_json();
assert_eq!(body["merchant_name"], "Acme Ltd");
assert_eq!(body["acquirer_fraud_rate"], 0.02);
}
}