use std::sync::Arc;
use crate::core::encoding::encode_segment;
use crate::core::error::Result;
use crate::core::models::audit::{MerchantAuditLogEntry, MerchantAuditLogListResponse};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
#[derive(Debug, Clone)]
pub struct Audit {
inner: Arc<Inner>,
}
impl Audit {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn list(
&self,
params: Option<&MerchantAuditLogListParams>,
) -> Result<MerchantAuditLogListResponse> {
let query = params
.map(MerchantAuditLogListParams::to_query)
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, "/audit", None, &query, None)
.await
}
pub async fn retrieve(&self, log_id: &str) -> Result<MerchantAuditLogEntry> {
let path = format!("/audit/{}", encode_segment(log_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
}
#[derive(Debug, Clone, Default)]
pub struct MerchantAuditLogListParams {
pub user_id: Option<String>,
pub profile_id: Option<String>,
pub session_id: Option<String>,
pub action: Option<String>,
pub entity_type: Option<String>,
pub entity_id: Option<String>,
pub start_date: Option<String>,
pub end_date: Option<String>,
pub offset: Option<i64>,
pub limit: Option<i64>,
}
impl MerchantAuditLogListParams {
pub(crate) fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = &self.user_id {
q.push(("user_id", v.clone()));
}
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
if let Some(v) = &self.session_id {
q.push(("session_id", v.clone()));
}
if let Some(v) = &self.action {
q.push(("action", v.clone()));
}
if let Some(v) = &self.entity_type {
q.push(("entity_type", v.clone()));
}
if let Some(v) = &self.entity_id {
q.push(("entity_id", v.clone()));
}
if let Some(v) = &self.start_date {
q.push(("start_date", v.clone()));
}
if let Some(v) = &self.end_date {
q.push(("end_date", v.clone()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
q
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
const ENTRY_JSON: &str = r#"{
"id": "log_1",
"actor": {"id": "usr_1", "kind": "team_member", "name": "ops@acme.test"},
"real_actor": {"id": "usr_2", "kind": "team_member", "name": "admin@acme.test"},
"impersonation_kind": "merchant_for_team_member",
"session": {
"id": "ses_1",
"ip_address": "203.0.113.7",
"country_code": "DE",
"latitude": 52.52,
"longitude": 13.4,
"auth_method": "password"
},
"profile_id": "pro_1",
"action": "update",
"entity_type": "business_profile",
"entity_id": "pro_1",
"entity_name": "EU Store",
"changed_fields": ["return_url", "webhook_url"],
"created_at": "2026-03-12T09:00:00Z",
"setting_change": {"key": "checkout.locale", "was_set": false, "is_set": true,
"old_value": null, "new_value": "de"},
"changes": [{"op": "moved", "environment": "live", "group": "express",
"field": "position", "item": {"kind": "method", "method": "apple_pay"},
"old_value": {"index": 2}, "new_value": {"index": 0}},
{"op": "changed", "field": "api_key", "withheld": true}],
"brand_new_field": 1
}"#;
#[tokio::test]
async fn list_serializes_every_named_filter_in_order() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"entries":[],"total_count":0,"offset":0,"limit":20}"#,
)]);
let params = MerchantAuditLogListParams {
user_id: Some("usr_1".to_string()),
profile_id: Some("pro_1".to_string()),
session_id: Some("ses_1".to_string()),
action: Some("update".to_string()),
entity_type: Some("business_profile".to_string()),
entity_id: Some("pro_1".to_string()),
start_date: Some("2026-03-01T00:00:00Z".to_string()),
end_date: Some("2026-03-31T00:00:00Z".to_string()),
offset: Some(40),
limit: Some(20),
};
client.audit().list(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/audit?user_id=usr_1&profile_id=pro_1&session_id=ses_1\
&action=update&entity_type=business_profile&entity_id=pro_1\
&start_date=2026-03-01T00:00:00Z\
&end_date=2026-03-31T00:00:00Z&offset=40&limit=20"
);
}
#[tokio::test]
async fn list_without_params_sends_no_query() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"entries":[],"total_count":0,"offset":0,"limit":20}"#,
)]);
client.audit().list(None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/audit");
}
#[tokio::test]
async fn retrieve_decodes_an_impersonated_entry_and_keeps_unknown_fields() {
let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
let entry = client.audit().retrieve("log/1").await.unwrap();
assert_eq!(entry.id, "log_1");
assert_eq!(entry.actor.kind, "team_member");
assert_eq!(entry.actor.name.as_deref(), Some("ops@acme.test"));
assert_eq!(
entry.real_actor.as_ref().and_then(|a| a.name.as_deref()),
Some("admin@acme.test")
);
assert_eq!(
entry.impersonation_kind.as_deref(),
Some("merchant_for_team_member")
);
assert_eq!(entry.session.as_ref().map(|s| s.id.as_str()), Some("ses_1"));
assert_eq!(entry.changed_fields, ["return_url", "webhook_url"]);
let setting = entry.setting_change.as_ref().unwrap();
assert!(!setting.was_set);
assert!(setting.old_value.is_none());
assert_eq!(setting.new_value, Some(serde_json::Value::from("de")));
let changes = entry.changes.as_ref().unwrap();
assert_eq!(changes[0].op, "moved");
assert_eq!(
changes[0].item.as_ref().unwrap().method.as_deref(),
Some("apple_pay")
);
assert!(changes[1].withheld);
assert!(entry.extra.contains_key("brand_new_field"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/audit/log%2F1");
}
#[tokio::test]
async fn a_delopay_actor_is_unnamed_and_sessionless() {
let (client, _mock) = client_with(vec![Step::ok(
r#"{
"id": "log_2",
"actor": {"kind": "delopay", "name": "DeloPay Support"},
"impersonation_kind": "admin_for_merchant",
"action": "update",
"entity_type": "merchant_account",
"changed_fields": [],
"created_at": "2026-03-12T10:00:00Z"
}"#,
)]);
let entry = client.audit().retrieve("log_2").await.unwrap();
assert_eq!(entry.actor.kind, "delopay");
assert!(entry.actor.id.is_none());
assert!(entry.session.is_none());
assert!(entry.real_actor.is_none());
}
#[tokio::test]
async fn an_unknown_actor_kind_still_decodes() {
let (client, _mock) = client_with(vec![Step::ok(
r#"{
"id": "log_3",
"actor": {"kind": "scheduled_job"},
"action": "delete",
"entity_type": "api_key",
"changed_fields": [],
"created_at": "2026-03-12T11:00:00Z"
}"#,
)]);
let entry = client.audit().retrieve("log_3").await.unwrap();
assert_eq!(entry.actor.kind, "scheduled_job");
}
}