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::settings::SettingsResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Settings {
inner: Arc<Inner>,
}
impl Settings {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn retrieve_merchant(&self, project_id: Option<&str>) -> Result<SettingsResponse> {
self.inner
.request(
HttpMethod::Get,
"/settings/merchant",
None,
&project_query(project_id),
None,
)
.await
}
pub async fn update_merchant(
&self,
params: &UpdateSettingsRequest,
project_id: Option<&str>,
) -> Result<SettingsResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Patch,
"/settings/merchant",
Some(&body),
&project_query(project_id),
None,
)
.await
}
pub async fn retrieve_shop(&self, profile_id: &str) -> Result<SettingsResponse> {
self.inner
.request(HttpMethod::Get, &shop_path(profile_id), None, &[], None)
.await
}
pub async fn update_shop(
&self,
profile_id: &str,
params: &UpdateSettingsRequest,
) -> Result<SettingsResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Patch,
&shop_path(profile_id),
Some(&body),
&[],
None,
)
.await
}
}
fn shop_path(profile_id: &str) -> String {
format!("/settings/shops/{}", encode_segment(profile_id))
}
fn project_query(project_id: Option<&str>) -> Vec<(&'static str, String)> {
match project_id {
Some(id) if !id.is_empty() => vec![("project_id", id.to_string())],
_ => Vec::new(),
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateSettingsRequest {
pub changes: Vec<SettingChangeRequest>,
}
impl UpdateSettingsRequest {
pub fn new(changes: Vec<SettingChangeRequest>) -> Self {
Self { changes }
}
}
impl ValidateRequest for UpdateSettingsRequest {
fn validate(&self) -> Result<()> {
self.changes.iter().try_for_each(|change| change.validate())
}
}
#[derive(Clone, Default, Serialize)]
pub struct SettingChangeRequest {
pub key: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub qualifier: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub clear: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expected_revision: Option<i64>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl std::fmt::Debug for SettingChangeRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SettingChangeRequest")
.field("key", &self.key)
.field("qualifier", &self.qualifier)
.field("value", &self.value.as_ref().map(|_| "[redacted]"))
.field("clear", &self.clear)
.field("expected_revision", &self.expected_revision)
.field("extra_keys", &self.extra.keys().collect::<Vec<_>>())
.finish()
}
}
impl SettingChangeRequest {
pub fn set_value(key: impl Into<String>, value: Value) -> Self {
Self {
key: key.into(),
value: Some(value),
..Default::default()
}
}
pub fn clear_value(key: impl Into<String>) -> Self {
Self {
key: key.into(),
clear: Some(true),
..Default::default()
}
}
#[must_use]
pub fn qualifier(mut self, qualifier: impl Into<String>) -> Self {
self.qualifier = Some(qualifier.into());
self
}
#[must_use]
pub fn expected_revision(mut self, revision: i64) -> Self {
self.expected_revision = Some(revision);
self
}
}
const SETTING_CHANGE_REQUEST_NAMED: &[&str] =
&["key", "qualifier", "value", "clear", "expected_revision"];
impl ValidateRequest for SettingChangeRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SETTING_CHANGE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on SettingChangeRequest"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const SETTINGS_JSON: &str = r#"{
"scope": "merchant",
"scope_id": "mer_1",
"settings": [{
"key": "replay_retention", "qualifier": null, "authority": "merchant",
"value": 30, "default_value": 7, "is_set": true, "revision": 4,
"updated_at": "2026-11-01T00:00:00Z",
"updated_by": {"id": "usr_1", "name": "ada@example.com"},
"secret": false, "effective_value": 30,
"effective_source": {"scope": "merchant", "scope_id": "mer_1",
"authority": "merchant"},
"detail": null, "entry_surprise": 1
}],
"surprise_field": "x"
}"#;
#[tokio::test]
async fn retrieve_merchant_gets_the_merchant_scope_without_a_project() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let out = client.settings().retrieve_merchant(None).await.unwrap();
assert_eq!(out.scope, "merchant");
assert_eq!(out.settings[0].key, "replay_retention");
assert_eq!(out.settings[0].value, json!(30));
assert_eq!(out.settings[0].revision, 4);
assert_eq!(
out.settings[0].updated_by.as_ref().map(|a| a.id.as_str()),
Some("usr_1")
);
assert_eq!(out.settings[0].extra["entry_surprise"], 1);
assert_eq!(out.extra["surprise_field"], "x");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/settings/merchant");
}
#[tokio::test]
async fn update_merchant_patches_a_project_with_the_changes() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let params = UpdateSettingsRequest::new(vec![
SettingChangeRequest::set_value("replay_retention", json!(30)).expected_revision(3),
SettingChangeRequest::clear_value("iframe_origin_rules"),
SettingChangeRequest::set_value("nullable_setting", Value::Null),
]);
client
.settings()
.update_merchant(¶ms, Some("prj_1"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PATCH");
assert_eq!(
seen[0].url,
"https://api.test/settings/merchant?project_id=prj_1"
);
assert_eq!(
seen[0].body_json(),
json!({"changes": [
{"key": "replay_retention", "value": 30, "expected_revision": 3},
{"key": "iframe_origin_rules", "clear": true},
{"key": "nullable_setting", "value": null}
]})
);
assert!(!seen[0].had_idempotency_key());
}
#[tokio::test]
async fn retrieve_shop_encodes_the_profile_id() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
client.settings().retrieve_shop("pro/1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/settings/shops/pro%2F1");
}
#[tokio::test]
async fn update_shop_patches_the_shop_path() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let params = UpdateSettingsRequest::new(vec![
SettingChangeRequest::set_value("payment_amount_limits", json!({"limits": []}))
.qualifier("stripe"),
]);
client
.settings()
.update_shop("pro_1", ¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PATCH");
assert_eq!(seen[0].url, "https://api.test/settings/shops/pro_1");
assert_eq!(
seen[0].body_json()["changes"][0],
json!({"key": "payment_amount_limits", "qualifier": "stripe",
"value": {"limits": []}})
);
}
#[tokio::test]
async fn update_rejects_a_colliding_extra_key_before_sending() {
let (client, mock) = client_with(vec![]);
let mut change = SettingChangeRequest::set_value("k", json!(1));
change.extra.insert("value".to_string(), json!(2));
let params = UpdateSettingsRequest::new(vec![change]);
match client
.settings()
.update_shop("pro_1", ¶ms)
.await
.unwrap_err()
{
DelopayError::InvalidRequest(msg) => assert!(msg.contains("value")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
assert_eq!(mock.call_count(), 0);
}
#[test]
fn a_change_debug_hides_the_value() {
let change = SettingChangeRequest::set_value("api_secret", json!("s3cr3t"));
assert!(!format!("{change:?}").contains("s3cr3t"));
}
#[test]
fn setting_change_request_named_fields_are_complete() {
let req = SettingChangeRequest {
key: "k".to_string(),
qualifier: Some("q".to_string()),
value: Some(json!(1)),
clear: Some(false),
expected_revision: Some(1),
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!(
SETTING_CHANGE_REQUEST_NAMED.contains(&key.as_str()),
"SETTING_CHANGE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
fn keyed_client_over_503s() -> (
crate::Delopay,
std::sync::Arc<crate::http::mock::MockTransport>,
) {
let (client, mock) = crate::http::mock::client_with_retries(
vec![Step::status(503, "{}"), Step::status(503, "{}")],
2,
);
(client.with_idempotency_key("client-wide-key"), mock)
}
fn assert_sent_once_unkeyed(mock: &crate::http::mock::MockTransport) {
assert_eq!(mock.call_count(), 1, "a 503 was replayed");
assert!(
!mock.seen.lock().unwrap()[0].had_idempotency_key(),
"the client-wide key was inherited"
);
}
#[tokio::test]
async fn new_writes_do_not_inherit_the_client_key() {
let (client, mock) = keyed_client_over_503s();
let params = UpdateSettingsRequest::new(vec![SettingChangeRequest::set_value(
"replay_retention",
json!(30),
)]);
assert!(
client
.settings()
.update_shop("pro_1", ¶ms)
.await
.is_err()
);
assert_sent_once_unkeyed(&mock);
}
}