delopay 0.2.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
    }
}

/// 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:?}"),
        }
    }
}