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::fee::FeeScheduleResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
pub use crate::core::models::fee::FeeType;
#[derive(Debug, Clone)]
pub struct Fees {
inner: Arc<Inner>,
}
impl Fees {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(
&self,
params: &FeeScheduleCreateRequest,
merchant_id: &str,
) -> Result<FeeScheduleResponse> {
params.validate()?;
let body = to_json_vec(params)?;
let query = [("merchant_id", merchant_id.to_string())];
self.inner
.request(
HttpMethod::Post,
"/merchant-fees",
Some(&body),
&query,
None,
)
.await
}
pub async fn list(&self, merchant_id: &str) -> Result<Vec<FeeScheduleResponse>> {
let query = [("merchant_id", merchant_id.to_string())];
self.inner
.request(HttpMethod::Get, "/merchant-fees/list", None, &query, None)
.await
}
pub async fn update(
&self,
fee_id: &str,
params: &FeeScheduleUpdateRequest,
) -> Result<FeeScheduleResponse> {
params.validate()?;
let body = to_json_vec(params)?;
let path = format!("/merchant-fees/{}", encode_segment(fee_id));
self.inner
.request(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn delete(&self, fee_id: &str) -> Result<FeeScheduleResponse> {
let path = format!("/merchant-fees/{}", encode_segment(fee_id));
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
}
#[derive(Debug, Clone, Serialize)]
pub struct FeeScheduleCreateRequest {
pub fee_type: FeeType,
#[serde(skip_serializing_if = "Option::is_none")]
pub shop_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub percentage_fee: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_fee_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_fee_currency: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_fee_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_fee_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub free_allowance_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub free_allowance_kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const FEE_SCHEDULE_CREATE_REQUEST_NAMED: &[&str] = &[
"fee_type",
"shop_id",
"percentage_fee",
"flat_fee_amount",
"flat_fee_currency",
"min_fee_amount",
"max_fee_amount",
"description",
"free_allowance_amount",
"free_allowance_kind",
"connector",
];
fn check_free_allowance(amount: Option<i64>, kind: Option<&str>) -> Result<()> {
if amount.is_some() != kind.is_some() {
return Err(DelopayError::InvalidRequest(
"`free_allowance_amount` and `free_allowance_kind` are set together".to_owned(),
));
}
Ok(())
}
impl ValidateRequest for FeeScheduleCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if FEE_SCHEDULE_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on FeeScheduleCreateRequest"
)));
}
}
check_free_allowance(
self.free_allowance_amount,
self.free_allowance_kind.as_deref(),
)
}
}
impl FeeScheduleCreateRequest {
pub fn new(fee_type: FeeType) -> Self {
Self {
fee_type,
shop_id: None,
percentage_fee: None,
flat_fee_amount: None,
flat_fee_currency: None,
min_fee_amount: None,
max_fee_amount: None,
description: None,
free_allowance_amount: None,
free_allowance_kind: None,
connector: None,
extra: serde_json::Map::new(),
}
}
pub fn free_allowance(mut self, amount: i64, kind: impl Into<String>) -> Self {
self.free_allowance_amount = Some(amount);
self.free_allowance_kind = Some(kind.into());
self
}
pub fn connector(mut self, connector: impl Into<String>) -> Self {
self.connector = Some(connector.into());
self
}
pub fn shop_id(mut self, shop_id: impl Into<String>) -> Self {
self.shop_id = Some(shop_id.into());
self
}
pub fn percentage_fee(mut self, percentage_fee: f64) -> Self {
self.percentage_fee = Some(percentage_fee);
self
}
pub fn flat_fee(mut self, amount: i64, currency: impl Into<String>) -> Self {
self.flat_fee_amount = Some(amount);
self.flat_fee_currency = Some(currency.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct FeeScheduleUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub fee_type: Option<FeeType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub percentage_fee: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_fee_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_fee_currency: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_fee_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_fee_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_active: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub free_allowance_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub free_allowance_kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const FEE_SCHEDULE_UPDATE_REQUEST_NAMED: &[&str] = &[
"fee_type",
"percentage_fee",
"flat_fee_amount",
"flat_fee_currency",
"min_fee_amount",
"max_fee_amount",
"description",
"is_active",
"free_allowance_amount",
"free_allowance_kind",
"connector",
];
impl ValidateRequest for FeeScheduleUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if FEE_SCHEDULE_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on FeeScheduleUpdateRequest"
)));
}
}
check_free_allowance(
self.free_allowance_amount,
self.free_allowance_kind.as_deref(),
)
}
}
impl FeeScheduleUpdateRequest {
pub fn new() -> Self {
Self::default()
}
pub fn free_allowance(mut self, amount: i64, kind: impl Into<String>) -> Self {
self.free_allowance_amount = Some(amount);
self.free_allowance_kind = Some(kind.into());
self
}
pub fn connector(mut self, connector: impl Into<String>) -> Self {
self.connector = Some(connector.into());
self
}
pub fn fee_type(mut self, fee_type: FeeType) -> Self {
self.fee_type = Some(fee_type);
self
}
pub fn percentage_fee(mut self, percentage_fee: f64) -> Self {
self.percentage_fee = Some(percentage_fee);
self
}
pub fn is_active(mut self, is_active: bool) -> Self {
self.is_active = Some(is_active);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const SCHEDULE_JSON: &str = r#"{
"id": "fee_1",
"merchant_id": "merch_1",
"fee_type": "percentage",
"is_active": true,
"fee_owner": "merchant",
"shop_id": "pro_1",
"percentage_fee": 2.5,
"free_allowance_amount": 10000,
"free_allowance_kind": "excess_only",
"connector": "stripe"
}"#;
#[tokio::test]
async fn create_posts_with_the_merchant_id_query() {
let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
let params = FeeScheduleCreateRequest::new(FeeType::Combined)
.shop_id("pro_1")
.percentage_fee(2.5)
.flat_fee(30, "USD");
let created = client.fees().create(¶ms, "merch_1").await.unwrap();
assert_eq!(created.id, "fee_1");
assert_eq!(created.fee_type, FeeType::Percentage);
assert_eq!(created.free_allowance_amount, Some(10_000));
assert_eq!(created.free_allowance_kind.as_deref(), Some("excess_only"));
assert_eq!(created.connector.as_deref(), Some("stripe"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/merchant-fees?merchant_id=merch_1"
);
let body = seen[0].body_json();
assert_eq!(body["fee_type"], "combined");
assert_eq!(body["shop_id"], "pro_1");
assert_eq!(body["percentage_fee"], 2.5);
assert_eq!(body["flat_fee_amount"], 30);
assert_eq!(body["flat_fee_currency"], "USD");
}
#[tokio::test]
async fn list_gets_the_list_path_with_the_merchant_id_query() {
let (client, mock) = client_with(vec![Step::ok(&format!("[{SCHEDULE_JSON}]"))]);
let schedules = client.fees().list("merch_1").await.unwrap();
assert_eq!(schedules.len(), 1);
assert_eq!(schedules[0].shop_id.as_deref(), Some("pro_1"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/merchant-fees/list?merchant_id=merch_1"
);
}
#[tokio::test]
async fn update_puts_to_the_encoded_fee_path() {
let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
let params = FeeScheduleUpdateRequest::new()
.fee_type(FeeType::Flat)
.is_active(false);
client.fees().update("fee/1", ¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/merchant-fees/fee%2F1");
let body = seen[0].body_json();
assert_eq!(body["fee_type"], "flat");
assert_eq!(body["is_active"], false);
}
#[tokio::test]
async fn delete_removes_the_schedule_by_id() {
let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
let deleted = client.fees().delete("fee_1").await.unwrap();
assert_eq!(deleted.id, "fee_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/merchant-fees/fee_1");
}
#[test]
fn a_half_set_free_allowance_is_refused() {
let mut half = FeeScheduleCreateRequest::new(FeeType::Percentage);
half.free_allowance_amount = Some(100);
assert!(half.validate().is_err());
let mut kind_only = FeeScheduleUpdateRequest::new();
kind_only.free_allowance_kind = Some("excess_only".to_string());
assert!(kind_only.validate().is_err());
let whole = FeeScheduleCreateRequest::new(FeeType::Percentage)
.free_allowance(100, "exemption_limit")
.connector("stripe");
assert!(whole.validate().is_ok());
let value = serde_json::to_value(whole).unwrap();
assert_eq!(value["free_allowance_amount"], 100);
assert_eq!(value["free_allowance_kind"], "exemption_limit");
assert_eq!(value["connector"], "stripe");
}
#[test]
fn fee_schedule_create_request_named_fields_are_complete() {
let req = FeeScheduleCreateRequest {
fee_type: FeeType::Combined,
shop_id: Some("pro_1".to_string()),
percentage_fee: Some(2.5),
flat_fee_amount: Some(30),
flat_fee_currency: Some("USD".to_string()),
min_fee_amount: Some(1),
max_fee_amount: Some(1000),
description: Some("standard".to_string()),
free_allowance_amount: Some(10_000),
free_allowance_kind: Some("excess_only".to_string()),
connector: Some("stripe".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!(
FEE_SCHEDULE_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"FEE_SCHEDULE_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn fee_schedule_update_request_named_fields_are_complete() {
let req = FeeScheduleUpdateRequest {
fee_type: Some(FeeType::Flat),
percentage_fee: Some(2.5),
flat_fee_amount: Some(30),
flat_fee_currency: Some("USD".to_string()),
min_fee_amount: Some(1),
max_fee_amount: Some(1000),
description: Some("standard".to_string()),
is_active: Some(true),
free_allowance_amount: Some(0),
free_allowance_kind: Some("exemption_limit".to_string()),
connector: Some(String::new()),
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!(
FEE_SCHEDULE_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"FEE_SCHEDULE_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn fee_schedule_create_validate_rejects_colliding_extra_key() {
let mut req = FeeScheduleCreateRequest::new(FeeType::Flat);
req.extra.insert("shop_id".to_string(), json!("pro_2"));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
#[test]
fn fee_schedule_update_validate_rejects_colliding_extra_key() {
let mut req = FeeScheduleUpdateRequest::new();
req.extra.insert("is_active".to_string(), json!(false));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
}