use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::to_json_vec;
use crate::core::error::{DelopayError, Result};
use crate::core::models::external_record::{ExternalRecordCapabilities, ExternalRecordResponse};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct ExternalRecords {
inner: Arc<Inner>,
}
impl ExternalRecords {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(&self, params: &ExternalRecordRequest) -> Result<ExternalRecordResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, "/external-records", Some(&body), None)
.await
}
pub async fn capabilities(&self) -> Result<ExternalRecordCapabilities> {
self.inner
.request(
HttpMethod::Get,
"/external-records/capabilities",
None,
&[],
None,
)
.await
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ExternalRecordResource {
Payment,
Refund,
Dispute,
Payout,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ExternalRecordEnvironment {
Live,
Sandbox,
}
#[derive(Debug, Clone, Serialize)]
pub struct ExternalRecordRequest {
pub resource: ExternalRecordResource,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refund_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub dispute_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payout_id: Option<String>,
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub environment: Option<ExternalRecordEnvironment>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
pub reason: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_reference: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub occurred_at: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ExternalRecordRequest {
fn base(resource: ExternalRecordResource, status: String, reason: String) -> Self {
Self {
resource,
payment_id: None,
refund_id: None,
dispute_id: None,
payout_id: None,
status,
environment: None,
amount: None,
reason,
connector_reference: None,
occurred_at: None,
extra: serde_json::Map::new(),
}
}
pub fn payment(
payment_id: impl Into<String>,
status: impl Into<String>,
environment: ExternalRecordEnvironment,
reason: impl Into<String>,
) -> Self {
Self {
payment_id: Some(payment_id.into()),
environment: Some(environment),
..Self::base(
ExternalRecordResource::Payment,
status.into(),
reason.into(),
)
}
}
pub fn refund(
payment_id: impl Into<String>,
refund_id: impl Into<String>,
status: impl Into<String>,
reason: impl Into<String>,
) -> Self {
Self {
payment_id: Some(payment_id.into()),
refund_id: Some(refund_id.into()),
..Self::base(ExternalRecordResource::Refund, status.into(), reason.into())
}
}
pub fn new_refund(
payment_id: impl Into<String>,
amount: i64,
status: impl Into<String>,
reason: impl Into<String>,
) -> Self {
Self {
payment_id: Some(payment_id.into()),
amount: Some(amount),
..Self::base(ExternalRecordResource::Refund, status.into(), reason.into())
}
}
pub fn dispute(
payment_id: impl Into<String>,
status: impl Into<String>,
reason: impl Into<String>,
) -> Self {
Self {
payment_id: Some(payment_id.into()),
..Self::base(
ExternalRecordResource::Dispute,
status.into(),
reason.into(),
)
}
}
pub fn payout(
payout_id: impl Into<String>,
status: impl Into<String>,
environment: ExternalRecordEnvironment,
reason: impl Into<String>,
) -> Self {
Self {
payout_id: Some(payout_id.into()),
environment: Some(environment),
..Self::base(ExternalRecordResource::Payout, status.into(), reason.into())
}
}
#[must_use]
pub fn dispute_id(mut self, dispute_id: impl Into<String>) -> Self {
self.dispute_id = Some(dispute_id.into());
self
}
#[must_use]
pub fn amount(mut self, amount: i64) -> Self {
self.amount = Some(amount);
self
}
#[must_use]
pub fn connector_reference(mut self, reference: impl Into<String>) -> Self {
self.connector_reference = Some(reference.into());
self
}
#[must_use]
pub fn occurred_at(mut self, occurred_at: impl Into<String>) -> Self {
self.occurred_at = Some(occurred_at.into());
self
}
}
const EXTERNAL_RECORD_REQUEST_NAMED: &[&str] = &[
"resource",
"payment_id",
"refund_id",
"dispute_id",
"payout_id",
"status",
"environment",
"amount",
"reason",
"connector_reference",
"occurred_at",
];
impl ValidateRequest for ExternalRecordRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if EXTERNAL_RECORD_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ExternalRecordRequest"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const RECORD_JSON: &str = r#"{
"record_id": "xr_1", "resource_kind": "refund", "resource_id": "ref_1",
"payment_id": "pay_1", "created_resource": true, "previous_status": null,
"recorded_status": "success", "webhook_outcome": "persisted",
"recorded_by": "user_1", "recorded_at": "2026-01-01T00:00:00Z",
"record_surprise": 1
}"#;
#[tokio::test]
async fn create_posts_the_flat_target_and_reason() {
let (client, mock) = client_with(vec![Step::ok(RECORD_JSON)]);
let req = ExternalRecordRequest::new_refund("pay_1", 500, "success", "refunded by phone")
.connector_reference("re_123")
.occurred_at("2026-01-01T00:00:00Z");
let out = client.external_records().create(&req).await.unwrap();
assert!(out.created_resource);
assert_eq!(out.recorded_status, "success");
assert_eq!(out.extra["record_surprise"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/external-records");
assert_eq!(
seen[0].body_json(),
json!({
"resource": "refund",
"payment_id": "pay_1",
"status": "success",
"amount": 500,
"reason": "refunded by phone",
"connector_reference": "re_123",
"occurred_at": "2026-01-01T00:00:00Z"
})
);
}
#[test]
fn each_constructor_sends_its_kinds_fields() {
let body = |req: ExternalRecordRequest| serde_json::to_value(req).unwrap();
assert_eq!(
body(ExternalRecordRequest::payment(
"pay_1",
"succeeded",
ExternalRecordEnvironment::Sandbox,
"r"
)),
json!({"resource": "payment", "payment_id": "pay_1", "status": "succeeded",
"environment": "sandbox", "reason": "r"})
);
assert_eq!(
body(ExternalRecordRequest::refund(
"pay_1", "ref_1", "failure", "r"
)),
json!({"resource": "refund", "payment_id": "pay_1", "refund_id": "ref_1",
"status": "failure", "reason": "r"})
);
assert_eq!(
body(ExternalRecordRequest::dispute("pay_1", "dispute_lost", "r").dispute_id("dp_1")),
json!({"resource": "dispute", "payment_id": "pay_1", "dispute_id": "dp_1",
"status": "dispute_lost", "reason": "r"})
);
assert_eq!(
body(ExternalRecordRequest::payout(
"po_1",
"success",
ExternalRecordEnvironment::Live,
"r"
)),
json!({"resource": "payout", "payout_id": "po_1", "status": "success",
"environment": "live", "reason": "r"})
);
}
#[tokio::test]
async fn create_is_not_retried_on_5xx() {
let (client, mock) = client_with_retries(
vec![Step::status(500, r#"{"error":{"message":"boom"}}"#)],
2,
);
let req = ExternalRecordRequest::dispute("pay_1", "dispute_won", "r");
client.external_records().create(&req).await.unwrap_err();
assert_eq!(mock.call_count(), 1);
}
#[tokio::test]
async fn capabilities_gets_every_kind() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"kinds":[{"resource":"payout","transition":true,
"create":{"status":"not_implemented","reason":"payout creation is not built"},
"statuses":["success","failed"],"x":1}]}"#,
)]);
let out = client.external_records().capabilities().await.unwrap();
let kind = &out.kinds[0];
assert_eq!(kind.create.status, "not_implemented");
assert_eq!(
kind.create.reason.as_deref(),
Some("payout creation is not built")
);
assert_eq!(kind.statuses, ["success", "failed"]);
assert_eq!(kind.extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/external-records/capabilities"
);
}
#[test]
fn external_record_request_named_fields_are_complete() {
let mut req = ExternalRecordRequest::payment(
"pay_1",
"succeeded",
ExternalRecordEnvironment::Live,
"r",
)
.dispute_id("dp_1")
.amount(1)
.connector_reference("c")
.occurred_at("2026-01-01T00:00:00Z");
req.refund_id = Some("ref_1".to_string());
req.payout_id = Some("po_1".to_string());
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
EXTERNAL_RECORD_REQUEST_NAMED.contains(&key.as_str()),
"EXTERNAL_RECORD_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn create_validate_rejects_colliding_extra_key() {
let mut req = ExternalRecordRequest::dispute("pay_1", "dispute_won", "r");
req.extra.insert("reason".to_string(), json!("other"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("reason")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[tokio::test]
async fn writes_ignore_the_client_wide_idempotency_key() {
let steps = (0..1)
.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
.external_records()
.create(&ExternalRecordRequest::dispute("pay_1", "dispute_won", "r"))
.await
.unwrap_err();
assert_eq!(mock.call_count(), 1);
for seen in mock.seen.lock().unwrap().iter() {
assert!(
!seen.had_idempotency_key(),
"{} sent the client key",
seen.url
);
}
}
#[tokio::test]
async fn writes_are_not_retried_after_a_network_error_with_a_client_key() {
let steps = (0..1)
.map(|_| Step::Fail(crate::http::transport::TransportErrorKind::Connect))
.collect();
let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
let client = client.with_idempotency_key("client-key");
client
.external_records()
.create(&ExternalRecordRequest::dispute("pay_1", "dispute_won", "r"))
.await
.unwrap_err();
assert_eq!(mock.call_count(), 1);
let seen = mock.seen.lock().unwrap();
for request in seen.iter() {
assert!(
!request.had_idempotency_key(),
"{} sent the client key",
request.url
);
}
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
("POST", "https://api.test/external-records")
);
}
}