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::buyer_portal::{
BuyerInvoiceLink, BuyerPortalLinkPage, BuyerPortalLinkRestrictions,
};
use crate::core::models::common::ListResponse;
use crate::core::models::customer::{
CustomerResponse, CustomerShopBulkPlacementResponse, CustomerShopPlacementResponse,
};
use crate::core::models::customer_identity::{
CustomerIdentityHistoryResponse, CustomerIdentityImportPreviewResponse,
CustomerIdentityImportResponse,
};
use crate::core::models::mandate::MandateResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Customers {
inner: Arc<Inner>,
profile_id: Option<String>,
}
impl Customers {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self {
inner,
profile_id: None,
}
}
#[must_use]
pub fn with_profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
fn profile_headers(&self) -> Vec<(&str, &str)> {
match &self.profile_id {
Some(id) => vec![("x-profile-id", id.as_str())],
None => Vec::new(),
}
}
pub async fn create(&self, params: &CustomerCreateRequest) -> Result<CustomerResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, "/customers", Some(&body), &[], None)
.await
}
pub async fn retrieve(&self, customer_id: &str) -> Result<CustomerResponse> {
let path = format!("/customers/{}", encode_segment(customer_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn update(
&self,
customer_id: &str,
params: &CustomerCreateRequest,
) -> Result<CustomerResponse> {
params.validate()?;
let path = format!("/customers/{}", encode_segment(customer_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn delete(&self, customer_id: &str) -> Result<CustomerResponse> {
let path = format!("/customers/{}", encode_segment(customer_id));
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn list(&self, params: Option<&CustomerListParams>) -> Result<Vec<CustomerResponse>> {
let query = params.map(CustomerListParams::to_query).unwrap_or_default();
self.inner
.request(HttpMethod::Get, "/customers/list", None, &query, None)
.await
}
pub async fn list_with_count(
&self,
params: Option<&CustomerListParams>,
) -> Result<ListResponse<CustomerResponse>> {
let query = params.map(CustomerListParams::to_query).unwrap_or_default();
self.inner
.request(
HttpMethod::Get,
"/customers/list-with-count",
None,
&query,
None,
)
.await
}
pub async fn list_by_profile(
&self,
params: Option<&CustomerListParams>,
) -> Result<Vec<CustomerResponse>> {
let query = params.map(CustomerListParams::to_query).unwrap_or_default();
self.inner
.request_with_headers(
HttpMethod::Get,
"/customers/profile/list",
None,
&query,
None,
&self.profile_headers(),
)
.await
}
pub async fn list_by_profile_with_count(
&self,
params: Option<&CustomerListParams>,
) -> Result<ListResponse<CustomerResponse>> {
let query = params.map(CustomerListParams::to_query).unwrap_or_default();
self.inner
.request_with_headers(
HttpMethod::Get,
"/customers/profile/list-with-count",
None,
&query,
None,
&self.profile_headers(),
)
.await
}
pub async fn retrieve_by_profile(&self, customer_id: &str) -> Result<CustomerResponse> {
let path = format!("/customers/profile/{}", encode_segment(customer_id));
self.inner
.request_with_headers(
HttpMethod::Get,
&path,
None,
&[],
None,
&self.profile_headers(),
)
.await
}
pub async fn create_by_profile(
&self,
params: &CustomerCreateRequest,
) -> Result<CustomerResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query_and_headers(
HttpMethod::Post,
"/customers/profile",
Some(&body),
&[],
&self.profile_headers(),
None,
)
.await
}
pub async fn update_by_profile(
&self,
customer_id: &str,
params: &CustomerCreateRequest,
) -> Result<CustomerResponse> {
params.validate()?;
let path = format!("/customers/profile/{}", encode_segment(customer_id));
let body = to_json_vec(params)?;
self.inner
.request_with_headers(
HttpMethod::Post,
&path,
Some(&body),
&[],
None,
&self.profile_headers(),
)
.await
}
pub async fn list_mandates_by_profile(
&self,
customer_id: &str,
) -> Result<Vec<MandateResponse>> {
let path = format!(
"/customers/profile/{}/mandates",
encode_segment(customer_id)
);
self.inner
.request_with_headers(
HttpMethod::Get,
&path,
None,
&[],
None,
&self.profile_headers(),
)
.await
}
pub async fn place_in_shop(
&self,
customer_id: &str,
profile_id: &str,
) -> Result<CustomerShopPlacementResponse> {
let path = format!("/customers/{}/shops", encode_segment(customer_id));
let body = to_json_vec(&serde_json::json!({ "profile_id": profile_id }))?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn place_many_in_shop(
&self,
profile_id: &str,
customer_ids: &[&str],
) -> Result<CustomerShopBulkPlacementResponse> {
let body = to_json_vec(&serde_json::json!({
"profile_id": profile_id,
"customer_ids": customer_ids,
}))?;
self.inner
.request(
HttpMethod::Post,
"/customers/shops/place",
Some(&body),
&[],
None,
)
.await
}
pub async fn list_mandates(&self, customer_id: &str) -> Result<Vec<MandateResponse>> {
let path = format!("/customers/{}/mandates", encode_segment(customer_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn preview_identity_import(
&self,
params: &CustomerIdentityImportPreviewRequest,
) -> Result<CustomerIdentityImportPreviewResponse> {
check_rows(¶ms.rows)?;
let body = to_json_vec(params)?;
check_body(&body, MAX_IDENTITY_IMPORT_REQUEST_BYTES)?;
self.inner
.request(
HttpMethod::Post,
"/customers/identity-history/import/preview",
Some(&body),
&[],
None,
)
.await
}
pub async fn import_identity_history(
&self,
params: &CustomerIdentityImportRequest,
) -> Result<CustomerIdentityImportResponse> {
check_rows(¶ms.rows)?;
let key = require_import_key(¶ms.idempotency_key)?;
let body = to_json_vec(params)?;
check_body(&body, MAX_IDENTITY_IMPORT_REQUEST_BYTES)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
"/customers/identity-history/import",
Some(&body),
Some(key),
)
.await
}
pub async fn retrieve_identity_import(
&self,
run_id: &str,
) -> Result<CustomerIdentityImportResponse> {
let path = format!(
"/customers/identity-history/import/{}",
encode_segment(run_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn list_identity_history(
&self,
params: &CustomerIdentityHistoryRequest,
) -> Result<CustomerIdentityHistoryResponse> {
if params.customer_ids.is_empty() || params.customer_ids.len() > MAX_IDENTITY_CUSTOMERS {
return Err(DelopayError::InvalidRequest(format!(
"`customer_ids` must hold 1 to {MAX_IDENTITY_CUSTOMERS} ids"
)));
}
let body = to_json_vec(params)?;
check_body(&body, MAX_IDENTITY_HISTORY_REQUEST_BYTES)?;
self.inner
.request(
HttpMethod::Post,
"/customers/identity-history/list",
Some(&body),
&[],
None,
)
.await
}
pub async fn search_identity_history(
&self,
params: &CustomerIdentityHistorySearchRequest,
) -> Result<CustomerIdentityHistoryResponse> {
if let Some(limit) = params.limit
&& !(1..=MAX_IDENTITY_SEARCH_RESULTS).contains(&limit)
{
return Err(DelopayError::InvalidRequest(format!(
"`limit` must be 1 to {MAX_IDENTITY_SEARCH_RESULTS}"
)));
}
if params.query.chars().count() > MAX_IDENTITY_SEARCH_QUERY_CHARS {
return Err(DelopayError::InvalidRequest(format!(
"`query` must hold at most {MAX_IDENTITY_SEARCH_QUERY_CHARS} characters"
)));
}
if params.cursor.is_some() && !params.group_by_customer {
return Err(DelopayError::InvalidRequest(
"`cursor` pages a search by customer; set `group_by_customer`".to_owned(),
));
}
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/customers/identity-history/search",
Some(&body),
&[],
None,
)
.await
}
}
impl Customers {
pub async fn create_portal_link(
&self,
customer_id: &str,
params: &BuyerInvoiceLinkRequest,
) -> Result<BuyerInvoiceLink> {
params.validate()?;
let path = portal_links_path(customer_id);
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
.await
}
pub async fn list_portal_links(
&self,
customer_id: &str,
params: Option<&BuyerPortalLinkListParams>,
) -> Result<BuyerPortalLinkPage> {
let path = portal_links_path(customer_id);
let query = params
.map(BuyerPortalLinkListParams::to_query)
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn revoke_portal_link(&self, customer_id: &str, link_id: &str) -> Result<()> {
let path = format!(
"{}/{}",
portal_links_path(customer_id),
encode_segment(link_id)
);
self.inner
.request_body_keyed::<serde::de::IgnoredAny>(HttpMethod::Delete, &path, None, None)
.await
.map(|_| ())
}
}
fn portal_links_path(customer_id: &str) -> String {
format!("/customers/{}/portal-links", encode_segment(customer_id))
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerInvoiceLinkRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_subscription_changes: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub restrictions: Option<BuyerPortalLinkRestrictions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_in_seconds: Option<u32>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl BuyerInvoiceLinkRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn allow_subscription_changes(mut self, allow: bool) -> Self {
self.allow_subscription_changes = Some(allow);
self
}
#[must_use]
pub fn restrictions(mut self, restrictions: BuyerPortalLinkRestrictions) -> Self {
self.restrictions = Some(restrictions);
self
}
#[must_use]
pub fn expires_in_seconds(mut self, seconds: u32) -> Self {
self.expires_in_seconds = Some(seconds);
self
}
}
const BUYER_INVOICE_LINK_REQUEST_NAMED: &[&str] = &[
"profile_id",
"allow_subscription_changes",
"restrictions",
"expires_in_seconds",
];
const BUYER_PORTAL_LINK_RESTRICTIONS_NAMED: &[&str] = &[
"subscription_changes",
"subscription_actions",
"profile_changes",
"email_policy",
"refund_requests",
"refund_requests_for_renewals",
];
const BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED: &[&str] = &[
"pause",
"resume",
"cancel_at_period_end",
"cancel_immediately",
"change_plan",
];
fn reject_colliding_extra(
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(())
}
impl ValidateRequest for BuyerInvoiceLinkRequest {
fn validate(&self) -> Result<()> {
reject_colliding_extra(
&self.extra,
BUYER_INVOICE_LINK_REQUEST_NAMED,
"BuyerInvoiceLinkRequest",
)?;
if let Some(restrictions) = &self.restrictions {
reject_colliding_extra(
&restrictions.extra,
BUYER_PORTAL_LINK_RESTRICTIONS_NAMED,
"BuyerPortalLinkRestrictions",
)?;
if let Some(actions) = &restrictions.subscription_actions {
reject_colliding_extra(
&actions.extra,
BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED,
"BuyerPortalSubscriptionPermissions",
)?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct BuyerPortalLinkListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl BuyerPortalLinkListParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
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
}
}
pub const MAX_IDENTITY_IMPORT_ROWS: usize = 1000;
pub const MAX_IDENTITY_CUSTOMERS: usize = 1000;
pub const MAX_IDENTITY_SEARCH_RESULTS: u32 = 100;
pub const MAX_IDENTITY_SEARCH_QUERY_CHARS: usize = 256;
pub const MAX_IDENTITY_IMPORT_REQUEST_BYTES: usize = 1000 * 7 * 1024 + 16 * 1024;
pub const MAX_IDENTITY_HISTORY_REQUEST_BYTES: usize = 128 * 1024;
const MAX_IDEMPOTENCY_KEY_CHARS: usize = 255;
fn check_rows(rows: &[CustomerIdentityImportRow]) -> Result<()> {
if rows.is_empty() || rows.len() > MAX_IDENTITY_IMPORT_ROWS {
return Err(DelopayError::InvalidRequest(format!(
"`rows` must hold 1 to {MAX_IDENTITY_IMPORT_ROWS} rows"
)));
}
for (index, row) in rows.iter().enumerate() {
for (name, value) in [
("first_seen_at", &row.first_seen_at),
("last_seen_at", &row.last_seen_at),
] {
if value
.as_deref()
.is_some_and(|value| !names_its_offset(value))
{
return Err(DelopayError::InvalidRequest(format!(
"`rows[{index}].{name}` must be an ISO 8601 date and time with its UTC \
offset, such as `2026-10-31T12:00:00Z`"
)));
}
}
}
Ok(())
}
fn names_its_offset(value: &str) -> bool {
let Some((_, time)) = value.split_once(['T', 't']) else {
return false;
};
if time.ends_with(['Z', 'z']) {
return true;
}
time.rfind(['+', '-']).is_some_and(|at| {
at > 0
&& time.get(at + 1..).is_some_and(|offset| {
!offset.is_empty() && offset.chars().all(|c| c.is_ascii_digit() || c == ':')
})
})
}
fn check_body(body: &[u8], limit: usize) -> Result<()> {
if body.len() > limit {
return Err(DelopayError::InvalidRequest(format!(
"the request body is {} bytes, over the {limit} bytes the API accepts",
body.len()
)));
}
Ok(())
}
fn require_import_key(key: &str) -> Result<&str> {
if key.trim().is_empty()
|| key.chars().count() > MAX_IDEMPOTENCY_KEY_CHARS
|| key.chars().any(char::is_control)
{
return Err(DelopayError::InvalidRequest(format!(
"`idempotency_key` must hold 1 to {MAX_IDEMPOTENCY_KEY_CHARS} printable characters"
)));
}
Ok(key)
}
#[derive(Clone, Serialize)]
pub struct CustomerIdentityImportRow {
pub customer_id: String,
pub kind: String,
pub value: String,
pub external_ref: String,
pub source_label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub first_seen_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_seen_at: Option<String>,
}
impl std::fmt::Debug for CustomerIdentityImportRow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomerIdentityImportRow")
.field("customer_id", &self.customer_id)
.field("kind", &self.kind)
.field("value", &"<redacted>")
.field("external_ref", &self.external_ref)
.field("source_label", &self.source_label)
.field("first_seen_at", &self.first_seen_at)
.field("last_seen_at", &self.last_seen_at)
.finish()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CustomerIdentityImportPreviewRequest {
pub rows: Vec<CustomerIdentityImportRow>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CustomerIdentityImportRequest {
pub idempotency_key: String,
pub rows: Vec<CustomerIdentityImportRow>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CustomerIdentityHistoryRequest {
pub customer_ids: Vec<String>,
}
#[derive(Clone, Serialize)]
pub struct CustomerIdentityHistorySearchRequest {
pub query: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub group_by_customer: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
}
impl CustomerIdentityHistorySearchRequest {
pub fn new(query: impl Into<String>) -> Self {
Self {
query: query.into(),
limit: None,
group_by_customer: false,
cursor: None,
}
}
}
impl std::fmt::Debug for CustomerIdentityHistorySearchRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomerIdentityHistorySearchRequest")
.field("query", &"<redacted>")
.field("limit", &self.limit)
.field("group_by_customer", &self.group_by_customer)
.field("cursor", &self.cursor.as_ref().map(|_| "<cursor>"))
.finish()
}
}
#[derive(Debug, Clone, Default)]
pub struct CustomerListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
pub customer_id: Option<String>,
pub search: Option<String>,
pub email: Option<String>,
pub start_time: Option<String>,
pub end_time: Option<String>,
pub profile_id: Option<String>,
pub profile_ids: Vec<String>,
pub project_id: Option<String>,
}
impl CustomerListParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
if let Some(v) = &self.customer_id {
q.push(("customer_id", v.clone()));
}
if let Some(v) = &self.search {
q.push(("search", v.clone()));
}
if let Some(v) = &self.email {
q.push(("email", v.clone()));
}
if let Some(v) = &self.start_time {
q.push(("start_time", v.clone()));
}
if let Some(v) = &self.end_time {
q.push(("end_time", v.clone()));
}
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
if !self.profile_ids.is_empty() {
q.push(("profile_ids", self.profile_ids.join(",")));
}
if let Some(v) = &self.project_id {
q.push(("project_id", v.clone()));
}
q
}
#[must_use]
pub fn profile_ids<I, S>(mut self, profile_ids: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.profile_ids = profile_ids.into_iter().map(Into::into).collect();
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CustomerCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_country_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const CUSTOMER_CREATE_REQUEST_NAMED: &[&str] = &[
"customer_id",
"name",
"email",
"phone",
"phone_country_code",
"description",
"address",
"metadata",
"profile_id",
];
impl ValidateRequest for CustomerCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CUSTOMER_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on CustomerCreateRequest"
)));
}
}
Ok(())
}
}
impl CustomerCreateRequest {
pub fn new() -> Self {
Self::default()
}
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
pub fn email(mut self, email: impl Into<String>) -> Self {
self.email = Some(email.into());
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn phone(mut self, phone: impl Into<String>, country_code: impl Into<String>) -> Self {
self.phone = Some(phone.into());
self.phone_country_code = Some(country_code.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use crate::core::models::buyer_portal::BuyerPortalSubscriptionPermissions;
use crate::core::models::customer_identity::CustomerIdentityImportOutcome;
use crate::http::mock::{Step, client_with, client_with_retries};
const IMPORT_JSON: &str = r#"{
"run_id": "cir_1",
"idempotency_key": "af-0001",
"replayed": false,
"rows_total": 1,
"rows_accepted": 1,
"rows_unchanged": 0,
"rows_rejected": 0,
"created_at": "2026-10-31T12:00:00.000Z",
"rows": [{"row_index": 0, "external_ref": "u1-email-0", "customer_id": "cus_1",
"kind": "email", "outcome": "accepted", "reason": null, "entry_id": "cih_1"}]
}"#;
const PORTAL_LINK_SUMMARY_JSON: &str = r#"{
"id": "bpl_1",
"profile_id": "pro_1",
"expires_at": 1767225600,
"allow_subscription_changes": true,
"restrictions": {"refund_requests": false, "subscription_actions": {"pause": true}},
"surprise_field": 1
}"#;
#[tokio::test]
async fn create_portal_link_posts_only_the_set_fields() {
let (client, mock) = client_with(vec![Step::ok(
r##"{"id":"bpl_1","url":"https://portal.test/#tok","expires_at":1767225600,"surprise_field":1}"##,
)]);
let params = BuyerInvoiceLinkRequest::new()
.profile_id("pro_1")
.allow_subscription_changes(true)
.restrictions(
BuyerPortalLinkRestrictions::new()
.refund_requests(false)
.subscription_actions(BuyerPortalSubscriptionPermissions::new().pause(true)),
)
.expires_in_seconds(3600);
let link = client
.customers()
.create_portal_link("cus/1", ¶ms)
.await
.unwrap();
assert_eq!(link.id, "bpl_1");
assert_eq!(link.url, "https://portal.test/#tok");
assert_eq!(link.expires_at, 1_767_225_600);
assert_eq!(link.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/customers/cus%2F1/portal-links"
);
assert_eq!(
seen[0].body_json(),
json!({
"profile_id": "pro_1",
"allow_subscription_changes": true,
"restrictions": {"refund_requests": false, "subscription_actions": {"pause": true}},
"expires_in_seconds": 3600
})
);
}
#[tokio::test]
async fn create_portal_link_sends_an_empty_object_by_default() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"id":"bpl_1","url":"https://portal.test/","expires_at":1}"#,
)]);
client
.customers()
.create_portal_link("cus_1", &BuyerInvoiceLinkRequest::new())
.await
.unwrap();
assert_eq!(mock.seen.lock().unwrap()[0].body_json(), json!({}));
}
#[tokio::test]
async fn list_portal_links_serializes_pagination() {
let page = format!(
r#"{{"data":[{PORTAL_LINK_SUMMARY_JSON}],"total_count":1,"limit":10,"offset":20}}"#
);
let (client, mock) = client_with(vec![Step::ok(&page), Step::ok(&page)]);
let customers = client.customers();
let out = customers
.list_portal_links(
"cus/1",
Some(&BuyerPortalLinkListParams {
limit: Some(10),
offset: Some(20),
}),
)
.await
.unwrap();
assert_eq!(out.total_count, 1);
let summary = &out.data[0];
assert_eq!(summary.id, "bpl_1");
assert!(summary.allow_subscription_changes);
assert_eq!(summary.restrictions.refund_requests, Some(false));
assert_eq!(
summary
.restrictions
.subscription_actions
.as_ref()
.unwrap()
.pause,
Some(true)
);
assert_eq!(summary.extra["surprise_field"], 1);
customers.list_portal_links("cus/1", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/customers/cus%2F1/portal-links?limit=10&offset=20"
);
assert_eq!(
seen[1].url,
"https://api.test/customers/cus%2F1/portal-links"
);
}
#[tokio::test]
async fn revoke_portal_link_deletes_the_link_path_and_accepts_an_empty_body() {
let (client, mock) = client_with(vec![Step::ok(""), Step::ok(r#"{"revoked":true}"#)]);
let customers = client.customers();
customers
.revoke_portal_link("cus/1", "bpl/1")
.await
.unwrap();
customers
.revoke_portal_link("cus/1", "bpl/1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/customers/cus%2F1/portal-links/bpl%2F1"
);
}
#[test]
fn buyer_invoice_link_request_named_fields_are_complete() {
let value = serde_json::to_value(
BuyerInvoiceLinkRequest::new()
.profile_id("pro_1")
.allow_subscription_changes(true)
.restrictions(BuyerPortalLinkRestrictions::new())
.expires_in_seconds(3600),
)
.unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
BUYER_INVOICE_LINK_REQUEST_NAMED.contains(&key.as_str()),
"BUYER_INVOICE_LINK_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn buyer_portal_link_restrictions_named_fields_are_complete() {
let value = serde_json::to_value(
BuyerPortalLinkRestrictions::new()
.subscription_changes(true)
.subscription_actions(BuyerPortalSubscriptionPermissions::new())
.profile_changes(false)
.email_policy("read_only")
.refund_requests(true)
.refund_requests_for_renewals(false),
)
.unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
BUYER_PORTAL_LINK_RESTRICTIONS_NAMED.contains(&key.as_str()),
"BUYER_PORTAL_LINK_RESTRICTIONS_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn buyer_portal_subscription_permissions_named_fields_are_complete() {
let value = serde_json::to_value(
BuyerPortalSubscriptionPermissions::new()
.pause(true)
.resume(true)
.cancel_at_period_end(false)
.cancel_immediately(false)
.change_plan(true),
)
.unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED.contains(&key.as_str()),
"BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn portal_link_validate_rejects_colliding_extra_keys_at_every_level() {
let mut top = BuyerInvoiceLinkRequest::new();
top.extra.insert("profile_id".to_string(), json!("pro_2"));
assert!(matches!(
top.validate(),
Err(DelopayError::InvalidRequest(msg)) if msg.contains("profile_id")
));
let mut restrictions = BuyerPortalLinkRestrictions::new();
restrictions
.extra
.insert("refund_requests".to_string(), json!(true));
let nested = BuyerInvoiceLinkRequest::new().restrictions(restrictions);
assert!(matches!(
nested.validate(),
Err(DelopayError::InvalidRequest(msg)) if msg.contains("refund_requests")
));
let mut actions = BuyerPortalSubscriptionPermissions::new();
actions.extra.insert("pause".to_string(), json!(true));
let deepest = BuyerInvoiceLinkRequest::new()
.restrictions(BuyerPortalLinkRestrictions::new().subscription_actions(actions));
assert!(matches!(
deepest.validate(),
Err(DelopayError::InvalidRequest(msg)) if msg.contains("pause")
));
}
fn identity_row() -> CustomerIdentityImportRow {
CustomerIdentityImportRow {
customer_id: "cus_1".to_string(),
kind: "email".to_string(),
value: "jane.doe@example.com".to_string(),
external_ref: "u1-email-0".to_string(),
source_label: "account".to_string(),
first_seen_at: None,
last_seen_at: None,
}
}
fn import_request(key: &str) -> CustomerIdentityImportRequest {
CustomerIdentityImportRequest {
idempotency_key: key.to_string(),
rows: vec![identity_row()],
}
}
#[tokio::test]
async fn identity_import_posts_the_rows_with_their_key_in_body_and_header() {
let (client, mock) = client_with(vec![Step::ok(IMPORT_JSON)]);
let run = client
.customers()
.import_identity_history(&import_request("af-0001"))
.await
.unwrap();
assert_eq!(run.run_id, "cir_1");
assert_eq!(run.rows[0].outcome, CustomerIdentityImportOutcome::Accepted);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/customers/identity-history/import"
);
assert_eq!(seen[0].header("idempotency-key"), Some("af-0001"));
let body = seen[0].body_json();
assert_eq!(body["idempotency_key"], "af-0001");
assert_eq!(body["rows"][0]["value"], "jane.doe@example.com");
assert!(body["rows"][0].get("first_seen_at").is_none());
}
#[tokio::test]
async fn identity_import_is_retried_after_a_5xx_under_the_same_key() {
let (client, mock) = client_with_retries(
vec![
Step::status(500, r#"{"error":{"message":"boom"}}"#),
Step::ok(IMPORT_JSON),
],
2,
);
client
.customers()
.import_identity_history(&import_request("af-0001"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert_eq!(seen[1].header("idempotency-key"), Some("af-0001"));
assert_eq!(seen[1].body_json()["idempotency_key"], "af-0001");
}
#[tokio::test]
async fn identity_preview_is_not_retried_after_a_5xx() {
let (client, mock) = client_with_retries(
vec![
Step::status(500, r#"{"error":{"message":"boom"}}"#),
Step::ok(
r#"{"rows_total":1,"rows_accepted":1,"rows_unchanged":0,"rows_rejected":0,"customers_without_record":0,"rows":[]}"#,
),
],
2,
);
let out = client
.customers()
.preview_identity_import(&CustomerIdentityImportPreviewRequest {
rows: vec![identity_row()],
})
.await;
assert!(out.is_err());
assert_eq!(mock.seen.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn identity_import_refuses_a_key_the_api_would_refuse_without_sending() {
let (client, mock) = client_with(vec![]);
for key in ["", " ", "line\nbreak", &"k".repeat(256)] {
let out = client
.customers()
.import_identity_history(&import_request(key))
.await;
assert!(
matches!(out, Err(DelopayError::InvalidRequest(_))),
"{key:?}"
);
}
assert_eq!(mock.seen.lock().unwrap().len(), 0);
}
#[tokio::test]
async fn identity_import_refuses_no_rows_and_more_than_a_thousand() {
let (client, mock) = client_with(vec![]);
let mut request = import_request("af-0001");
request.rows.clear();
assert!(
client
.customers()
.import_identity_history(&request)
.await
.is_err()
);
request.rows = vec![identity_row(); MAX_IDENTITY_IMPORT_ROWS + 1];
assert!(
client
.customers()
.import_identity_history(&request)
.await
.is_err()
);
assert_eq!(mock.seen.lock().unwrap().len(), 0);
}
#[tokio::test]
async fn identity_search_sends_the_text_in_the_body_only() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"entries":[{"id":"cih_1","customer_id":"cus_1","kind":"email",
"value":"jane.doe@example.com","normalized_value":"jane.doe@example.com",
"source":"import","source_label":"account","seen_count":1,
"recorded_at":"2026-10-31T12:00:00.000Z"}],"truncated":true}"#,
)]);
let found = client
.customers()
.search_identity_history(&CustomerIdentityHistorySearchRequest {
limit: Some(10),
..CustomerIdentityHistorySearchRequest::new("doe@exam")
})
.await
.unwrap();
assert_eq!(found.truncated, Some(true));
assert_eq!(found.entries[0].customer_id, "cus_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/customers/identity-history/search"
);
assert_eq!(seen[0].body_json()["query"], "doe@exam");
assert_eq!(seen[0].body_json()["limit"], 10);
assert!(
seen[0].body_json().get("group_by_customer").is_none(),
"the default answer sends no grouping"
);
}
#[tokio::test]
async fn identity_search_by_customer_sends_its_page_and_reads_the_customers() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"entries":[],"truncated":false,"total_customers":3,"next_cursor":"6162",
"customers":[{"customer_id":"cus_1","entries":[{"id":"cih_1","customer_id":"cus_1",
"kind":"email","value":"jane.doe@example.com","normalized_value":"jane.doe@example.com",
"source":"import","source_label":"account","seen_count":1,
"recorded_at":"2026-10-31T12:00:00.000Z"}]}]}"#,
)]);
let page = client
.customers()
.search_identity_history(&CustomerIdentityHistorySearchRequest {
group_by_customer: true,
cursor: Some("5a5a".to_string()),
limit: Some(1),
..CustomerIdentityHistorySearchRequest::new("doe@exam")
})
.await
.unwrap();
assert_eq!(page.total_customers, Some(3));
assert_eq!(page.next_cursor.as_deref(), Some("6162"));
let customers = page.customers.expect("customers");
assert_eq!(customers[0].customer_id, "cus_1");
assert_eq!(customers[0].entries.len(), 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].body_json()["group_by_customer"], true);
assert_eq!(seen[0].body_json()["cursor"], "5a5a");
}
#[tokio::test]
async fn identity_search_refuses_a_limit_outside_one_to_a_hundred() {
let (client, mock) = client_with(vec![]);
for limit in [0, MAX_IDENTITY_SEARCH_RESULTS + 1] {
let out = client
.customers()
.search_identity_history(&CustomerIdentityHistorySearchRequest {
limit: Some(limit),
..CustomerIdentityHistorySearchRequest::new("doe")
})
.await;
assert!(out.is_err(), "{limit}");
}
assert_eq!(mock.seen.lock().unwrap().len(), 0);
}
const PREVIEW_JSON: &str = r#"{"rows_total":1,"rows_accepted":1,"rows_unchanged":0,
"rows_rejected":0,"customers_without_record":1,"rows_with_other_customers":1,
"rows":[{"row_index":0,"external_ref":"u1-email-0","customer_id":"cus_1",
"kind":"email","outcome":"accepted","reason":null,"other_customers":2}]}"#;
fn preview_of(rows: Vec<CustomerIdentityImportRow>) -> CustomerIdentityImportPreviewRequest {
CustomerIdentityImportPreviewRequest { rows }
}
#[tokio::test]
async fn identity_preview_reads_the_conflict_note_and_the_customers_without_record() {
let (client, _mock) = client_with(vec![Step::ok(PREVIEW_JSON)]);
let preview = client
.customers()
.preview_identity_import(&preview_of(vec![identity_row()]))
.await
.unwrap();
assert_eq!(preview.customers_without_record, 1);
assert_eq!(preview.rows_with_other_customers, 1);
assert_eq!(preview.rows[0].other_customers, Some(2));
}
#[test]
fn a_time_names_its_offset_only_with_z_or_a_signed_offset() {
for value in [
"2026-10-31T12:00:00Z",
"2026-10-31T12:00:00.123z",
"2026-10-31T12:00:00+01:00",
"2026-10-31T12:00:00-05:30",
"2026-10-31T12:00:00+0100",
] {
assert!(names_its_offset(value), "{value}");
}
for value in [
"2026-10-31T12:00:00",
"2026-10-31",
"2026-10-31T12:00:00+",
"",
] {
assert!(!names_its_offset(value), "{value}");
}
}
#[tokio::test]
async fn identity_import_refuses_a_time_without_its_offset_without_sending() {
let (client, mock) = client_with(vec![Step::ok(PREVIEW_JSON)]);
for (first, last) in [
(Some("2026-10-31T12:00:00"), None),
(None, Some("2026-10-31")),
] {
let mut row = identity_row();
row.first_seen_at = first.map(str::to_owned);
row.last_seen_at = last.map(str::to_owned);
let out = client
.customers()
.preview_identity_import(&preview_of(vec![identity_row(), row.clone()]))
.await;
assert!(
matches!(out, Err(DelopayError::InvalidRequest(ref message)) if message.contains("rows[1]")),
"{out:?}"
);
let out = client
.customers()
.import_identity_history(&CustomerIdentityImportRequest {
idempotency_key: "af-0001".to_owned(),
rows: vec![row],
})
.await;
assert!(matches!(out, Err(DelopayError::InvalidRequest(_))));
}
assert_eq!(mock.seen.lock().unwrap().len(), 0);
let mut dated = identity_row();
dated.first_seen_at = Some("2026-10-31T12:00:00Z".to_owned());
dated.last_seen_at = Some("2026-11-01T08:00:00+01:00".to_owned());
client
.customers()
.preview_identity_import(&preview_of(vec![dated]))
.await
.unwrap();
assert_eq!(
mock.seen.lock().unwrap()[0].body_json()["rows"][0]["first_seen_at"],
"2026-10-31T12:00:00Z"
);
}
#[tokio::test]
async fn identity_import_refuses_a_body_over_its_limit_without_sending() {
let (client, mock) = client_with(vec![Step::ok(PREVIEW_JSON)]);
let mut row = identity_row();
row.value = "x".repeat(7300);
let over = vec![row.clone(); MAX_IDENTITY_IMPORT_ROWS];
let out = client
.customers()
.preview_identity_import(&preview_of(over.clone()))
.await;
assert!(
matches!(out, Err(DelopayError::InvalidRequest(_))),
"{out:?}"
);
let out = client
.customers()
.import_identity_history(&CustomerIdentityImportRequest {
idempotency_key: "af-0001".to_owned(),
rows: over,
})
.await;
assert!(
matches!(out, Err(DelopayError::InvalidRequest(_))),
"{out:?}"
);
assert_eq!(mock.seen.lock().unwrap().len(), 0);
row.value = "x".repeat(7000);
client
.customers()
.preview_identity_import(&preview_of(vec![row; MAX_IDENTITY_IMPORT_ROWS]))
.await
.unwrap();
assert_eq!(mock.seen.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn identity_list_refuses_a_body_over_its_limit_without_sending() {
let (client, mock) = client_with(vec![Step::ok(r#"{"entries":[]}"#)]);
let out = client
.customers()
.list_identity_history(&CustomerIdentityHistoryRequest {
customer_ids: vec!["c".repeat(140); MAX_IDENTITY_CUSTOMERS],
})
.await;
assert!(
matches!(out, Err(DelopayError::InvalidRequest(_))),
"{out:?}"
);
assert_eq!(mock.seen.lock().unwrap().len(), 0);
client
.customers()
.list_identity_history(&CustomerIdentityHistoryRequest {
customer_ids: vec!["c".repeat(64); MAX_IDENTITY_CUSTOMERS],
})
.await
.unwrap();
assert_eq!(mock.seen.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn identity_search_refuses_a_long_query_and_a_cursor_without_grouping() {
let (client, mock) = client_with(vec![Step::ok(r#"{"entries":[]}"#)]);
let long = CustomerIdentityHistorySearchRequest::new(
"q".repeat(MAX_IDENTITY_SEARCH_QUERY_CHARS + 1),
);
assert!(matches!(
client.customers().search_identity_history(&long).await,
Err(DelopayError::InvalidRequest(_))
));
let ungrouped = CustomerIdentityHistorySearchRequest {
cursor: Some("c1".to_owned()),
..CustomerIdentityHistorySearchRequest::new("doe")
};
assert!(matches!(
client.customers().search_identity_history(&ungrouped).await,
Err(DelopayError::InvalidRequest(_))
));
assert_eq!(mock.seen.lock().unwrap().len(), 0);
client
.customers()
.search_identity_history(&CustomerIdentityHistorySearchRequest::new(
"ü".repeat(MAX_IDENTITY_SEARCH_QUERY_CHARS),
))
.await
.unwrap();
assert_eq!(mock.seen.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn identity_readback_encodes_the_run_id_and_reads_the_entries() {
let readback =
IMPORT_JSON.trim_end().trim_end_matches('}').to_string() + r#","entries":[]}"#;
let (client, mock) = client_with(vec![Step::ok(&readback)]);
let run = client
.customers()
.retrieve_identity_import("cir/1")
.await
.unwrap();
assert_eq!(run.entries.map(|e| e.len()), Some(0));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/customers/identity-history/import/cir%2F1"
);
}
#[tokio::test]
async fn identity_list_refuses_no_customers_without_sending() {
let (client, mock) = client_with(vec![]);
let out = client
.customers()
.list_identity_history(&CustomerIdentityHistoryRequest {
customer_ids: vec![],
})
.await;
assert!(out.is_err());
assert_eq!(mock.seen.lock().unwrap().len(), 0);
}
#[test]
fn identity_values_never_reach_debug() {
let row = format!("{:?}", identity_row());
assert!(!row.contains("jane.doe"), "{row}");
let search = format!(
"{:?}",
CustomerIdentityHistorySearchRequest::new("secret-needle")
);
assert!(!search.contains("secret-needle"), "{search}");
let entry: crate::core::models::customer_identity::CustomerIdentityEntry =
serde_json::from_str(
r#"{"id":"cih_1","customer_id":"cus_1","kind":"email",
"value":"jane.doe@example.com","normalized_value":"jane.doe@example.com",
"source":"import","source_label":"account","seen_count":1,
"recorded_at":"2026-10-31T12:00:00.000Z"}"#,
)
.unwrap();
let entry = format!("{entry:?}");
assert!(!entry.contains("jane.doe"), "{entry}");
}
#[test]
fn an_unknown_import_outcome_still_decodes() {
let row: crate::core::models::customer_identity::CustomerIdentityImportRowResult =
serde_json::from_str(r#"{"row_index":0,"external_ref":"x","outcome":"merged"}"#)
.unwrap();
assert_eq!(row.outcome, CustomerIdentityImportOutcome::Unknown);
}
fn full_customer_create_request() -> CustomerCreateRequest {
CustomerCreateRequest {
customer_id: Some("cus_1".to_string()),
name: Some("Ada Lovelace".to_string()),
email: Some("ada@example.com".to_string()),
phone: Some("5551234".to_string()),
phone_country_code: Some("+44".to_string()),
description: Some("VIP customer".to_string()),
address: Some(json!({"country": "GB"})),
metadata: Some(json!({"tier": "gold"})),
profile_id: Some("pro_1".to_string()),
extra: serde_json::Map::new(),
}
}
#[test]
fn customer_create_request_named_fields_are_complete() {
let value = serde_json::to_value(full_customer_create_request()).unwrap();
let obj = value.as_object().expect("serializes to a JSON object");
for key in obj.keys() {
assert!(
CUSTOMER_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"CUSTOMER_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
add it, or CustomerCreateRequest's extra-key collision guard \
will silently stop covering this field"
);
}
}
#[test]
fn validate_rejects_extra_key_colliding_with_named_field() {
let mut req = CustomerCreateRequest::new().email("ada@example.com");
req.extra.insert("name".to_string(), json!("collide"));
let err = req.validate().unwrap_err();
match err {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[tokio::test]
async fn list_serializes_shop_filters() {
let (client, mock) = client_with(vec![Step::ok("[]")]);
let params = CustomerListParams {
limit: Some(10),
profile_id: Some("pro_1".to_string()),
..Default::default()
};
client.customers().list(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/customers/list?limit=10&profile_id=pro_1"
);
}
#[tokio::test]
async fn list_sends_profile_ids_as_one_comma_separated_value() {
let (client, mock) = client_with(vec![Step::ok("[]")]);
let params = CustomerListParams::default().profile_ids(["pro_1", "pro_2"]);
client.customers().list(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/customers/list?profile_ids=pro_1,pro_2"
);
}
#[tokio::test]
async fn list_omits_an_empty_profile_ids_filter() {
let (client, mock) = client_with(vec![Step::ok("[]")]);
let params = CustomerListParams::default().profile_ids(Vec::<String>::new());
client.customers().list(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/customers/list");
}
#[tokio::test]
async fn list_with_count_hits_its_path_and_reads_the_total() {
let (client, mock) = client_with(vec![
Step::ok(r#"{"total_count":9,"data":[{"customer_id":"cus_1"}]}"#),
Step::ok(r#"{"total_count":0,"data":[]}"#),
]);
let customers = client.customers();
let out = customers.list_with_count(None).await.unwrap();
assert_eq!(out.total_count, Some(9));
assert_eq!(out.data.len(), 1);
let params = CustomerListParams {
customer_id: Some("cus_1".to_string()),
search: Some("ada".to_string()),
start_time: Some("2026-01-01T00:00:00Z".to_string()),
end_time: Some("2026-02-01T00:00:00Z".to_string()),
..Default::default()
};
customers.list_with_count(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/customers/list-with-count");
assert_eq!(
seen[1].url,
"https://api.test/customers/list-with-count?customer_id=cus_1&search=ada\
&start_time=2026-01-01T00:00:00Z&end_time=2026-02-01T00:00:00Z"
);
}
#[tokio::test]
async fn every_customer_list_sends_the_exact_email_filter() {
let (client, mock) = client_with(vec![
Step::ok("[]"),
Step::ok(r#"{"total_count":1,"data":[]}"#),
Step::ok("[]"),
Step::ok(r#"{"total_count":1,"data":[]}"#),
]);
let params = CustomerListParams {
email: Some("jane@example.com".to_string()),
..Default::default()
};
let customers = client.customers();
customers.list(Some(¶ms)).await.unwrap();
customers.list_with_count(Some(¶ms)).await.unwrap();
customers.list_by_profile(Some(¶ms)).await.unwrap();
customers
.list_by_profile_with_count(Some(¶ms))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
let urls: Vec<&str> = seen.iter().map(|call| call.url.as_str()).collect();
assert_eq!(
urls,
[
"https://api.test/customers/list?email=jane@example.com",
"https://api.test/customers/list-with-count?email=jane@example.com",
"https://api.test/customers/profile/list?email=jane@example.com",
"https://api.test/customers/profile/list-with-count?email=jane@example.com",
]
);
}
#[tokio::test]
async fn profile_scoped_lists_hit_the_profile_paths() {
let (client, mock) = client_with(vec![
Step::ok("[]"),
Step::ok(r#"{"total_count":9,"data":[]}"#),
]);
let params = CustomerListParams {
limit: Some(10),
search: Some("ada".to_string()),
..Default::default()
};
client
.customers()
.list_by_profile(Some(¶ms))
.await
.unwrap();
let out = client
.customers()
.list_by_profile_with_count(None)
.await
.unwrap();
assert_eq!(out.total_count, Some(9));
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
(
"GET",
"https://api.test/customers/profile/list?limit=10&search=ada"
)
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
("GET", "https://api.test/customers/profile/list-with-count")
);
}
#[tokio::test]
async fn list_mandates_gets_the_customer_mandates_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"[{"mandate_id":"man_1","status":"active"}]"#,
)]);
let out = client.customers().list_mandates("cus_1").await.unwrap();
assert_eq!(out[0].mandate_id, "man_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/customers/cus_1/mandates");
}
#[tokio::test]
async fn portal_link_writes_ignore_the_client_wide_idempotency_key() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, "{}"),
Step::status(503, "{}"),
Step::ok(""),
],
2,
);
let customers = client.with_idempotency_key("client-key").customers();
assert!(
customers
.create_portal_link("cus_1", &BuyerInvoiceLinkRequest::new())
.await
.is_err()
);
assert!(
customers
.revoke_portal_link("cus_1", "bpl_1")
.await
.is_err()
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert!(seen.iter().all(|step| !step.had_idempotency_key()));
}
}