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::core::models::refund_request::{
BuyerRefundRequest, BuyerRefundRequestList, RefundBulkBlockBuyerResponse,
RefundBulkBlockPreviewResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::buyer_blocklist::BuyerBlocklistKind;
#[derive(Debug, Clone)]
pub struct Refunds {
inner: Arc<Inner>,
}
impl Refunds {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
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
}
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
}
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
}
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
}
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
}
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
}
pub async fn filters(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(HttpMethod::Get, "/refunds/filter", None, query, None)
.await
}
pub async fn aggregate(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(HttpMethod::Get, "/refunds/aggregate", None, query, None)
.await
}
pub async fn aggregate_by_profile(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/refunds/profile/aggregate",
None,
query,
None,
)
.await
}
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
}
pub async fn list_requests(
&self,
params: Option<&BuyerRefundRequestListParams>,
) -> Result<BuyerRefundRequestList> {
let query = params
.map(BuyerRefundRequestListParams::to_query)
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, "/refund-requests", None, &query, None)
.await
}
pub async fn approve_request(
&self,
request_id: &str,
params: &BuyerRefundRequestApprove,
) -> Result<BuyerRefundRequest> {
params.validate()?;
let path = format!("/refund-requests/{}/approve", encode_segment(request_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
.await
}
pub async fn decline_request(
&self,
request_id: &str,
params: &BuyerRefundRequestDecline,
) -> Result<BuyerRefundRequest> {
let path = format!("/refund-requests/{}/decline", encode_segment(request_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
.await
}
pub async fn bulk_block_preview(
&self,
params: &RefundBulkBlockPreviewRequest,
) -> Result<RefundBulkBlockPreviewResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
"/refunds/bulk/block-buyer/preview",
Some(&body),
None,
)
.await
}
pub async fn bulk_block_buyer(
&self,
params: &RefundBulkBlockBuyerRequest,
) -> Result<RefundBulkBlockBuyerResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
"/refunds/bulk/block-buyer",
Some(&body),
None,
)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundCreateRequest {
pub payment_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub refund_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refund_type: Option<RefundType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line_credits: Option<Vec<RefundLineCreditRequest>>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundLineCreditRequest {
pub line_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub quantity: Option<i32>,
pub amount: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_amount: Option<i64>,
}
impl RefundLineCreditRequest {
pub fn new(line_id: impl Into<String>, amount: i64) -> Self {
Self {
line_id: line_id.into(),
amount,
..Default::default()
}
}
#[must_use]
pub fn quantity(mut self, quantity: i32) -> Self {
self.quantity = Some(quantity);
self
}
#[must_use]
pub fn tax_amount(mut self, tax_amount: i64) -> Self {
self.tax_amount = Some(tax_amount);
self
}
}
const REFUND_CREATE_REQUEST_NAMED: &[&str] = &[
"payment_id",
"refund_id",
"amount",
"reason",
"refund_type",
"metadata",
"line_credits",
];
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 {
pub fn new(payment_id: impl Into<String>) -> Self {
Self {
payment_id: payment_id.into(),
..Default::default()
}
}
pub fn amount(mut self, amount: i64) -> Self {
self.amount = Some(amount);
self
}
pub fn reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn refund_type(mut self, refund_type: RefundType) -> Self {
self.refund_type = Some(refund_type);
self
}
#[must_use]
pub fn line_credits(mut self, credits: Vec<RefundLineCreditRequest>) -> Self {
self.line_credits = Some(credits);
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
fn reject_extra_collisions(
extra: &serde_json::Map<String, Value>,
named: &[&str],
type_name: &str,
) -> Result<()> {
for key in extra.keys() {
if named.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on {type_name}"
)));
}
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BuyerRefundRequestStatus {
Requested,
Approved,
Declined,
}
impl BuyerRefundRequestStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Requested => "requested",
Self::Approved => "approved",
Self::Declined => "declined",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct BuyerRefundRequestListParams {
pub payment_id: Option<String>,
pub status: Option<BuyerRefundRequestStatus>,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
impl BuyerRefundRequestListParams {
pub(crate) fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = &self.payment_id {
q.push(("payment_id", v.clone()));
}
if let Some(v) = self.status {
q.push(("status", v.as_str().to_string()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerRefundRequestApprove {
pub refund_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reply: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl BuyerRefundRequestApprove {
pub fn new(refund_id: impl Into<String>) -> Self {
Self {
refund_id: refund_id.into(),
..Default::default()
}
}
#[must_use]
pub fn reply(mut self, reply: impl Into<String>) -> Self {
self.reply = Some(reply.into());
self
}
}
const BUYER_REFUND_REQUEST_APPROVE_NAMED: &[&str] = &["refund_id", "reply"];
impl ValidateRequest for BuyerRefundRequestApprove {
fn validate(&self) -> Result<()> {
reject_extra_collisions(
&self.extra,
BUYER_REFUND_REQUEST_APPROVE_NAMED,
"BuyerRefundRequestApprove",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerRefundRequestDecline {
pub reply: String,
}
impl BuyerRefundRequestDecline {
pub fn new(reply: impl Into<String>) -> Self {
Self {
reply: reply.into(),
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundBulkBlockPreviewRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub ids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub filters: Option<Value>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl RefundBulkBlockPreviewRequest {
pub fn for_ids(ids: Vec<String>) -> Self {
Self {
ids: Some(ids),
..Default::default()
}
}
pub fn for_filters(filters: Value) -> Self {
Self {
filters: Some(filters),
..Default::default()
}
}
}
const REFUND_BULK_BLOCK_PREVIEW_REQUEST_NAMED: &[&str] = &["ids", "filters"];
impl ValidateRequest for RefundBulkBlockPreviewRequest {
fn validate(&self) -> Result<()> {
reject_extra_collisions(
&self.extra,
REFUND_BULK_BLOCK_PREVIEW_REQUEST_NAMED,
"RefundBulkBlockPreviewRequest",
)
}
}
#[derive(Clone, Serialize)]
pub struct RefundBulkExcludedIdentifier {
pub kind: BuyerBlocklistKind,
pub value: String,
}
impl RefundBulkExcludedIdentifier {
pub fn new(kind: BuyerBlocklistKind, value: impl Into<String>) -> Self {
Self {
kind,
value: value.into(),
}
}
}
impl std::fmt::Debug for RefundBulkExcludedIdentifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RefundBulkExcludedIdentifier")
.field("kind", &self.kind)
.field("value", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RefundBulkBlockBuyerRequest {
pub ids: Vec<String>,
pub kinds: Vec<BuyerBlocklistKind>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub exclude: Vec<RefundBulkExcludedIdentifier>,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl RefundBulkBlockBuyerRequest {
pub fn new(ids: Vec<String>, kinds: Vec<BuyerBlocklistKind>) -> Self {
Self {
ids,
kinds,
..Default::default()
}
}
#[must_use]
pub fn exclude(mut self, identifier: RefundBulkExcludedIdentifier) -> Self {
self.exclude.push(identifier);
self
}
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
}
const REFUND_BULK_BLOCK_BUYER_REQUEST_NAMED: &[&str] = &["ids", "kinds", "exclude", "note"];
impl ValidateRequest for RefundBulkBlockBuyerRequest {
fn validate(&self) -> Result<()> {
reject_extra_collisions(
&self.extra,
REFUND_BULK_BLOCK_BUYER_REQUEST_NAMED,
"RefundBulkBlockBuyerRequest",
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
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"})),
line_credits: Some(vec![
RefundLineCreditRequest::new("pli_1", 500)
.quantity(1)
.tax_amount(80),
]),
extra: serde_json::Map::new(),
}
}
#[test]
fn line_credits_serialize_only_the_set_fields() {
let req = RefundCreateRequest::new("pay_1")
.amount(500)
.line_credits(vec![RefundLineCreditRequest::new("pli_1", 500)]);
let value = serde_json::to_value(req).unwrap();
assert_eq!(
value["line_credits"],
json!([{"line_id": "pli_1", "amount": 500}])
);
}
#[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() {
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");
}
const REFUND_REQUEST_JSON: &str = r#"{
"id": "rr_1", "payment_id": "pay_1", "profile_id": "pro_1",
"customer_id": "cus_1", "purchase_kind": "payment", "reason": "not_received",
"message": "It never arrived at my flat", "amount": 1500, "currency": "EUR",
"status": "approved", "refund_id": "ref_1", "approved_amount": 1500,
"merchant_reply": "Sorry", "decided_by": "user_1", "test_mode": false,
"created_at": "2026-01-01T00:00:00Z", "decided_at": "2026-01-02T00:00:00Z",
"rr_surprise": 1
}"#;
#[tokio::test]
async fn list_requests_gets_with_the_filters_and_redacts_the_message() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"data":[{REFUND_REQUEST_JSON}],"total_count":1,"limit":10,"offset":0}}"#
))]);
let params = BuyerRefundRequestListParams {
payment_id: Some("pay_1".to_string()),
status: Some(BuyerRefundRequestStatus::Requested),
limit: Some(10),
offset: Some(0),
};
let page = client.refunds().list_requests(Some(¶ms)).await.unwrap();
assert_eq!(page.total_count, 1);
assert_eq!(page.data[0].amount, 1500);
assert_eq!(page.data[0].extra["rr_surprise"], 1);
assert!(!format!("{page:?}").contains("never arrived"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/refund-requests?payment_id=pay_1&status=requested&limit=10&offset=0"
);
}
#[tokio::test]
async fn approve_request_posts_the_refund_to_the_encoded_path() {
let (client, mock) = client_with(vec![Step::ok(REFUND_REQUEST_JSON)]);
let out = client
.refunds()
.approve_request(
"rr/1",
&BuyerRefundRequestApprove::new("ref_1").reply("Refunded"),
)
.await
.unwrap();
assert_eq!(out.refund_id.as_deref(), Some("ref_1"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/refund-requests/rr%2F1/approve"
);
assert_eq!(
seen[0].body_json(),
json!({"refund_id": "ref_1", "reply": "Refunded"})
);
}
#[tokio::test]
async fn decline_request_posts_the_reply() {
let (client, mock) = client_with(vec![Step::ok(REFUND_REQUEST_JSON)]);
let out = client
.refunds()
.decline_request("rr_1", &BuyerRefundRequestDecline::new("Delivered"))
.await
.unwrap();
assert_eq!(out.id, "rr_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/refund-requests/rr_1/decline");
assert_eq!(seen[0].body_json(), json!({"reply": "Delivered"}));
}
#[tokio::test]
async fn bulk_block_preview_posts_the_filters() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"selected_count":1,"refunds":[{"refund_id":"ref_1","payment_id":"pay_1",
"profile_id":"pro_1","identifiers":[{"kind":"ip","value":"203.0.113.9",
"profile_id":"pro_1","source":"paying_browser","already_blocked":false}],
"omitted_count":0,"error_code":null,"error_message":null}],
"not_found":["ref_2"],"truncated":false,"max_refunds":500,
"max_run_refunds":50,"x":1}"#,
)]);
let req = RefundBulkBlockPreviewRequest::for_filters(json!({"payment_id": "pay_1"}));
let out = client.refunds().bulk_block_preview(&req).await.unwrap();
assert_eq!(out.refunds[0].identifiers[0].source, "paying_browser");
assert_eq!(out.not_found, ["ref_2"]);
assert_eq!(out.extra["x"], 1);
assert!(!format!("{out:?}").contains("203.0.113.9"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/refunds/bulk/block-buyer/preview"
);
assert_eq!(
seen[0].body_json(),
json!({"filters": {"payment_id": "pay_1"}})
);
}
#[tokio::test]
async fn bulk_block_buyer_posts_kinds_and_exclusions() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"results":[{"refund_id":"ref_1","payment_id":"pay_1","outcome":"blocked",
"reason":null,"identifiers":[{"kind":"email","value":"b@example.com",
"state":"added","entry_id":"bbl_1"}],"error_code":null,"error_message":null,"x":1}]}"#,
)]);
let req = RefundBulkBlockBuyerRequest::new(
vec!["ref_1".to_string()],
vec![BuyerBlocklistKind::Email, BuyerBlocklistKind::Ip],
)
.exclude(RefundBulkExcludedIdentifier::new(
BuyerBlocklistKind::Ip,
"203.0.113.9",
))
.note("chargeback abuse");
assert!(!format!("{req:?}").contains("203.0.113.9"));
let out = client.refunds().bulk_block_buyer(&req).await.unwrap();
assert_eq!(
out.results[0].identifiers[0].entry_id.as_deref(),
Some("bbl_1")
);
assert_eq!(out.results[0].extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/refunds/bulk/block-buyer");
assert_eq!(
seen[0].body_json(),
json!({
"ids": ["ref_1"],
"kinds": ["email", "ip"],
"exclude": [{"kind": "ip", "value": "203.0.113.9"}],
"note": "chargeback abuse"
})
);
}
#[tokio::test]
async fn bulk_block_buyer_is_not_retried_on_5xx() {
let (client, mock) = crate::http::mock::client_with_retries(
vec![Step::status(500, r#"{"error":{"message":"boom"}}"#)],
2,
);
let req = RefundBulkBlockBuyerRequest::new(
vec!["ref_1".to_string()],
vec![BuyerBlocklistKind::Email],
);
client.refunds().bulk_block_buyer(&req).await.unwrap_err();
assert_eq!(mock.call_count(), 1);
}
#[test]
fn buyer_refund_request_approve_named_fields_are_complete() {
let req = BuyerRefundRequestApprove::new("ref_1").reply("r");
assert_named_complete(&req, BUYER_REFUND_REQUEST_APPROVE_NAMED);
}
#[test]
fn refund_bulk_block_preview_request_named_fields_are_complete() {
let mut req = RefundBulkBlockPreviewRequest::for_ids(vec!["ref_1".to_string()]);
req.filters = Some(json!({}));
assert_named_complete(&req, REFUND_BULK_BLOCK_PREVIEW_REQUEST_NAMED);
}
#[test]
fn refund_bulk_block_buyer_request_named_fields_are_complete() {
let req = RefundBulkBlockBuyerRequest::new(vec![], vec![BuyerBlocklistKind::Email])
.exclude(RefundBulkExcludedIdentifier::new(
BuyerBlocklistKind::Email,
"e",
))
.note("n");
assert_named_complete(&req, REFUND_BULK_BLOCK_BUYER_REQUEST_NAMED);
}
#[test]
fn bulk_block_buyer_validate_rejects_colliding_extra_key() {
let mut req = RefundBulkBlockBuyerRequest::new(vec![], vec![]);
req.extra.insert("kinds".to_string(), json!([]));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("kinds")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
fn assert_named_complete<T: Serialize>(req: &T, named: &[&str]) {
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
named.contains(&key.as_str()),
"NAMED is missing wire key `{key}`"
);
}
}
#[tokio::test]
async fn writes_ignore_the_client_wide_idempotency_key() {
let steps = (0..4)
.map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
.collect();
let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
let client = client.with_idempotency_key("client-key");
client
.refunds()
.approve_request("rr_1", &BuyerRefundRequestApprove::new("ref_1"))
.await
.unwrap_err();
client
.refunds()
.decline_request("rr_1", &BuyerRefundRequestDecline::new("no"))
.await
.unwrap_err();
client
.refunds()
.bulk_block_preview(&RefundBulkBlockPreviewRequest::for_ids(vec![
"ref_1".to_string(),
]))
.await
.unwrap_err();
client
.refunds()
.bulk_block_buyer(&RefundBulkBlockBuyerRequest::new(
vec!["ref_1".to_string()],
vec![BuyerBlocklistKind::Email],
))
.await
.unwrap_err();
assert_eq!(mock.call_count(), 4);
for seen in mock.seen.lock().unwrap().iter() {
assert!(
!seen.had_idempotency_key(),
"{} sent the client key",
seen.url
);
}
}
}