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::sell_to_restriction::{
ConnectorSellToRestriction, ProjectSellToRestriction, SellToRestrictionCapabilitiesResponse,
SellToRestrictionDecisionsResponse, SellToRestrictionsResponse, ShopSellToRestriction,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct SellToRestrictions {
inner: Arc<Inner>,
}
impl SellToRestrictions {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn retrieve(&self) -> Result<SellToRestrictionsResponse> {
self.inner
.request(HttpMethod::Get, "/sell-to-restrictions", None, &[], None)
.await
}
pub async fn update_merchant_policy(
&self,
params: &SellToRestrictionPolicyRequest,
) -> Result<SellToRestrictionsResponse> {
self.put("/sell-to-restrictions/merchant", params).await
}
pub async fn update_shop_override(
&self,
profile_id: &str,
params: &SellToRestrictionPolicyRequest,
) -> Result<ShopSellToRestriction> {
self.put(&scoped_path("shops", profile_id), params).await
}
pub async fn delete_shop_override(&self, profile_id: &str) -> Result<ShopSellToRestriction> {
self.delete(&scoped_path("shops", profile_id)).await
}
pub async fn retrieve_project(&self, project_id: &str) -> Result<ProjectSellToRestriction> {
self.get(&scoped_path("projects", project_id)).await
}
pub async fn update_project_policy(
&self,
project_id: &str,
params: &SellToRestrictionPolicyRequest,
) -> Result<ProjectSellToRestriction> {
self.put(&scoped_path("projects", project_id), params).await
}
pub async fn delete_project_policy(
&self,
project_id: &str,
) -> Result<ProjectSellToRestriction> {
self.delete(&scoped_path("projects", project_id)).await
}
pub async fn retrieve_connector_policy(
&self,
merchant_connector_id: &str,
) -> Result<ConnectorSellToRestriction> {
self.get(&scoped_path("connectors", merchant_connector_id))
.await
}
pub async fn update_connector_policy(
&self,
merchant_connector_id: &str,
params: &SellToRestrictionPolicyRequest,
) -> Result<ConnectorSellToRestriction> {
self.put(&scoped_path("connectors", merchant_connector_id), params)
.await
}
pub async fn delete_connector_policy(
&self,
merchant_connector_id: &str,
) -> Result<ConnectorSellToRestriction> {
self.delete(&scoped_path("connectors", merchant_connector_id))
.await
}
pub async fn capabilities(&self) -> Result<SellToRestrictionCapabilitiesResponse> {
self.get("/sell-to-restrictions/capabilities").await
}
pub async fn list_decisions(
&self,
payment_id: &str,
) -> Result<SellToRestrictionDecisionsResponse> {
let path = format!("{}/decisions", scoped_path("payments", payment_id));
self.get(&path).await
}
async fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
self.inner
.request(HttpMethod::Get, path, None, &[], None)
.await
}
async fn put<T: serde::de::DeserializeOwned>(
&self,
path: &str,
params: &SellToRestrictionPolicyRequest,
) -> Result<T> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Put, path, Some(&body), None)
.await
}
async fn delete<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
self.inner
.request_body_keyed(HttpMethod::Delete, path, None, None)
.await
}
}
fn scoped_path(kind: &str, id: &str) -> String {
format!("/sell-to-restrictions/{kind}/{}", encode_segment(id))
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SellToRestrictionPolicyRequest {
pub blocked_countries: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub block_unknown_ip_country: Option<bool>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl SellToRestrictionPolicyRequest {
pub fn new(blocked_countries: Vec<String>) -> Self {
Self {
blocked_countries,
..Default::default()
}
}
#[must_use]
pub fn block_unknown_ip_country(mut self, block: bool) -> Self {
self.block_unknown_ip_country = Some(block);
self
}
}
const SELL_TO_RESTRICTION_POLICY_REQUEST_NAMED: &[&str] =
&["blocked_countries", "block_unknown_ip_country"];
impl ValidateRequest for SellToRestrictionPolicyRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SELL_TO_RESTRICTION_POLICY_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on SellToRestrictionPolicyRequest"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const POLICY_JSON: &str = r#"{"blocked_countries":["RU","KP"],"block_unknown_ip_country":true,"modified_at":"2026-01-01T00:00:00Z"}"#;
fn shop_json() -> String {
format!(
r#"{{"profile_id":"pro_1","profile_name":"Main","source":"shop",
"effective_policy":{POLICY_JSON},"shop_surprise":1}}"#
)
}
fn project_json() -> String {
format!(
r#"{{"project_id":"prj_1","project_name":"EU","parent_project_id":null,
"is_active":true,"policy":{POLICY_JSON},"project_surprise":1}}"#
)
}
fn connector_json() -> String {
format!(
r#"{{"merchant_connector_id":"mca_1","connector_name":"stripe",
"policy":{POLICY_JSON},"enforces":{{"ip_country":true,"card_issuing_country":false}},
"connector_surprise":1}}"#
)
}
fn policy() -> SellToRestrictionPolicyRequest {
SellToRestrictionPolicyRequest::new(vec!["RU".to_string(), "KP".to_string()])
.block_unknown_ip_country(true)
}
#[tokio::test]
async fn retrieve_gets_every_policy() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"merchant_policy":{POLICY_JSON},"shops":[{}],"projects":[{}],"connectors":[{}],"x":1}}"#,
shop_json(),
project_json(),
connector_json()
))]);
let out = client.sell_to_restrictions().retrieve().await.unwrap();
assert_eq!(out.merchant_policy.unwrap().blocked_countries, ["RU", "KP"]);
assert_eq!(out.shops[0].source, "shop");
assert_eq!(out.projects[0].project_id, "prj_1");
assert!(out.connectors[0].enforces.ip_country);
assert_eq!(out.extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/sell-to-restrictions");
}
#[tokio::test]
async fn update_merchant_policy_puts_the_policy() {
let (client, mock) = client_with(vec![Step::ok(r#"{"shops":[]}"#)]);
client
.sell_to_restrictions()
.update_merchant_policy(&policy())
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/merchant"
);
assert_eq!(
seen[0].body_json(),
json!({"blocked_countries": ["RU", "KP"], "block_unknown_ip_country": true})
);
}
#[tokio::test]
async fn update_shop_override_puts_the_encoded_shop() {
let (client, mock) = client_with(vec![Step::ok(&shop_json())]);
let shop = client
.sell_to_restrictions()
.update_shop_override("pro/1", &policy())
.await
.unwrap();
assert_eq!(shop.extra["shop_surprise"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/shops/pro%2F1"
);
assert_eq!(
seen[0].body_json()["blocked_countries"],
json!(["RU", "KP"])
);
}
#[tokio::test]
async fn delete_shop_override_deletes_the_shop() {
let (client, mock) = client_with(vec![Step::ok(&shop_json())]);
client
.sell_to_restrictions()
.delete_shop_override("pro_1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/shops/pro_1"
);
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn retrieve_project_gets_the_project() {
let (client, mock) = client_with(vec![Step::ok(&project_json())]);
let project = client
.sell_to_restrictions()
.retrieve_project("prj_1")
.await
.unwrap();
assert!(project.is_active);
assert_eq!(project.extra["project_surprise"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/projects/prj_1"
);
}
#[tokio::test]
async fn update_project_policy_puts_the_project() {
let (client, mock) = client_with(vec![Step::ok(&project_json())]);
client
.sell_to_restrictions()
.update_project_policy("prj_1", &SellToRestrictionPolicyRequest::new(vec![]))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/projects/prj_1"
);
assert_eq!(seen[0].body_json(), json!({"blocked_countries": []}));
}
#[tokio::test]
async fn delete_project_policy_deletes_the_project() {
let (client, mock) = client_with(vec![Step::ok(&project_json())]);
client
.sell_to_restrictions()
.delete_project_policy("prj_1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/projects/prj_1"
);
}
#[tokio::test]
async fn retrieve_connector_policy_gets_the_connector() {
let (client, mock) = client_with(vec![Step::ok(&connector_json())]);
let out = client
.sell_to_restrictions()
.retrieve_connector_policy("mca_1")
.await
.unwrap();
assert_eq!(out.connector_name, "stripe");
assert_eq!(out.extra["connector_surprise"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/connectors/mca_1"
);
}
#[tokio::test]
async fn update_connector_policy_puts_the_connector() {
let (client, mock) = client_with(vec![Step::ok(&connector_json())]);
client
.sell_to_restrictions()
.update_connector_policy("mca_1", &policy())
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/connectors/mca_1"
);
assert_eq!(seen[0].body_json()["block_unknown_ip_country"], true);
}
#[tokio::test]
async fn delete_connector_policy_deletes_the_connector() {
let (client, mock) = client_with(vec![Step::ok(&connector_json())]);
client
.sell_to_restrictions()
.delete_connector_policy("mca/1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/connectors/mca%2F1"
);
}
#[tokio::test]
async fn capabilities_gets_the_capabilities_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"ip_country_resolution":{"edge_country_header":true,"geoip_database":false,
"signed_checkout_forwarding":true},"rails":[{"rail":"api_payments",
"ip_country":"merchant_stated_ip","card_issuing_country":"before_authorization","x":1}]}"#,
)]);
let out = client.sell_to_restrictions().capabilities().await.unwrap();
assert!(out.ip_country_resolution.edge_country_header);
assert_eq!(out.rails[0].ip_country, "merchant_stated_ip");
assert_eq!(out.rails[0].extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/capabilities"
);
}
#[tokio::test]
async fn list_decisions_gets_the_payment_decisions() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","decisions":[{"stage":"confirm","signal":"ip_country",
"country":"RU","policy_source":"merchant","created_at":"2026-01-01T00:00:00Z","x":1}]}"#,
)]);
let out = client
.sell_to_restrictions()
.list_decisions("pay/1")
.await
.unwrap();
assert_eq!(out.decisions[0].country.as_deref(), Some("RU"));
assert_eq!(out.decisions[0].extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/sell-to-restrictions/payments/pay%2F1/decisions"
);
}
#[test]
fn sell_to_restriction_policy_request_named_fields_are_complete() {
let value = serde_json::to_value(policy()).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
SELL_TO_RESTRICTION_POLICY_REQUEST_NAMED.contains(&key.as_str()),
"SELL_TO_RESTRICTION_POLICY_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn policy_validate_rejects_colliding_extra_key() {
let mut req = SellToRestrictionPolicyRequest::new(vec![]);
req.extra
.insert("blocked_countries".to_string(), json!(["US"]));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("blocked_countries")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[tokio::test]
async fn writes_ignore_the_client_wide_idempotency_key() {
let steps = (0..7)
.map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
.collect();
let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
let client = client.with_idempotency_key("client-key");
client
.sell_to_restrictions()
.update_merchant_policy(&policy())
.await
.unwrap_err();
client
.sell_to_restrictions()
.update_shop_override("pro_1", &policy())
.await
.unwrap_err();
client
.sell_to_restrictions()
.delete_shop_override("pro_1")
.await
.unwrap_err();
client
.sell_to_restrictions()
.update_project_policy("prj_1", &policy())
.await
.unwrap_err();
client
.sell_to_restrictions()
.delete_project_policy("prj_1")
.await
.unwrap_err();
client
.sell_to_restrictions()
.update_connector_policy("mca_1", &policy())
.await
.unwrap_err();
client
.sell_to_restrictions()
.delete_connector_policy("mca_1")
.await
.unwrap_err();
assert_eq!(mock.call_count(), 7);
for seen in mock.seen.lock().unwrap().iter() {
assert!(
!seen.had_idempotency_key(),
"{} sent the client key",
seen.url
);
}
}
}