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::export::{
DisputeExportRecord, ExportEnvelope, MerchantAuditLogExportRecord, PayoutExportRecord,
RefundExportRecord, SubscriptionExportRecord, TransactionExportRecord,
TransactionLineExportRecord,
};
use crate::http::client::{Inner, KeyPolicy};
use crate::http::transport::HttpMethod;
use crate::resources::audit::MerchantAuditLogListParams;
use crate::resources::disputes::DisputeListParams;
use crate::resources::subscriptions::SubscriptionListParams;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ExportFormat {
#[default]
Json,
Csv,
Pdf,
}
impl ExportFormat {
pub fn accept(self) -> &'static str {
match self {
Self::Json => "application/json",
Self::Csv => "text/csv",
Self::Pdf => "application/pdf",
}
}
}
#[derive(Debug, Clone)]
pub struct Export {
inner: Arc<Inner>,
presentation: Option<String>,
}
pub const MAX_EXPORT_PRESENTATION_BYTES: usize = 6 * 1024;
const PRESENTATION_HEADER: &str = "x-delopay-export-presentation";
impl Export {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self {
inner,
presentation: None,
}
}
pub fn with_presentation(&self, presentation: &Value) -> Result<Self> {
let json = to_json_vec(presentation)?;
let encoded = base64url_unpadded(&json);
if encoded.len() > MAX_EXPORT_PRESENTATION_BYTES {
return Err(DelopayError::InvalidRequest(format!(
"the export presentation is {} bytes encoded; the API reads at most \
{MAX_EXPORT_PRESENTATION_BYTES}",
encoded.len()
)));
}
Ok(Self {
inner: self.inner.clone(),
presentation: Some(encoded),
})
}
fn file_headers(&self, format: ExportFormat) -> Vec<(&'static str, &str)> {
let mut headers = vec![("accept", format.accept())];
if format == ExportFormat::Pdf
&& let Some(presentation) = &self.presentation
{
headers.push((PRESENTATION_HEADER, presentation.as_str()));
}
headers
}
pub async fn transactions(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<TransactionExportRecord>> {
self.post_json("/export/transactions", &filters_or_empty(filters))
.await
}
pub async fn transactions_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
self.post_file("/export/transactions", &filters_or_empty(filters), format)
.await
}
pub async fn transactions_for_profile(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<TransactionExportRecord>> {
self.post_json("/export/profile/transactions", &filters_or_empty(filters))
.await
}
pub async fn transactions_for_profile_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
self.post_file(
"/export/profile/transactions",
&filters_or_empty(filters),
format,
)
.await
}
pub async fn transaction_lines(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<TransactionLineExportRecord>> {
self.post_json_unkeyed("/export/transactions/lines", &filters_or_empty(filters))
.await
}
pub async fn transaction_lines_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
refuse_pdf(format)?;
self.post_file_unkeyed(
"/export/transactions/lines",
&filters_or_empty(filters),
format,
)
.await
}
pub async fn transaction_lines_for_profile(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<TransactionLineExportRecord>> {
self.post_json_unkeyed(
"/export/profile/transactions/lines",
&filters_or_empty(filters),
)
.await
}
pub async fn transaction_lines_for_profile_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
refuse_pdf(format)?;
self.post_file_unkeyed(
"/export/profile/transactions/lines",
&filters_or_empty(filters),
format,
)
.await
}
pub async fn refunds(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<RefundExportRecord>> {
self.post_json("/refunds/list/export", &filters_or_empty(filters))
.await
}
pub async fn refunds_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
self.post_file("/refunds/list/export", &filters_or_empty(filters), format)
.await
}
pub async fn refunds_for_profile(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<RefundExportRecord>> {
self.post_json("/refunds/profile/list/export", &filters_or_empty(filters))
.await
}
pub async fn refunds_for_profile_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
self.post_file(
"/refunds/profile/list/export",
&filters_or_empty(filters),
format,
)
.await
}
pub async fn payouts(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<PayoutExportRecord>> {
self.post_json("/payouts/list/export", &filters_or_empty(filters))
.await
}
pub async fn payouts_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
self.post_file("/payouts/list/export", &filters_or_empty(filters), format)
.await
}
pub async fn payouts_for_profile(
&self,
filters: Option<&Value>,
) -> Result<ExportEnvelope<PayoutExportRecord>> {
self.post_json("/payouts/profile/list/export", &filters_or_empty(filters))
.await
}
pub async fn payouts_for_profile_file(
&self,
filters: Option<&Value>,
format: ExportFormat,
) -> Result<Vec<u8>> {
self.post_file(
"/payouts/profile/list/export",
&filters_or_empty(filters),
format,
)
.await
}
pub async fn disputes(
&self,
params: Option<&DisputeListParams>,
) -> Result<ExportEnvelope<DisputeExportRecord>> {
let query = params.map(DisputeListParams::to_query).unwrap_or_default();
self.get_json("/disputes/list/export", &query).await
}
pub async fn disputes_file(
&self,
params: Option<&DisputeListParams>,
format: ExportFormat,
) -> Result<Vec<u8>> {
let query = params.map(DisputeListParams::to_query).unwrap_or_default();
self.get_file("/disputes/list/export", &query, format).await
}
pub async fn disputes_for_profile(
&self,
params: Option<&DisputeListParams>,
) -> Result<ExportEnvelope<DisputeExportRecord>> {
let query = params.map(DisputeListParams::to_query).unwrap_or_default();
self.get_json("/disputes/profile/list/export", &query).await
}
pub async fn disputes_for_profile_file(
&self,
params: Option<&DisputeListParams>,
format: ExportFormat,
) -> Result<Vec<u8>> {
let query = params.map(DisputeListParams::to_query).unwrap_or_default();
self.get_file("/disputes/profile/list/export", &query, format)
.await
}
pub async fn subscriptions(
&self,
profile_id: &str,
params: Option<&SubscriptionListParams>,
) -> Result<ExportEnvelope<SubscriptionExportRecord>> {
let query = params
.map(SubscriptionListParams::to_query)
.unwrap_or_default();
self.inner
.request_with_headers(
HttpMethod::Get,
"/subscriptions/list/export",
None,
&query,
None,
&[
("x-profile-id", profile_id),
("accept", ExportFormat::Json.accept()),
],
)
.await
}
pub async fn subscriptions_file(
&self,
profile_id: &str,
params: Option<&SubscriptionListParams>,
format: ExportFormat,
) -> Result<Vec<u8>> {
let query = params
.map(SubscriptionListParams::to_query)
.unwrap_or_default();
let mut headers = self.file_headers(format);
headers.push(("x-profile-id", profile_id));
self.inner
.send_raw(
HttpMethod::Get,
"/subscriptions/list/export",
None,
&query,
None,
&headers,
None,
)
.await
}
pub async fn audit_log(
&self,
params: Option<&MerchantAuditLogListParams>,
) -> Result<ExportEnvelope<MerchantAuditLogExportRecord>> {
let query = params
.map(MerchantAuditLogListParams::to_query)
.unwrap_or_default();
self.get_json("/audit/export", &query).await
}
pub async fn audit_log_file(
&self,
params: Option<&MerchantAuditLogListParams>,
format: ExportFormat,
) -> Result<Vec<u8>> {
let query = params
.map(MerchantAuditLogListParams::to_query)
.unwrap_or_default();
self.get_file("/audit/export", &query, format).await
}
async fn post_json<B: Serialize, T: serde::de::DeserializeOwned>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let bytes = to_json_vec(body)?;
self.inner
.request_with_headers(
HttpMethod::Post,
path,
Some(&bytes),
&[],
None,
&[("accept", ExportFormat::Json.accept())],
)
.await
}
async fn post_file<B: Serialize>(
&self,
path: &str,
body: &B,
format: ExportFormat,
) -> Result<Vec<u8>> {
let bytes = to_json_vec(body)?;
self.inner
.send_raw(
HttpMethod::Post,
path,
Some(&bytes),
&[],
None,
&self.file_headers(format),
None,
)
.await
}
async fn post_json_unkeyed<B: Serialize, T: serde::de::DeserializeOwned>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let bytes = to_json_vec(body)?;
self.inner
.request_body_keyed_with_query_and_headers(
HttpMethod::Post,
path,
Some(&bytes),
&[],
&[("accept", ExportFormat::Json.accept())],
None,
)
.await
}
async fn post_file_unkeyed<B: Serialize>(
&self,
path: &str,
body: &B,
format: ExportFormat,
) -> Result<Vec<u8>> {
let bytes = to_json_vec(body)?;
self.inner
.send_raw_keyed(
HttpMethod::Post,
path,
Some(&bytes),
&[],
None,
KeyPolicy::BodyKeyOnly,
&self.file_headers(format),
None,
)
.await
}
async fn get_json<T: serde::de::DeserializeOwned>(
&self,
path: &str,
query: &[(&str, String)],
) -> Result<T> {
self.inner
.request_with_headers(
HttpMethod::Get,
path,
None,
query,
None,
&[("accept", ExportFormat::Json.accept())],
)
.await
}
async fn get_file(
&self,
path: &str,
query: &[(&str, String)],
format: ExportFormat,
) -> Result<Vec<u8>> {
self.inner
.send_raw(
HttpMethod::Get,
path,
None,
query,
None,
&self.file_headers(format),
None,
)
.await
}
}
fn base64url_unpadded(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b = [
chunk[0],
chunk.get(1).copied().unwrap_or(0),
chunk.get(2).copied().unwrap_or(0),
];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
let chars = chunk.len() + 1;
for i in 0..chars {
let index = (n >> (18 - 6 * i)) & 0x3f;
out.push(char::from(ALPHABET[index as usize]));
}
}
out
}
fn refuse_pdf(format: ExportFormat) -> Result<()> {
if format == ExportFormat::Pdf {
return Err(DelopayError::InvalidRequest(
"a transaction line export is CSV or JSON only; it has no PDF form".to_owned(),
));
}
Ok(())
}
fn filters_or_empty(filters: Option<&Value>) -> Value {
filters
.cloned()
.unwrap_or_else(|| Value::Object(Default::default()))
}
#[cfg(test)]
mod tests {
use super::{
DelopayError, ExportFormat, MAX_EXPORT_PRESENTATION_BYTES, SubscriptionListParams,
base64url_unpadded,
};
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
#[test]
fn base64url_unpadded_matches_the_rfc_vectors() {
assert_eq!(base64url_unpadded(b""), "");
assert_eq!(base64url_unpadded(b"f"), "Zg");
assert_eq!(base64url_unpadded(b"fo"), "Zm8");
assert_eq!(base64url_unpadded(b"foo"), "Zm9v");
assert_eq!(base64url_unpadded(b"foobar"), "Zm9vYmFy");
assert_eq!(base64url_unpadded(&[0xfb, 0xff]), "-_8");
}
#[tokio::test]
async fn the_presentation_header_is_sent_with_pdf_files_only() {
let (client, mock) =
client_with(vec![Step::ok("%PDF"), Step::ok("a,b\n"), Step::ok("%PDF")]);
let presentation = json!({"title": "Ä", "filters_heading": "Filter", "filters": [],
"no_filters": "-", "no_rows": "-", "row_count": "{count}", "page": "{page}"});
let export = client.export().with_presentation(&presentation).unwrap();
export
.transactions_file(None, ExportFormat::Pdf)
.await
.unwrap();
export
.transactions_file(None, ExportFormat::Csv)
.await
.unwrap();
export.disputes_file(None, ExportFormat::Pdf).await.unwrap();
let seen = mock.seen.lock().unwrap();
let expected = base64url_unpadded(&serde_json::to_vec(&presentation).unwrap());
assert_eq!(
seen[0].header("x-delopay-export-presentation"),
Some(expected.as_str())
);
assert_eq!(seen[0].header("accept"), Some("application/pdf"));
assert_eq!(seen[1].header("x-delopay-export-presentation"), None);
assert_eq!(seen[2].method, "GET");
assert_eq!(
seen[2].header("x-delopay-export-presentation"),
Some(expected.as_str())
);
assert_eq!(seen[2].header("accept"), Some("application/pdf"));
}
#[tokio::test]
async fn an_oversized_presentation_is_refused_before_sending() {
let (client, _mock) = client_with(vec![]);
let huge = json!({"title": "x".repeat(MAX_EXPORT_PRESENTATION_BYTES)});
assert!(matches!(
client.export().with_presentation(&huge),
Err(DelopayError::InvalidRequest(_))
));
}
const LINE_ROWS_JSON: &str = r#"{
"records": [
{
"payment_id": "pay_1", "merchant_id": "mer_1", "shop_id": "pro_1",
"created_at": "2026-09-01T00:00:00Z", "status": "succeeded", "test_mode": false,
"payment_amount": 1500, "payment_currency": "EUR", "row_kind": "line",
"line_id": "pli_1", "position": 0, "parent_line_id": null, "line_role": "product",
"product_id": "prod_1", "product_name": "Hat", "product_alias": null,
"attributed": true, "quantity": 2, "unit_amount": 750, "line_total": 1500,
"currency": "EUR", "tax_rate": 19.0, "tax_amount": null, "surprise_field": 1
},
{
"payment_id": "pay_2", "merchant_id": "mer_1", "shop_id": "pro_1",
"created_at": null, "status": "failed", "test_mode": null,
"payment_amount": 900, "payment_currency": "EUR", "row_kind": "no_lines",
"line_id": null, "position": null, "parent_line_id": null, "line_role": null,
"product_id": null, "product_name": null, "product_alias": null,
"attributed": false, "quantity": null, "unit_amount": null, "line_total": null,
"currency": null, "tax_rate": null, "tax_amount": null
}
],
"record_count": 2,
"filters": {}
}"#;
#[tokio::test]
async fn transaction_lines_posts_the_list_filters_and_asks_for_json() {
let (client, mock) = client_with(vec![Step::ok(LINE_ROWS_JSON)]);
let filters = json!({"currency": ["EUR"], "limit": 100});
let out = client
.export()
.transaction_lines(Some(&filters))
.await
.unwrap();
assert_eq!(out.record_count, Some(2));
let line = &out.records[0];
assert_eq!(line.row_kind, "line");
assert_eq!(line.quantity, Some(2));
assert_eq!(line.tax_rate, Some(19.0));
assert!(line.tax_amount.is_none());
assert_eq!(line.extra["surprise_field"], 1);
let no_lines = &out.records[1];
assert_eq!(no_lines.row_kind, "no_lines");
assert!(!no_lines.attributed);
assert!(no_lines.test_mode.is_none());
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/export/transactions/lines");
assert_eq!(seen[0].body_json(), filters);
assert_eq!(seen[0].header("accept"), Some("application/json"));
}
#[tokio::test]
async fn transaction_lines_for_profile_file_asks_for_csv_on_the_profile_path() {
let (client, mock) = client_with(vec![Step::ok(
"payment_id,row_kind
pay_1,line
",
)]);
let out = client
.export()
.transaction_lines_for_profile_file(None, ExportFormat::Csv)
.await
.unwrap();
assert_eq!(
out,
b"payment_id,row_kind
pay_1,line
"
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/export/profile/transactions/lines"
);
assert_eq!(seen[0].body_json(), json!({}));
assert_eq!(seen[0].header("accept"), Some("text/csv"));
}
#[tokio::test]
async fn transaction_lines_for_profile_posts_to_the_profile_path() {
let (client, mock) = client_with(vec![Step::ok(LINE_ROWS_JSON)]);
client
.export()
.transaction_lines_for_profile(None)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/export/profile/transactions/lines"
);
assert_eq!(seen[0].header("accept"), Some("application/json"));
}
#[tokio::test]
async fn transaction_lines_file_posts_csv_and_refuses_pdf_before_sending() {
let (client, mock) = client_with(vec![Step::ok(
"payment_id
pay_1
",
)]);
let export = client.export();
let csv = export
.transaction_lines_file(None, ExportFormat::Csv)
.await
.unwrap();
assert_eq!(
csv,
b"payment_id
pay_1
"
);
assert!(matches!(
export.transaction_lines_file(None, ExportFormat::Pdf).await,
Err(DelopayError::InvalidRequest(_))
));
assert!(matches!(
export
.transaction_lines_for_profile_file(None, ExportFormat::Pdf)
.await,
Err(DelopayError::InvalidRequest(_))
));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].url, "https://api.test/export/transactions/lines");
assert_eq!(seen[0].header("accept"), Some("text/csv"));
}
#[tokio::test]
async fn transactions_posts_the_list_filter_and_asks_for_json() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"records":[{"payment_id":"pay_1","amount":500,"test_mode":false,"connector_settlement_status":"paid_out"}],"record_count":1,"filters":{}}"#,
)]);
let filters = json!({"profile_id": ["pro_1"], "start_time": "2026-09-01T00:00:00Z"});
let out = client.export().transactions(Some(&filters)).await.unwrap();
assert_eq!(out.record_count, Some(1));
assert_eq!(out.records[0].payment_id, "pay_1");
assert_eq!(out.records[0].test_mode, Some(false));
assert_eq!(
out.records[0].connector_settlement_status.as_deref(),
Some("paid_out")
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/export/transactions");
assert_eq!(seen[0].body_json(), filters);
assert_eq!(seen[0].header("accept"), Some("application/json"));
}
#[tokio::test]
async fn transactions_file_asks_for_csv_and_returns_bytes() {
let (client, mock) = client_with(vec![
Step::ok("payment_id,amount\npay_1,500\n"),
Step::ok("payment_id\n"),
]);
let export = client.export();
let out = export
.transactions_file(None, ExportFormat::Csv)
.await
.unwrap();
assert_eq!(out, b"payment_id,amount\npay_1,500\n");
export
.transactions_for_profile_file(None, ExportFormat::Pdf)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("accept"), Some("text/csv"));
assert_eq!(seen[0].body_json(), json!({}));
assert_eq!(seen[1].url, "https://api.test/export/profile/transactions");
assert_eq!(seen[1].header("accept"), Some("application/pdf"));
assert_eq!(seen[1].body_json(), json!({}));
}
#[tokio::test]
async fn subscriptions_export_scopes_by_profile_header() {
let (client, mock) = client_with(vec![Step::ok(r#"{"records":[],"record_count":0}"#)]);
client
.export()
.subscriptions(
"pro_1",
Some(&SubscriptionListParams {
limit: Some(50),
offset: Some(100),
test_mode: Some(true),
}),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/list/export?limit=50&offset=100&test_mode=true"
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn line_exports_ignore_the_client_wide_idempotency_key() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, "{}"),
Step::status(503, "{}"),
Step::ok("{}"),
],
2,
);
let export = client.with_idempotency_key("client-key").export();
assert!(export.transaction_lines(None).await.is_err());
assert!(
export
.transaction_lines_for_profile_file(None, ExportFormat::Csv)
.await
.is_err()
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert!(seen.iter().all(|step| !step.had_idempotency_key()));
assert_eq!(seen[1].header("accept"), Some("text/csv"));
}
}