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;
use crate::core::models::customer::CustomerResponse;
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>,
}
impl Customers {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
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(
HttpMethod::Get,
"/customers/profile/list",
None,
&query,
None,
)
.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(
HttpMethod::Get,
"/customers/profile/list-with-count",
None,
&query,
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
}
}
#[derive(Debug, Clone, Default)]
pub struct CustomerListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
pub email: 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.email {
q.push(("email", 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(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",
];
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 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;
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"})),
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:?}"),
}
}
use crate::http::mock::{Step, client_with};
#[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_keeps_count_in_extra() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"count":1,"total_count":9,"data":[{"customer_id":"cus_1"}]}"#,
)]);
let out = client.customers().list_with_count(None).await.unwrap();
assert_eq!(out.total_count, Some(9));
assert_eq!(out.extra["count"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/customers/list-with-count");
}
#[tokio::test]
async fn profile_scoped_lists_hit_the_profile_paths() {
let (client, mock) = client_with(vec![
Step::ok("[]"),
Step::ok(r#"{"count":1,"total_count":9,"data":[]}"#),
]);
let params = CustomerListParams {
limit: Some(10),
email: Some("ada@example.com".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&email=ada@example.com"
)
);
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");
}
}