delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `refunds` resource.

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::common::{ListResponse, RefundType};
use crate::core::models::refund::RefundResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Refund a payment (fully or partially).
    pub async fn create(&self, params: &RefundCreateRequest) -> Result<RefundResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/refunds", Some(&body), &[], None)
            .await
    }

    /// Refund a payment with an `Idempotency-Key` so the call is retry-safe.
    pub async fn create_idempotent(
        &self,
        params: &RefundCreateRequest,
        idempotency_key: &str,
    ) -> Result<RefundResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/refunds",
                Some(&body),
                &[],
                Some(idempotency_key),
            )
            .await
    }

    /// Retrieve a refund by ID.
    pub async fn retrieve(&self, refund_id: &str) -> Result<RefundResponse> {
        let path = format!("/refunds/{}", encode_segment(refund_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a refund's reason or metadata.
    pub async fn update(
        &self,
        refund_id: &str,
        params: &RefundUpdateRequest,
    ) -> Result<RefundResponse> {
        let path = format!("/refunds/{}", encode_segment(refund_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// List refunds. Pass optional filter/pagination params as a JSON object.
    pub async fn list(&self, params: Option<&Value>) -> Result<ListResponse<RefundResponse>> {
        let body = params
            .cloned()
            .unwrap_or_else(|| Value::Object(Default::default()));
        let bytes = to_json_vec(&body)?;
        self.inner
            .request(HttpMethod::Post, "/refunds/list", Some(&bytes), &[], None)
            .await
    }

    /// List refunds scoped to the profile the API key belongs to. Pass
    /// optional filter/pagination params as a JSON object.
    pub async fn list_by_profile(
        &self,
        params: Option<&Value>,
    ) -> Result<ListResponse<RefundResponse>> {
        let body = params
            .cloned()
            .unwrap_or_else(|| Value::Object(Default::default()));
        let bytes = to_json_vec(&body)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/refunds/profile/list",
                Some(&bytes),
                &[],
                None,
            )
            .await
    }

    /// Retrieve the filter options available for refunds. Query keys are open
    /// — pass `&[]` for none; see the API reference.
    pub async fn filters(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(HttpMethod::Get, "/refunds/filter", None, query, None)
            .await
    }

    /// Retrieve aggregated refund statistics. Query keys are open — see the
    /// API reference.
    pub async fn aggregate(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(HttpMethod::Get, "/refunds/aggregate", None, query, None)
            .await
    }

    /// Retrieve aggregated refund statistics, scoped to the profile the API
    /// key belongs to. Query keys are open — see the API reference.
    pub async fn aggregate_by_profile(&self, query: &[(&str, String)]) -> Result<Value> {
        self.inner
            .request(
                HttpMethod::Get,
                "/refunds/profile/aggregate",
                None,
                query,
                None,
            )
            .await
    }

    /// Manually move a refund to a new status. The body shape is open — see
    /// the API reference.
    pub async fn manual_update(&self, refund_id: &str, params: &Value) -> Result<RefundResponse> {
        let path = format!("/refunds/{}/manual-update", encode_segment(refund_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }
}

/// Parameters for [`Refunds::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundCreateRequest {
    /// ID of the payment to refund.
    pub payment_id: String,
    /// Provide your own refund ID (acts as an idempotency key server-side).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refund_id: Option<String>,
    /// Amount to refund in minor units. Omit to refund the full amount.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<i64>,
    /// Reason for the refund (stored for reporting).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Refund processing type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refund_type: Option<RefundType>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `RefundCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const REFUND_CREATE_REQUEST_NAMED: &[&str] = &[
    "payment_id",
    "refund_id",
    "amount",
    "reason",
    "refund_type",
    "metadata",
];

impl ValidateRequest for RefundCreateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if REFUND_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on RefundCreateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl RefundCreateRequest {
    /// A full refund of `payment_id`.
    pub fn new(payment_id: impl Into<String>) -> Self {
        Self {
            payment_id: payment_id.into(),
            ..Default::default()
        }
    }

    /// Refund only `amount` (minor units) instead of the full payment.
    pub fn amount(mut self, amount: i64) -> Self {
        self.amount = Some(amount);
        self
    }

    /// Set the refund reason.
    pub fn reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Set the refund processing type.
    pub fn refund_type(mut self, refund_type: RefundType) -> Self {
        self.refund_type = Some(refund_type);
        self
    }
}

/// Parameters for [`Refunds::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundUpdateRequest {
    /// Updated reason.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Updated metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Every optional field populated so serialization emits the full key set.
    fn full_refund_create_request() -> RefundCreateRequest {
        RefundCreateRequest {
            payment_id: "pay_1".to_string(),
            refund_id: Some("ref_1".to_string()),
            amount: Some(500),
            reason: Some("requested_by_customer".to_string()),
            refund_type: Some(RefundType::Instant),
            metadata: Some(json!({"order_id": "o_1"})),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard: catches a new field added to `RefundCreateRequest`
    /// without a matching update to `REFUND_CREATE_REQUEST_NAMED`.
    #[test]
    fn refund_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_refund_create_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                REFUND_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "REFUND_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or RefundCreateRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = RefundCreateRequest::new("pay_1");
        req.extra.insert("amount".to_string(), json!(999));

        let err = req.validate().unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    use crate::http::mock::{Step, client_with};

    const REFUND_JSON: &str = r#"{
        "refund_id": "ref_1", "payment_id": "pay_1", "amount": 500,
        "currency": "EUR", "status": "succeeded"
    }"#;

    #[tokio::test]
    async fn list_by_profile_posts_to_the_profile_scoped_path() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"size":0,"data":[]}"#),
            Step::ok(r#"{"size":0,"data":[]}"#),
        ]);
        client.refunds().list_by_profile(None).await.unwrap();
        client
            .refunds()
            .list_by_profile(Some(&json!({"limit": 5})))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/refunds/profile/list");
        assert_eq!(
            seen[0].body_json(),
            json!({}),
            "None params must still send an empty JSON object body"
        );
        assert_eq!(seen[1].body_json()["limit"], 5);
    }

    #[tokio::test]
    async fn filters_and_aggregate_endpoints_hit_their_paths_with_queries() {
        let (client, mock) = client_with(vec![Step::ok("{}"), Step::ok("{}"), Step::ok("{}")]);
        client
            .refunds()
            .filters(&[("currency", "EUR".to_string())])
            .await
            .unwrap();
        client
            .refunds()
            .aggregate(&[("start_time", "2024-01-01".to_string())])
            .await
            .unwrap();
        client.refunds().aggregate_by_profile(&[]).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/refunds/filter?currency=EUR")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            (
                "GET",
                "https://api.test/refunds/aggregate?start_time=2024-01-01"
            )
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("GET", "https://api.test/refunds/profile/aggregate")
        );
    }

    #[tokio::test]
    async fn manual_update_puts_to_the_encoded_manual_update_path() {
        // The verb is the point: every other refund mutation is a POST.
        let (client, mock) = client_with(vec![Step::ok(REFUND_JSON)]);
        client
            .refunds()
            .manual_update("ref/1", &json!({"status": "succeeded"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/refunds/ref%2F1/manual-update"
        );
        assert_eq!(seen[0].body_json()["status"], "succeeded");
    }
}