delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `audit` resource: a merchant's own audit log.
//!
//! Everything changed on the merchant's account and its shops, grouped by the
//! sign-in it happened in.
//!
//! Requires a dashboard JWT (`DelopayBuilder::jwt`) whose role holds the
//! `AuditLog` permission; an API key cannot read it. That is deliberate: the
//! log names people, and an API key names no one.
//!
//! There is no `merchant_id` parameter anywhere here. The scope comes from the
//! token, so the resource cannot be pointed at another merchant.

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;

/// The `audit` resource, obtained via [`crate::Delopay::audit`].
#[derive(Debug, Clone)]
pub struct Audit {
    inner: Arc<Inner>,
}

impl Audit {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// List the merchant's audit entries, newest first. `GET /audit`
    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
    }

    /// One entry. `GET /audit/{log_id}`
    ///
    /// An id belonging to another merchant answers 404, not 403 — the endpoint
    /// does not confirm that an entry it will not serve exists.
    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
    }
}

/// Filters for [`Audit::list`].
///
/// Every id here is one of the merchant's own: the token fixes the merchant,
/// so these narrow within it and cannot reach across it.
#[derive(Debug, Clone, Default)]
pub struct MerchantAuditLogListParams {
    /// One of this merchant's own users.
    pub user_id: Option<String>,
    /// One of this merchant's shops.
    pub profile_id: Option<String>,
    /// One sign-in — the changes made in a single session.
    pub session_id: Option<String>,
    /// What was done, e.g. `"update"`.
    pub action: Option<String>,
    /// What it was done to, e.g. `"business_profile"`.
    pub entity_type: Option<String>,
    /// One entity's changes, by its ID.
    pub entity_id: Option<String>,
    /// Inclusive lower bound, ISO 8601 (`2026-03-12T00:00:00Z`).
    pub start_date: Option<String>,
    /// Inclusive upper bound, ISO 8601.
    pub end_date: Option<String>,
    /// Page offset.
    pub offset: Option<i64>,
    /// Page size.
    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(&params)).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");
    }

    /// The whole entry decodes, including the two actors and the session.
    ///
    /// Mutation: type `changed_fields` as `Option<Vec<String>>` and drop the
    /// `real_actor` assertion, and an impersonated change reads as if the
    /// signed-in user made it themselves.
    #[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");
    }

    /// A DeloPay actor is unnamed and carries no session, and both absences
    /// have to survive decoding rather than becoming empty strings.
    ///
    /// Mutation: default `id` / `session` to something non-`None` and this
    /// fails — which is the shape that would let a dashboard print a DeloPay
    /// employee's identity or their device to a merchant.
    #[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());
    }

    /// An unknown actor kind is data, not a failure: a party added later must
    /// not stop a merchant reading their own log.
    #[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");
    }
}