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::cost_rule::{
MerchantCostRuleCategory, MerchantCostRuleDeleteResponse, MerchantCostRuleResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct CostRules {
inner: Arc<Inner>,
}
impl CostRules {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn list(&self, merchant_id: &str) -> Result<Vec<MerchantCostRuleResponse>> {
self.inner
.request(
HttpMethod::Get,
"/cost-rules",
None,
&merchant_query(merchant_id),
None,
)
.await
}
pub async fn create(
&self,
merchant_id: &str,
params: &CreateMerchantCostRuleRequest,
) -> Result<MerchantCostRuleResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Post,
"/cost-rules",
Some(&body),
&merchant_query(merchant_id),
None,
)
.await
}
pub async fn update(
&self,
merchant_id: &str,
rule_id: &str,
params: &UpdateMerchantCostRuleRequest,
) -> Result<MerchantCostRuleResponse> {
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Put,
&rule_path(rule_id),
Some(&body),
&merchant_query(merchant_id),
None,
)
.await
}
pub async fn delete(
&self,
merchant_id: &str,
rule_id: &str,
) -> Result<MerchantCostRuleDeleteResponse> {
self.inner
.request_body_keyed_with_query(
HttpMethod::Delete,
&rule_path(rule_id),
None,
&merchant_query(merchant_id),
None,
)
.await
}
}
fn rule_path(rule_id: &str) -> String {
format!("/cost-rules/{}", encode_segment(rule_id))
}
fn merchant_query(merchant_id: &str) -> Vec<(&'static str, String)> {
vec![("merchant_id", merchant_id.to_string())]
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateMerchantCostRuleRequest {
pub category: MerchantCostRuleCategory,
#[serde(skip_serializing_if = "Option::is_none")]
pub shop_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub percentage: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub flat_currency: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub effective_from: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub effective_to: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl CreateMerchantCostRuleRequest {
pub fn new(category: impl Into<MerchantCostRuleCategory>) -> Self {
Self {
category: category.into(),
..Default::default()
}
}
#[must_use]
pub fn shop_id(mut self, shop_id: impl Into<String>) -> Self {
self.shop_id = Some(shop_id.into());
self
}
#[must_use]
pub fn percentage(mut self, percentage: f64) -> Self {
self.percentage = Some(percentage);
self
}
#[must_use]
pub fn flat_amount(mut self, flat_amount: i64) -> Self {
self.flat_amount = Some(flat_amount);
self
}
#[must_use]
pub fn flat_currency(mut self, flat_currency: impl Into<String>) -> Self {
self.flat_currency = Some(flat_currency.into());
self
}
#[must_use]
pub fn min_amount(mut self, min_amount: i64) -> Self {
self.min_amount = Some(min_amount);
self
}
#[must_use]
pub fn max_amount(mut self, max_amount: i64) -> Self {
self.max_amount = Some(max_amount);
self
}
#[must_use]
pub fn effective_from(mut self, effective_from: impl Into<String>) -> Self {
self.effective_from = Some(effective_from.into());
self
}
#[must_use]
pub fn effective_to(mut self, effective_to: impl Into<String>) -> Self {
self.effective_to = Some(effective_to.into());
self
}
#[must_use]
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
}
const CREATE_MERCHANT_COST_RULE_REQUEST_NAMED: &[&str] = &[
"category",
"shop_id",
"percentage",
"flat_amount",
"flat_currency",
"min_amount",
"max_amount",
"effective_from",
"effective_to",
"label",
];
impl ValidateRequest for CreateMerchantCostRuleRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CREATE_MERCHANT_COST_RULE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on CreateMerchantCostRuleRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateMerchantCostRuleRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub effective_to: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_active: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub label: Option<Option<String>>,
}
impl UpdateMerchantCostRuleRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn effective_to(mut self, effective_to: impl Into<String>) -> Self {
self.effective_to = Some(effective_to.into());
self
}
#[must_use]
pub fn is_active(mut self, is_active: bool) -> Self {
self.is_active = Some(is_active);
self
}
#[must_use]
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = Some(Some(label.into()));
self
}
#[must_use]
pub fn clear_label(mut self) -> Self {
self.label = Some(None);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const RULE_JSON: &str = r#"{
"id": "mcr_1",
"merchant_id": "mer_1",
"shop_id": "pro_1",
"category": "partner_share",
"percentage": 42.5,
"effective_from": "2026-01-01T00:00:00Z",
"is_active": true,
"label": "Studio A",
"surprise_field": 1
}"#;
#[tokio::test]
async fn list_gets_the_merchant_rules() {
let (client, mock) = client_with(vec![Step::ok(&format!("[{RULE_JSON}]"))]);
let out = client.cost_rules().list("mer_1").await.unwrap();
assert_eq!(out[0].id, "mcr_1");
assert_eq!(out[0].category, "partner_share");
assert_eq!(out[0].percentage, Some(42.5));
assert!(out[0].effective_to.is_none());
assert_eq!(out[0].extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/cost-rules?merchant_id=mer_1");
}
#[tokio::test]
async fn create_ignores_a_client_wide_key_and_is_not_replayed() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, r#"{"error":{"message":"down"}}"#),
Step::ok(RULE_JSON),
],
2,
);
let params = CreateMerchantCostRuleRequest::new("partner_share").percentage(42.5);
assert!(
client
.with_idempotency_key("client-key")
.cost_rules()
.create("mer_1", ¶ms)
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn create_posts_the_rule_and_omits_unset_fields() {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let params = CreateMerchantCostRuleRequest::new("partner_share")
.shop_id("pro_1")
.percentage(42.5)
.label("Studio A");
let out = client.cost_rules().create("mer_1", ¶ms).await.unwrap();
assert_eq!(out.shop_id.as_deref(), Some("pro_1"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/cost-rules?merchant_id=mer_1");
assert_eq!(
seen[0].body_json(),
json!({"category":"partner_share","shop_id":"pro_1","percentage":42.5,
"label":"Studio A"})
);
}
#[tokio::test]
async fn update_puts_the_encoded_rule_and_sends_a_null_label_to_clear_it() {
let (client, mock) = client_with(vec![Step::ok(RULE_JSON)]);
let params = UpdateMerchantCostRuleRequest::new()
.is_active(false)
.clear_label();
client
.cost_rules()
.update("mer_1", "mcr/1", ¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/cost-rules/mcr%2F1?merchant_id=mer_1"
);
assert_eq!(seen[0].body_json(), json!({"is_active":false,"label":null}));
}
#[test]
fn update_without_a_label_leaves_the_key_out() {
let value =
serde_json::to_value(UpdateMerchantCostRuleRequest::new().is_active(true)).unwrap();
assert_eq!(value, json!({"is_active":true}));
let value = serde_json::to_value(UpdateMerchantCostRuleRequest::new().label("B")).unwrap();
assert_eq!(value, json!({"label":"B"}));
}
#[tokio::test]
async fn delete_deletes_the_encoded_rule_and_decodes_the_answer() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"deleted":true,"id":"mcr/1","surprise_field":1}"#,
)]);
let out = client.cost_rules().delete("mer_1", "mcr/1").await.unwrap();
assert!(out.deleted);
assert_eq!(out.id, "mcr/1");
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/cost-rules/mcr%2F1?merchant_id=mer_1"
);
}
#[test]
fn create_merchant_cost_rule_request_named_fields_are_complete() {
let req = CreateMerchantCostRuleRequest::new("goods")
.shop_id("pro_1")
.percentage(10.0)
.flat_amount(100)
.flat_currency("EUR")
.min_amount(1)
.max_amount(1000)
.effective_from("2026-01-01T00:00:00Z")
.effective_to("2027-01-01T00:00:00Z")
.label("Supplier");
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
CREATE_MERCHANT_COST_RULE_REQUEST_NAMED.contains(&key.as_str()),
"CREATE_MERCHANT_COST_RULE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn create_validate_rejects_colliding_extra_key() {
let mut req = CreateMerchantCostRuleRequest::new("goods");
req.extra.insert("category".to_string(), json!("other"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("category")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}