Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(customer): customer v2 refactor for customer create end point (#5350)

Sahkal Poddaraaf1f2b1e5e1
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index aced6a293a..a2eb9d476e 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -19,6 +19,7 @@ openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"]
recon = []
v2 = []
v1 = []
+customer_v2 = []
merchant_account_v2 = []
payment_v2 = []
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index 73fb5264ed..ace4b54916 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -13,6 +13,7 @@ use utoipa::ToSchema;
use crate::payments;
/// The customer details
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
pub struct CustomerRequest {
/// The identifier for the customer object. If not provided the customer ID will be autogenerated.
@@ -47,6 +48,77 @@ pub struct CustomerRequest {
pub metadata: Option<pii::SecretSerdeValue>,
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+impl CustomerRequest {
+ pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
+ Some(
+ self.customer_id
+ .to_owned()
+ .unwrap_or_else(common_utils::generate_customer_id_of_default_length),
+ )
+ }
+ pub fn get_address(&self) -> Option<payments::AddressDetails> {
+ self.address.clone()
+ }
+ pub fn get_optional_email(&self) -> Option<pii::Email> {
+ self.email.clone()
+ }
+}
+
+/// The customer details
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
+pub struct CustomerRequest {
+ /// The merchant identifier for the customer object.
+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub merchant_reference_id: Option<id_type::CustomerId>,
+ /// The customer's name
+ #[schema(max_length = 255, value_type = String, example = "Jon Test")]
+ pub name: Secret<String>,
+ /// The customer's email address
+ #[schema(value_type = String, max_length = 255, example = "[email protected]")]
+ pub email: pii::Email,
+ /// The customer's phone number
+ #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")]
+ pub phone: Option<Secret<String>>,
+ /// An arbitrary string that you can attach to a customer object.
+ #[schema(max_length = 255, example = "First Customer")]
+ pub description: Option<String>,
+ /// The country code for the customer phone number
+ #[schema(max_length = 255, example = "+65")]
+ pub phone_country_code: Option<String>,
+ /// The default billing address for the customer
+ #[schema(value_type = Option<AddressDetails>)]
+ pub default_billing_address: Option<payments::AddressDetails>,
+ /// The default shipping address for the customer
+ #[schema(value_type = Option<AddressDetails>)]
+ pub default_shipping_address: Option<payments::AddressDetails>,
+ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
+ /// characters long. Metadata is useful for storing additional, structured information on an
+ /// object.
+ #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
+ pub metadata: Option<pii::SecretSerdeValue>,
+}
+
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+impl CustomerRequest {
+ pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
+ self.merchant_reference_id.clone()
+ }
+
+ pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> {
+ self.default_billing_address.clone()
+ }
+
+ pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> {
+ self.default_shipping_address.clone()
+ }
+
+ pub fn get_optional_email(&self) -> Option<pii::Email> {
+ Some(self.email.clone())
+ }
+}
+
pub struct CustomerRequestWithEmail {
pub name: Option<Secret<String>>,
pub email: Option<pii::Email>,
@@ -126,6 +198,7 @@ impl ToEncryptable<EncryptableCustomer, Secret<String>, Secret<String>>
}
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CustomerResponse {
/// The identifier for the customer object
@@ -163,11 +236,97 @@ pub struct CustomerResponse {
pub default_payment_method_id: Option<String>,
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+impl CustomerResponse {
+ pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
+ Some(self.customer_id.clone())
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct CustomerResponse {
+ /// The identifier for the customer object
+ #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub merchant_reference_id: Option<id_type::CustomerId>,
+ /// The customer's name
+ #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")]
+ pub name: crypto::OptionalEncryptableName,
+ /// The customer's email address
+ #[schema(value_type = Option<String> ,max_length = 255, example = "[email protected]")]
+ pub email: crypto::OptionalEncryptableEmail,
+ /// The customer's phone number
+ #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")]
+ pub phone: crypto::OptionalEncryptablePhone,
+ /// The country code for the customer phone number
+ #[schema(max_length = 255, example = "+65")]
+ pub phone_country_code: Option<String>,
+ /// An arbitrary string that you can attach to a customer object.
+ #[schema(max_length = 255, example = "First Customer")]
+ pub description: Option<String>,
+ /// The default billing address for the customer
+ #[schema(value_type = Option<AddressDetails>)]
+ pub default_billing_address: Option<payments::AddressDetails>,
+ /// The default shipping address for the customer
+ #[schema(value_type = Option<AddressDetails>)]
+ pub default_shipping_address: Option<payments::AddressDetails>,
+ /// A timestamp (ISO 8601 code) that determines when the customer was created
+ #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")]
+ #[serde(with = "custom_serde::iso8601")]
+ pub created_at: time::PrimitiveDateTime,
+ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500
+ /// characters long. Metadata is useful for storing additional, structured information on an
+ /// object.
+ #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
+ pub metadata: Option<pii::SecretSerdeValue>,
+ /// The identifier for the default payment method.
+ #[schema(max_length = 64, example = "pm_djh2837dwduh890123")]
+ pub default_payment_method_id: Option<String>,
+}
+
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+impl CustomerResponse {
+ pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
+ self.merchant_reference_id.clone()
+ }
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CustomerId {
pub customer_id: id_type::CustomerId,
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+impl CustomerId {
+ pub fn get_merchant_reference_id(&self) -> id_type::CustomerId {
+ self.customer_id.clone()
+ }
+
+ pub fn new_customer_id_struct(cust: id_type::CustomerId) -> Self {
+ Self { customer_id: cust }
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct CustomerId {
+ pub merchant_reference_id: id_type::CustomerId,
+}
+
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+impl CustomerId {
+ pub fn get_merchant_reference_id(&self) -> id_type::CustomerId {
+ self.merchant_reference_id.clone()
+ }
+
+ pub fn new_customer_id_struct(cust: id_type::CustomerId) -> Self {
+ Self {
+ merchant_reference_id: cust,
+ }
+ }
+}
+
#[derive(Debug, Deserialize, Serialize, ToSchema)]
pub struct CustomerDeleteResponse {
/// The identifier for the customer object
@@ -184,6 +343,7 @@ pub struct CustomerDeleteResponse {
pub payment_methods_deleted: bool,
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
fn unknown_merchant() -> String {
String::from("merchant_unknown")
}
diff --git a/crates/api_models/src/events/customer.rs b/crates/api_models/src/events/customer.rs
index f98061a2d8..daa8748a24 100644
--- a/crates/api_models/src/events/customer.rs
+++ b/crates/api_models/src/events/customer.rs
@@ -12,7 +12,7 @@ impl ApiEventMetric for CustomerDeleteResponse {
impl ApiEventMetric for CustomerRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
- self.customer_id
+ self.get_merchant_reference_id()
.clone()
.map(|customer_id| ApiEventsType::Customer { customer_id })
}
@@ -20,16 +20,16 @@ impl ApiEventMetric for CustomerRequest {
impl ApiEventMetric for CustomerResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::Customer {
- customer_id: self.customer_id.clone(),
- })
+ self.get_merchant_reference_id()
+ .clone()
+ .map(|cid| ApiEventsType::Customer { customer_id: cid })
}
}
impl ApiEventMetric for CustomerId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Customer {
- customer_id: self.customer_id.clone(),
+ customer_id: self.get_merchant_reference_id().clone(),
})
}
}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 1ca01114dd..fa7b3dc2dd 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -11,10 +11,12 @@ use masking::PeekInterface;
use serde::de;
use utoipa::{schema, ToSchema};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use crate::customers;
#[cfg(feature = "payouts")]
use crate::payouts;
use crate::{
- admin, customers, enums as api_enums,
+ admin, enums as api_enums,
payments::{self, BankCodeResponse},
};
@@ -1481,6 +1483,7 @@ impl From<PaymentMethodRecord> for PaymentMethodMigrate {
}
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl From<PaymentMethodRecord> for customers::CustomerRequest {
fn from(record: PaymentMethodRecord) -> Self {
Self {
@@ -1506,3 +1509,30 @@ impl From<PaymentMethodRecord> for customers::CustomerRequest {
}
}
}
+
+// #[cfg(feature = "v2")]
+// impl From<PaymentMethodRecord> for customers::CustomerRequest {
+// fn from(record: PaymentMethodRecord) -> Self {
+// Self {
+// merchant_reference_id: Some(record.customer_id),
+// name: record.name.unwrap(),
+// email: record.email.unwrap(),
+// phone: record.phone,
+// description: None,
+// phone_country_code: record.phone_country_code,
+// default_billing_address: Some(payments::AddressDetails {
+// city: Some(record.billing_address_city),
+// country: record.billing_address_country,
+// line1: Some(record.billing_address_line1),
+// line2: record.billing_address_line2,
+// state: Some(record.billing_address_state),
+// line3: record.billing_address_line3,
+// zip: Some(record.billing_address_zip),
+// first_name: Some(record.billing_address_first_name),
+// last_name: Some(record.billing_address_last_name),
+// }),
+// default_shipping_address: None,
+// metadata: None,
+// }
+// }
+// }
diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs
index 7901dec6db..779781a7d8 100644
--- a/crates/common_utils/src/crypto.rs
+++ b/crates/common_utils/src/crypto.rs
@@ -490,6 +490,10 @@ pub type OptionalEncryptablePhone = Option<Encryptable<Secret<String>>>;
pub type OptionalEncryptableValue = Option<Encryptable<Secret<serde_json::Value>>>;
/// Type alias for `Option<Secret<serde_json::Value>>`
pub type OptionalSecretValue = Option<Secret<serde_json::Value>>;
+/// Type alias for `Encryptable<Secret<String>>` used for `name` field
+pub type EncryptableName = Encryptable<Secret<String>>;
+/// Type alias for `Encryptable<Secret<String>>` used for `email` field
+pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>;
#[cfg(test)]
mod crypto_tests {
diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index df410a1d5f..9024ffe79d 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -8,10 +8,11 @@ readme = "README.md"
license.workspace = true
[features]
-default = ["kv_store", "v1"]
+default = ["kv_store", "v1"]
kv_store = []
v1 = []
v2 = []
+customer_v2 = []
merchant_account_v2 = []
payment_v2 = []
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index 65348fd493..2ce3ecca53 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -15,6 +15,7 @@ payouts = ["api_models/payouts"]
frm = ["api_models/frm"]
v2 = ["api_models/v2", "diesel_models/v2"]
v1 = ["api_models/v1", "diesel_models/v1"]
+customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"]
merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2"]
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
new file mode 100644
index 0000000000..ef7c816b0d
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -0,0 +1,197 @@
+use api_models::customers::CustomerRequestWithEncryption;
+use common_utils::{
+ crypto, date_time,
+ encryption::Encryption,
+ errors::{CustomResult, ValidationError},
+ id_type, pii,
+ types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
+};
+use diesel_models::customers::CustomerUpdateInternal;
+use error_stack::ResultExt;
+use masking::{PeekInterface, Secret};
+use time::PrimitiveDateTime;
+
+use crate::type_encryption as types;
+// use api_models::payments::Address;
+// use crate::type_encryption::AsyncLift;
+
+pub enum SoftDeleteStatus {
+ Active,
+ Redacted,
+}
+
+#[derive(Clone, Debug)]
+pub struct Customer {
+ pub id: Option<i32>,
+ pub customer_id: id_type::CustomerId,
+ pub merchant_id: String,
+ pub name: crypto::OptionalEncryptableName,
+ pub email: crypto::OptionalEncryptableEmail,
+ pub phone: crypto::OptionalEncryptablePhone,
+ pub phone_country_code: Option<String>,
+ pub description: Option<String>,
+ pub created_at: PrimitiveDateTime,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub modified_at: PrimitiveDateTime,
+ pub connector_customer: Option<serde_json::Value>,
+ pub address_id: Option<String>,
+ pub default_payment_method_id: Option<String>,
+ pub updated_by: Option<String>,
+ // pub default_billing_address: Option<Address>,
+ // pub default_shipping_address: Option<Address>,
+ // pub merchant_reference_id: Option<id_type::CustomerId>,
+ // pub status: Option<SoftDeleteStatus>
+}
+
+#[async_trait::async_trait]
+impl super::behaviour::Conversion for Customer {
+ type DstType = diesel_models::customers::Customer;
+ type NewDstType = diesel_models::customers::CustomerNew;
+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
+ Ok(diesel_models::customers::Customer {
+ id: self.id.ok_or(ValidationError::MissingRequiredField {
+ field_name: "id".to_string(),
+ })?,
+ customer_id: self.customer_id,
+ merchant_id: self.merchant_id,
+ name: self.name.map(|value| value.into()),
+ email: self.email.map(|value| value.into()),
+ phone: self.phone.map(Encryption::from),
+ phone_country_code: self.phone_country_code,
+ description: self.description,
+ created_at: self.created_at,
+ metadata: self.metadata,
+ modified_at: self.modified_at,
+ connector_customer: self.connector_customer,
+ address_id: self.address_id,
+ default_payment_method_id: self.default_payment_method_id,
+ updated_by: self.updated_by,
+ })
+ }
+
+ async fn convert_back(
+ state: &KeyManagerState,
+ item: Self::DstType,
+ key: &Secret<Vec<u8>>,
+ _key_store_ref_id: String,
+ ) -> CustomResult<Self, ValidationError>
+ where
+ Self: Sized,
+ {
+ let decrypted = types::batch_decrypt(
+ state,
+ CustomerRequestWithEncryption::to_encryptable(CustomerRequestWithEncryption {
+ name: item.name.clone(),
+ phone: item.phone.clone(),
+ email: item.email.clone(),
+ }),
+ Identifier::Merchant(item.merchant_id.clone()),
+ key.peek(),
+ )
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting customer data".to_string(),
+ })?;
+ let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted)
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting customer data".to_string(),
+ })?;
+
+ Ok(Self {
+ id: Some(item.id),
+ customer_id: item.customer_id,
+ merchant_id: item.merchant_id,
+ name: encryptable_customer.name,
+ email: encryptable_customer.email,
+ phone: encryptable_customer.phone,
+ phone_country_code: item.phone_country_code,
+ description: item.description,
+ created_at: item.created_at,
+ metadata: item.metadata,
+ modified_at: item.modified_at,
+ connector_customer: item.connector_customer,
+ address_id: item.address_id,
+ default_payment_method_id: item.default_payment_method_id,
+ updated_by: item.updated_by,
+ })
+ }
+
+ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
+ let now = date_time::now();
+ Ok(diesel_models::customers::CustomerNew {
+ customer_id: self.customer_id,
+ merchant_id: self.merchant_id,
+ name: self.name.map(Encryption::from),
+ email: self.email.map(Encryption::from),
+ phone: self.phone.map(Encryption::from),
+ description: self.description,
+ phone_country_code: self.phone_country_code,
+ metadata: self.metadata,
+ created_at: now,
+ modified_at: now,
+ connector_customer: self.connector_customer,
+ address_id: self.address_id,
+ updated_by: self.updated_by,
+ })
+ }
+}
+
+#[derive(Clone, Debug)]
+pub enum CustomerUpdate {
+ Update {
+ name: crypto::OptionalEncryptableName,
+ email: crypto::OptionalEncryptableEmail,
+ phone: Box<crypto::OptionalEncryptablePhone>,
+ description: Option<String>,
+ phone_country_code: Option<String>,
+ metadata: Option<pii::SecretSerdeValue>,
+ connector_customer: Option<serde_json::Value>,
+ address_id: Option<String>,
+ },
+ ConnectorCustomer {
+ connector_customer: Option<serde_json::Value>,
+ },
+ UpdateDefaultPaymentMethod {
+ default_payment_method_id: Option<Option<String>>,
+ },
+}
+
+impl From<CustomerUpdate> for CustomerUpdateInternal {
+ fn from(customer_update: CustomerUpdate) -> Self {
+ match customer_update {
+ CustomerUpdate::Update {
+ name,
+ email,
+ phone,
+ description,
+ phone_country_code,
+ metadata,
+ connector_customer,
+ address_id,
+ } => Self {
+ name: name.map(Encryption::from),
+ email: email.map(Encryption::from),
+ phone: phone.map(Encryption::from),
+ description,
+ phone_country_code,
+ metadata,
+ connector_customer,
+ modified_at: Some(date_time::now()),
+ address_id,
+ ..Default::default()
+ },
+ CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
+ connector_customer,
+ modified_at: Some(date_time::now()),
+ ..Default::default()
+ },
+ CustomerUpdate::UpdateDefaultPaymentMethod {
+ default_payment_method_id,
+ } => Self {
+ default_payment_method_id,
+ modified_at: Some(date_time::now()),
+ ..Default::default()
+ },
+ }
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index fa3db72b08..387c024df1 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -1,4 +1,5 @@
pub mod api;
+pub mod customer;
pub mod errors;
pub mod mandates;
pub mod merchant_account;
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index 07bf323819..bf8a1b9caa 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -255,11 +255,15 @@ impl super::behaviour::Conversion for MerchantAccount {
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
- .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek()))
+ .async_lift(|inner| {
+ decrypt_optional(state, inner, identifier.clone(), key.peek())
+ })
.await?,
merchant_details: item
.merchant_details
- .async_lift(|inner| decrypt(state, inner, identifier.clone(), key.peek()))
+ .async_lift(|inner| {
+ decrypt_optional(state, inner, identifier.clone(), key.peek())
+ })
.await?,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index ece60ac6de..2338f5edc1 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -542,14 +542,23 @@ impl behaviour::Conversion for PaymentIntent {
}
async fn convert_back(
+ state: &KeyManagerState,
storage_model: Self::DstType,
key: &masking::Secret<Vec<u8>>,
+ key_store_ref_id: String,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
- let inner_decrypt = |inner| decrypt(inner, key.peek());
+ let inner_decrypt = |inner| {
+ decrypt_optional(
+ state,
+ inner,
+ common_utils::types::keymanager::Identifier::Merchant(key_store_ref_id.clone()),
+ key.peek(),
+ )
+ };
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 743a94c942..62ddb0067b 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -32,6 +32,7 @@ recon = ["email", "api_models/recon"]
retry = []
v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2"]
v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1"]
+customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"]
merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2", "hyperswitch_domain_models/merchant_account_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"]
diff --git a/crates/router/src/compatibility/stripe.rs b/crates/router/src/compatibility/stripe.rs
index 5d3fd5b6cd..7946bb0d9e 100644
--- a/crates/router/src/compatibility/stripe.rs
+++ b/crates/router/src/compatibility/stripe.rs
@@ -4,12 +4,16 @@ pub mod payment_intents;
pub mod refunds;
pub mod setup_intents;
pub mod webhooks;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use actix_web::{web, Scope};
pub mod errors;
-
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use crate::routes;
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
pub struct StripeApis;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl StripeApis {
pub fn server(state: routes::AppState) -> Scope {
let max_depth = 10;
diff --git a/crates/router/src/compatibility/stripe/app.rs b/crates/router/src/compatibility/stripe/app.rs
index 5b4be4dde0..9ef29596cf 100644
--- a/crates/router/src/compatibility/stripe/app.rs
+++ b/crates/router/src/compatibility/stripe/app.rs
@@ -1,6 +1,8 @@
use actix_web::{web, Scope};
-use super::{customers::*, payment_intents::*, refunds::*, setup_intents::*, webhooks::*};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use super::customers::*;
+use super::{payment_intents::*, refunds::*, setup_intents::*, webhooks::*};
use crate::routes::{self, mandates, webhooks};
pub struct PaymentIntents;
@@ -76,6 +78,7 @@ impl Refunds {
pub struct Customers;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl Customers {
pub fn server(config: routes::AppState) -> Scope {
web::scope("/customers")
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs
index 264f205c90..d07f08ef40 100644
--- a/crates/router/src/compatibility/stripe/customers.rs
+++ b/crates/router/src/compatibility/stripe/customers.rs
@@ -1,9 +1,14 @@
pub mod types;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use actix_web::{web, HttpRequest, HttpResponse};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::id_type;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use error_stack::report;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use router_env::{instrument, tracing, Flow};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use crate::{
compatibility::{stripe::errors, wrap},
core::{api_locking, customers, payment_methods::cards},
@@ -12,6 +17,7 @@ use crate::{
types::api::{customers as customer_types, payment_methods},
};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customer_create(
state: web::Data<routes::AppState>,
@@ -52,15 +58,15 @@ pub async fn customer_create(
))
.await
}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customer_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
- let payload = customer_types::CustomerId {
- customer_id: path.into_inner(),
- };
+ let payload = customer_types::CustomerId::new_customer_id_struct(path.into_inner());
let flow = Flow::CustomersRetrieve;
@@ -86,6 +92,8 @@ pub async fn customer_retrieve(
))
.await
}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customer_update(
state: web::Data<routes::AppState>,
@@ -129,15 +137,15 @@ pub async fn customer_update(
))
.await
}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customer_delete(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
- let payload = customer_types::CustomerId {
- customer_id: path.into_inner(),
- };
+ let payload = customer_types::CustomerId::new_customer_id_struct(path.into_inner());
let flow = Flow::CustomersDelete;
@@ -163,6 +171,8 @@ pub async fn customer_delete(
))
.await
}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<routes::AppState>,
diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs
index 0e1a5d1a79..e2acc7b17b 100644
--- a/crates/router/src/compatibility/stripe/customers/types.rs
+++ b/crates/router/src/compatibility/stripe/customers/types.rs
@@ -1,17 +1,17 @@
use std::{convert::From, default::Default};
use api_models::{payment_methods as api_types, payments};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use common_utils::{crypto::Encryptable, date_time};
use common_utils::{
- crypto::Encryptable,
- date_time, id_type,
+ id_type,
pii::{self, Email},
};
use serde::{Deserialize, Serialize};
-use crate::{
- logger,
- types::{api, api::enums as api_enums},
-};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use crate::logger;
+use crate::types::{api, api::enums as api_enums};
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct Shipping {
@@ -117,6 +117,7 @@ impl From<StripeAddressDetails> for payments::AddressDetails {
}
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl From<CreateCustomerRequest> for api::CustomerRequest {
fn from(req: CreateCustomerRequest) -> Self {
Self {
@@ -132,6 +133,7 @@ impl From<CreateCustomerRequest> for api::CustomerRequest {
}
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl From<CustomerUpdateRequest> for api::CustomerRequest {
fn from(req: CustomerUpdateRequest) -> Self {
Self {
@@ -146,6 +148,7 @@ impl From<CustomerUpdateRequest> for api::CustomerRequest {
}
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl From<api::CustomerResponse> for CreateCustomerResponse {
fn from(cust: api::CustomerResponse) -> Self {
let cust = cust.into_inner();
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index c0dc969db1..d34e2f081e 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -1,28 +1,36 @@
use api_models::customers::CustomerRequestWithEmail;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use common_utils::{crypto::Encryptable, ext_traits::OptionExt};
use common_utils::{
- crypto::Encryptable,
errors::ReportSwitchExt,
- ext_traits::OptionExt,
- types::keymanager::{Identifier, ToEncryptable},
+ ext_traits::AsyncExt,
+ id_type,
+ types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use error_stack::{report, ResultExt};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use hyperswitch_domain_models::type_encryption::encrypt;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use masking::{Secret, SwitchStrategy};
use router_env::{instrument, tracing};
use crate::{
- core::{
- errors::{self, StorageErrorExt},
- payment_methods::cards,
- },
+ core::errors::{self, StorageErrorExt},
+ db::StorageInterface,
pii::PeekInterface,
- routes::{metrics, SessionState},
+ routes::SessionState,
services,
types::{
api::customers,
domain::{self, types},
- storage::{self, enums},
+ transformers::ForeignFrom,
},
+};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use crate::{
+ core::payment_methods::cards,
+ routes::metrics,
+ types::storage::{self, enums},
utils::CustomerAddress,
};
@@ -33,122 +41,329 @@ pub async fn create_customer(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- mut customer_data: customers::CustomerRequest,
+ customer_data: customers::CustomerRequest,
) -> errors::CustomerResponse<customers::CustomerResponse> {
- let db = state.store.as_ref();
- let customer_id = customer_data
- .customer_id
- .clone()
- .unwrap_or_else(common_utils::generate_customer_id_of_default_length);
+ let db: &dyn StorageInterface = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+
+ let merchant_reference_id = customer_data.get_merchant_reference_id();
let merchant_id = &merchant_account.merchant_id;
- merchant_id.clone_into(&mut customer_data.merchant_id);
- let key_manager_state = &(&state).into();
+
+ let merchant_reference_id_customer = MerchantReferenceIdForCustomer {
+ customer_id: merchant_reference_id.as_ref(),
+ merchant_id,
+ merchant_account: &merchant_account,
+ key_store: &key_store,
+ key_manager_state,
+ };
// We first need to validate whether the customer with the given customer id already exists
// this may seem like a redundant db call, as the insert_customer will anyway return this error
//
// Consider a scenario where the address is inserted and then when inserting the customer,
// it errors out, now the address that was inserted is not deleted
- match db
- .find_customer_by_customer_id_merchant_id(
- key_manager_state,
- &customer_id,
- merchant_id,
- &key_store,
- merchant_account.storage_scheme,
- )
- .await
- {
- Err(err) => {
- if !err.current_context().is_db_not_found() {
- Err(err).switch()
- } else {
- Ok(())
- }
- }
- Ok(_) => Err(report!(
- errors::CustomersErrorResponse::CustomerAlreadyExists
- )),
- }?;
- let key = key_store.key.get_inner().peek();
- let address = if let Some(addr) = &customer_data.address {
- let customer_address: api_models::payments::AddressDetails = addr.clone();
-
- let address = customer_data
- .get_domain_address(
- &state,
- customer_address,
- merchant_id,
- &customer_id,
- key,
- merchant_account.storage_scheme,
- )
- .await
- .switch()
- .attach_printable("Failed while encrypting address")?;
+ merchant_reference_id_customer
+ .verify_if_customer_not_present_by_optional_merchant_reference_id(db)
+ .await?;
- Some(
- db.insert_address_for_customers(key_manager_state, address, &key_store)
- .await
- .switch()
- .attach_printable("Failed while inserting new address")?,
+ let domain_customer = customer_data
+ .create_domain_model_from_request(
+ db,
+ &key_store,
+ &merchant_reference_id,
+ &merchant_account,
+ key_manager_state,
+ &state,
)
- } else {
- None
- };
-
- let encrypted_data = types::batch_encrypt(
- &(&state).into(),
- CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
- name: customer_data.name.clone(),
- email: customer_data.email.clone(),
- phone: customer_data.phone.clone(),
- }),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key,
- )
- .await
- .switch()
- .attach_printable("Failed while encrypting Customer")?;
- let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
- .change_context(errors::CustomersErrorResponse::InternalServerError)?;
- let new_customer = domain::Customer {
- customer_id: customer_id.to_owned(),
- merchant_id: merchant_id.to_string(),
- name: encryptable_customer.name,
- email: encryptable_customer.email,
- phone: encryptable_customer.phone,
- description: customer_data.description,
- phone_country_code: customer_data.phone_country_code,
- metadata: customer_data.metadata,
- id: None,
- connector_customer: None,
- address_id: address.clone().map(|addr| addr.address_id),
- created_at: common_utils::date_time::now(),
- modified_at: common_utils::date_time::now(),
- default_payment_method_id: None,
- updated_by: None,
- };
+ .await?;
let customer = db
.insert_customer(
+ domain_customer,
key_manager_state,
- new_customer,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?;
- let address_details = address.map(api_models::payments::AddressDetails::from);
+ customer_data.generate_response(&customer)
+}
- Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::from((customer, address_details)),
- ))
+#[async_trait::async_trait]
+trait CustomerCreateBridge {
+ async fn create_domain_model_from_request<'a>(
+ &'a self,
+ db: &'a dyn StorageInterface,
+ key_store: &'a domain::MerchantKeyStore,
+ merchant_reference_id: &'a Option<id_type::CustomerId>,
+ merchant_account: &'a domain::MerchantAccount,
+ key_manager_state: &'a KeyManagerState,
+ state: &'a SessionState,
+ ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>;
+
+ fn generate_response<'a>(
+ &'a self,
+ customer: &'a domain::Customer,
+ ) -> errors::CustomerResponse<customers::CustomerResponse>;
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+#[async_trait::async_trait]
+impl CustomerCreateBridge for customers::CustomerRequest {
+ async fn create_domain_model_from_request<'a>(
+ &'a self,
+ db: &'a dyn StorageInterface,
+ key_store: &'a domain::MerchantKeyStore,
+ merchant_reference_id: &'a Option<id_type::CustomerId>,
+ merchant_account: &'a domain::MerchantAccount,
+ key_manager_state: &'a KeyManagerState,
+ state: &'a SessionState,
+ ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
+ // Setting default billing address to Db
+ let address = self.get_address();
+ let merchant_id = &merchant_account.merchant_id;
+ let key = key_store.key.get_inner().peek();
+
+ let customer_billing_address_struct = AddressStructForDbEntry {
+ address: address.as_ref(),
+ customer_data: self,
+ merchant_id,
+ customer_id: merchant_reference_id.as_ref(),
+ storage_scheme: merchant_account.storage_scheme,
+ key_store,
+ key_manager_state,
+ state,
+ };
+
+ let address_from_db = customer_billing_address_struct
+ .encrypt_customer_address_and_set_to_db(db)
+ .await?;
+
+ let encrypted_data = types::batch_encrypt(
+ key_manager_state,
+ CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
+ name: self.name.clone(),
+ email: self.email.clone(),
+ phone: self.phone.clone(),
+ }),
+ Identifier::Merchant(key_store.merchant_id.clone()),
+ key,
+ )
+ .await
+ .switch()
+ .attach_printable("Failed while encrypting Customer")?;
+
+ let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
+ .change_context(errors::CustomersErrorResponse::InternalServerError)?;
+
+ Ok(domain::Customer {
+ customer_id: merchant_reference_id
+ .to_owned()
+ .ok_or(errors::CustomersErrorResponse::InternalServerError)?,
+ merchant_id: merchant_id.to_string(),
+ name: encryptable_customer.name,
+ email: encryptable_customer.email,
+ phone: encryptable_customer.phone,
+ description: self.description.clone(),
+ phone_country_code: self.phone_country_code.clone(),
+ metadata: self.metadata.clone(),
+ id: None,
+ connector_customer: None,
+ address_id: address_from_db.clone().map(|addr| addr.address_id),
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ default_payment_method_id: None,
+ updated_by: None,
+ })
+ }
+
+ fn generate_response<'a>(
+ &'a self,
+ customer: &'a domain::Customer,
+ ) -> errors::CustomerResponse<customers::CustomerResponse> {
+ let address = self.get_address();
+ let address_details = address.map(api_models::payments::AddressDetails::from);
+
+ Ok(services::ApplicationResponse::Json(
+ customers::CustomerResponse::foreign_from((customer.clone(), address_details)),
+ ))
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+#[async_trait::async_trait]
+impl CustomerCreateBridge for customers::CustomerRequest {
+ async fn create_domain_model_from_request<'a>(
+ &'a self,
+ _db: &'a dyn StorageInterface,
+ key_store: &'a domain::MerchantKeyStore,
+ merchant_reference_id: &'a Option<id_type::CustomerId>,
+ merchant_account: &'a domain::MerchantAccount,
+ key_state: &'a KeyManagerState,
+ _state: &'a SessionState,
+ ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
+ let _default_customer_billing_address = self.get_default_customer_billing_address();
+ let _default_customer_shipping_address = self.get_default_customer_shipping_address();
+ let merchant_id = merchant_account.merchant_id.clone();
+ let key = key_store.key.get_inner().peek();
+
+ let encrypted_data = types::batch_encrypt(
+ key_state,
+ CustomerRequestWithEmail::to_encryptable(CustomerRequestWithEmail {
+ name: Some(self.name.clone()),
+ email: Some(self.email.clone()),
+ phone: self.phone.clone(),
+ }),
+ Identifier::Merchant(key_store.merchant_id.clone()),
+ key,
+ )
+ .await
+ .switch()
+ .attach_printable("Failed while encrypting Customer")?;
+
+ let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
+ .change_context(errors::CustomersErrorResponse::InternalServerError)?;
+
+ Ok(domain::Customer {
+ customer_id: merchant_reference_id
+ .to_owned()
+ .ok_or(errors::CustomersErrorResponse::InternalServerError)?, // doing this to make it compile, will remove once we start moving to domain models
+ merchant_id: merchant_id.to_string(),
+ name: encryptable_customer.name,
+ email: encryptable_customer.email,
+ phone: encryptable_customer.phone,
+ description: self.description.clone(),
+ phone_country_code: self.phone_country_code.clone(),
+ metadata: self.metadata.clone(),
+ id: None,
+ connector_customer: None,
+ address_id: None,
+ created_at: common_utils::date_time::now(),
+ modified_at: common_utils::date_time::now(),
+ default_payment_method_id: None,
+ updated_by: None,
+ // default_billing_address: default_customer_billing_address,
+ // default_shipping_address: default_customer_shipping_address,
+ // merchant_reference_id,
+ // status: Some(customer_domain::SoftDeleteStatus::Active)
+ })
+ }
+
+ fn generate_response<'a>(
+ &'a self,
+ customer: &'a domain::Customer,
+ ) -> errors::CustomerResponse<customers::CustomerResponse> {
+ Ok(services::ApplicationResponse::Json(
+ customers::CustomerResponse::foreign_from(customer.clone()),
+ ))
+ }
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+struct AddressStructForDbEntry<'a> {
+ address: Option<&'a api_models::payments::AddressDetails>,
+ customer_data: &'a customers::CustomerRequest,
+ merchant_id: &'a str,
+ customer_id: Option<&'a id_type::CustomerId>,
+ storage_scheme: common_enums::MerchantStorageScheme,
+ key_store: &'a domain::MerchantKeyStore,
+ key_manager_state: &'a KeyManagerState,
+ state: &'a SessionState,
+}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+impl<'a> AddressStructForDbEntry<'a> {
+ async fn encrypt_customer_address_and_set_to_db(
+ &self,
+ db: &dyn StorageInterface,
+ ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> {
+ let encrypted_customer_address = self
+ .address
+ .async_map(|addr| async {
+ self.customer_data
+ .get_domain_address(
+ self.state,
+ addr.clone(),
+ self.merchant_id,
+ self.customer_id
+ .ok_or(errors::CustomersErrorResponse::InternalServerError)?, // should we raise error since in v1 appilcation is supposed to have this id or generate it at this point.
+ self.key_store.key.get_inner().peek(),
+ self.storage_scheme,
+ )
+ .await
+ .switch()
+ .attach_printable("Failed while encrypting address")
+ })
+ .await
+ .transpose()?;
+
+ encrypted_customer_address
+ .async_map(|encrypt_add| async {
+ db.insert_address_for_customers(self.key_manager_state, encrypt_add, self.key_store)
+ .await
+ .switch()
+ .attach_printable("Failed while inserting new address")
+ })
+ .await
+ .transpose()
+ }
+}
+
+struct MerchantReferenceIdForCustomer<'a> {
+ customer_id: Option<&'a id_type::CustomerId>,
+ merchant_id: &'a str,
+ merchant_account: &'a domain::MerchantAccount,
+ key_store: &'a domain::MerchantKeyStore,
+ key_manager_state: &'a KeyManagerState,
+}
+
+impl<'a> MerchantReferenceIdForCustomer<'a> {
+ async fn verify_if_customer_not_present_by_optional_merchant_reference_id(
+ &self,
+ db: &dyn StorageInterface,
+ ) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> {
+ self.customer_id
+ .async_map(|cust| async {
+ self.verify_if_customer_not_present_by_merchant_reference(cust, db)
+ .await
+ })
+ .await
+ .transpose()
+ }
+
+ async fn verify_if_customer_not_present_by_merchant_reference(
+ &self,
+ cus: &'a id_type::CustomerId,
+ db: &dyn StorageInterface,
+ ) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> {
+ match db
+ .find_customer_by_customer_id_merchant_id(
+ self.key_manager_state,
+ cus,
+ self.merchant_id,
+ self.key_store,
+ self.merchant_account.storage_scheme,
+ )
+ .await
+ {
+ Err(err) => {
+ if !err.current_context().is_db_not_found() {
+ Err(err).switch()
+ } else {
+ Ok(())
+ }
+ }
+ Ok(_) => Err(report!(
+ errors::CustomersErrorResponse::CustomerAlreadyExists
+ )),
+ }
+ }
}
+#[cfg(all(any(feature = "v1", feature = "v2",), not(feature = "customer_v2")))]
#[instrument(skip(state))]
pub async fn retrieve_customer(
state: SessionState,
@@ -177,10 +392,11 @@ pub async fn retrieve_customer(
None => None,
};
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::from((response, address)),
+ customers::CustomerResponse::foreign_from((response, address)),
))
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip(state))]
pub async fn list_customers(
state: SessionState,
@@ -196,12 +412,13 @@ pub async fn list_customers(
let customers = domain_customers
.into_iter()
- .map(|domain_customer| customers::CustomerResponse::from((domain_customer, None)))
+ .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None)))
.collect();
Ok(services::ApplicationResponse::Json(customers))
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all)]
pub async fn delete_customer(
state: SessionState,
@@ -371,6 +588,10 @@ pub async fn delete_customer(
Ok(services::ApplicationResponse::Json(response))
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2", feature = "oltp"),
+ not(feature = "customer_v2")
+))]
#[instrument(skip(state))]
pub async fn update_customer(
state: SessionState,
@@ -497,7 +718,7 @@ pub async fn update_customer(
.switch()?;
Ok(services::ApplicationResponse::Json(
- customers::CustomerResponse::from((response, update_customer.address)),
+ customers::CustomerResponse::foreign_from((response, update_customer.address)),
))
}
diff --git a/crates/router/src/core/errors/customers_error_response.rs b/crates/router/src/core/errors/customers_error_response.rs
index e5b6d4a526..5bda9a69a8 100644
--- a/crates/router/src/core/errors/customers_error_response.rs
+++ b/crates/router/src/core/errors/customers_error_response.rs
@@ -33,3 +33,5 @@ impl actix_web::ResponseError for CustomersErrorResponse {
.error_response()
}
}
+
+// should be removed hola bola
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index dbbd73e7dd..e9cddebe09 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -233,13 +233,17 @@ pub async fn get_customer_mandates(
) -> RouterResponse<Vec<mandates::MandateResponse>> {
let mandates = state
.store
- .find_mandate_by_merchant_id_customer_id(&merchant_account.merchant_id, &req.customer_id)
+ .find_mandate_by_merchant_id_customer_id(
+ &merchant_account.merchant_id,
+ &req.get_merchant_reference_id(),
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while finding mandate: merchant_id: {}, customer_id: {:?}",
- merchant_account.merchant_id, req.customer_id
+ merchant_account.merchant_id,
+ req.get_merchant_reference_id()
)
})?;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index aa630ad983..183ee97ede 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1675,7 +1675,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
updated_by: None,
};
metrics::CUSTOMER_CREATED.add(&metrics::CONTEXT, 1, &[]);
- db.insert_customer(key_manager_state, new_customer, key_store, storage_scheme)
+ db.insert_customer(new_customer, key_manager_state, key_store, storage_scheme)
.await
}
})
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index f264a056f6..c3fc3adcb2 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -44,6 +44,7 @@ use crate::{
self,
enums::{self, IntentStatus},
},
+ transformers::ForeignTryFrom,
},
utils::{self, OptionExt},
};
@@ -644,7 +645,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
let customer_id = payment_data.payment_intent.customer_id.clone();
let raw_customer_details = customer
- .map(|customer| CustomerData::try_from(customer.clone()))
+ .map(|customer| CustomerData::foreign_try_from(customer.clone()))
.transpose()?;
let session_state = state.session_state();
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index f95ec0d014..d7fcdf6e14 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -30,6 +30,7 @@ use crate::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt},
+ transformers::ForeignTryFrom,
},
utils::OptionExt,
};
@@ -785,9 +786,9 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
}
}
-impl TryFrom<domain::Customer> for CustomerData {
+impl ForeignTryFrom<domain::Customer> for CustomerData {
type Error = errors::ApiErrorResponse;
- fn try_from(value: domain::Customer) -> Result<Self, Self::Error> {
+ fn foreign_try_from(value: domain::Customer) -> Result<Self, Self::Error> {
Ok(Self {
name: value.name.map(|name| name.into_inner()),
email: value.email.map(Email::from),
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 6cda7b2843..c3aa128f2f 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -664,8 +664,8 @@ pub async fn get_or_create_customer_details(
Ok(Some(
db.insert_customer(
- key_manager_state,
customer,
+ key_manager_state,
key_store,
merchant_account.storage_scheme,
)
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 1bfda65852..4bb29c3741 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -1,6 +1,7 @@
use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState};
use error_stack::ResultExt;
use futures::future::try_join_all;
+use hyperswitch_domain_models::customer;
use router_env::{instrument, tracing};
use super::MockDb;
@@ -18,7 +19,7 @@ use crate::{
#[async_trait::async_trait]
pub trait CustomerInterface
where
- domain::Customer:
+ customer::Customer:
Conversion<DstType = storage_types::Customer, NewDstType = storage_types::CustomerNew>,
{
async fn delete_customer_by_customer_id_merchant_id(
@@ -34,7 +35,7 @@ where
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Option<domain::Customer>, errors::StorageError>;
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_customer_id_merchant_id(
@@ -42,11 +43,11 @@ where
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: String,
- customer: domain::Customer,
+ customer: customer::Customer,
customer_update: storage_types::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError>;
+ ) -> CustomResult<customer::Customer, errors::StorageError>;
async fn find_customer_by_customer_id_merchant_id(
&self,
@@ -55,22 +56,22 @@ where
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError>;
+ ) -> CustomResult<customer::Customer, errors::StorageError>;
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Customer>, errors::StorageError>;
+ ) -> CustomResult<Vec<customer::Customer>, errors::StorageError>;
async fn insert_customer(
&self,
+ customer_data: customer::Customer,
state: &KeyManagerState,
- customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError>;
+ ) -> CustomResult<customer::Customer, errors::StorageError>;
}
#[cfg(feature = "kv_store")]
@@ -79,6 +80,7 @@ mod storage {
use diesel_models::kv;
use error_stack::{report, ResultExt};
use futures::future::try_join_all;
+ use hyperswitch_domain_models::customer;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::{
@@ -114,7 +116,7 @@ mod storage {
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::Customer::find_optional_by_customer_id_merchant_id(
@@ -181,11 +183,11 @@ mod storage {
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: String,
- customer: domain::Customer,
+ customer: customer::Customer,
customer_update: storage_types::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let customer = Conversion::convert(customer)
.await
@@ -265,7 +267,7 @@ mod storage {
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::Customer::find_by_customer_id_merchant_id(
@@ -303,7 +305,7 @@ mod storage {
}
}?;
- let result: domain::Customer = customer
+ let result: customer::Customer = customer
.convert(
state,
key_store.key.get_inner(),
@@ -327,7 +329,7 @@ mod storage {
state: &KeyManagerState,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
+ ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let encrypted_customers =
@@ -355,11 +357,11 @@ mod storage {
#[instrument(skip_all)]
async fn insert_customer(
&self,
+ customer_data: customer::Customer,
state: &KeyManagerState,
- customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
let customer_id = customer_data.customer_id.clone();
let merchant_id = customer_data.merchant_id.clone();
let mut new_customer = customer_data
@@ -453,6 +455,7 @@ mod storage {
use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState};
use error_stack::{report, ResultExt};
use futures::future::try_join_all;
+ use hyperswitch_domain_models::customer;
use masking::PeekInterface;
use router_env::{instrument, tracing};
@@ -483,9 +486,9 @@ mod storage {
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let maybe_customer: Option<domain::Customer> =
+ let maybe_customer: Option<customer::Customer> =
storage_types::Customer::find_optional_by_customer_id_merchant_id(
&conn,
customer_id,
@@ -518,11 +521,11 @@ mod storage {
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: String,
- _customer: domain::Customer,
+ _customer: customer::Customer,
customer_update: storage_types::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Customer::update_by_customer_id_merchant_id(
&conn,
@@ -548,9 +551,9 @@ mod storage {
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let customer: domain::Customer =
+ let customer: customer::Customer =
storage_types::Customer::find_by_customer_id_merchant_id(
&conn,
customer_id,
@@ -578,7 +581,7 @@ mod storage {
state: &KeyManagerState,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
+ ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let encrypted_customers =
@@ -602,11 +605,11 @@ mod storage {
#[instrument(skip_all)]
async fn insert_customer(
&self,
+ customer_data: customer::Customer,
state: &KeyManagerState,
- customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
customer_data
.construct_new()
@@ -655,7 +658,7 @@ impl CustomerInterface for MockDb {
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
+ ) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
let customers = self.customers.lock().await;
let customer = customers
.iter()
@@ -682,7 +685,7 @@ impl CustomerInterface for MockDb {
state: &KeyManagerState,
merchant_id: &str,
key_store: &domain::MerchantKeyStore,
- ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
+ ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let customers = self.customers.lock().await;
let customers = try_join_all(
@@ -712,11 +715,11 @@ impl CustomerInterface for MockDb {
_state: &KeyManagerState,
_customer_id: id_type::CustomerId,
_merchant_id: String,
- _customer: domain::Customer,
+ _customer: customer::Customer,
_customer_update: storage_types::CustomerUpdate,
_key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
@@ -728,7 +731,7 @@ impl CustomerInterface for MockDb {
_merchant_id: &str,
_key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
@@ -736,11 +739,11 @@ impl CustomerInterface for MockDb {
#[allow(clippy::panic)]
async fn insert_customer(
&self,
+ customer_data: customer::Customer,
state: &KeyManagerState,
- customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
- ) -> CustomResult<domain::Customer, errors::StorageError> {
+ ) -> CustomResult<customer::Customer, errors::StorageError> {
let mut customers = self.customers.lock().await;
let customer = Conversion::convert(customer_data)
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 7062ea141e..b9d2f0907a 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -425,13 +425,13 @@ impl CustomerInterface for KafkaStore {
async fn insert_customer(
&self,
- state: &KeyManagerState,
customer_data: domain::Customer,
+ state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
- .insert_customer(state, customer_data, key_store, storage_scheme)
+ .insert_customer(customer_data, state, key_store, storage_scheme)
.await
}
}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 13fffc8204..530f3f98ce 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -130,7 +130,11 @@ pub fn mk_app(
.service(routes::Mandates::server(state.clone()))
}
- #[cfg(feature = "oltp")]
+ #[cfg(all(
+ feature = "oltp",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2")
+ ))]
{
server_app = server_app
.service(routes::EphemeralKey::server(state.clone()))
@@ -165,7 +169,11 @@ pub fn mk_app(
.service(routes::PayoutLink::server(state.clone()));
}
- #[cfg(feature = "stripe")]
+ #[cfg(all(
+ feature = "stripe",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2")
+ ))]
{
server_app = server_app.service(routes::StripeApis::server(state.clone()));
}
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index f21c11c0aa..df7b64e6e8 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -67,7 +67,11 @@ pub use self::app::{
pub use self::app::{Blocklist, Routing, Verify, WebhookEvents};
#[cfg(feature = "payouts")]
pub use self::app::{PayoutLink, Payouts};
-#[cfg(feature = "stripe")]
+#[cfg(all(
+ feature = "stripe",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2")
+))]
pub use super::compatibility::stripe::StripeApis;
#[cfg(feature = "olap")]
pub use crate::analytics::routes::{self as analytics, Analytics};
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index f6380d3f9c..4f79670cac 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -26,6 +26,14 @@ use super::dummy_connector::*;
use super::payout_link::*;
#[cfg(feature = "payouts")]
use super::payouts::*;
+#[cfg(all(
+ feature = "oltp",
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2")
+))]
+use super::pm_auth;
+#[cfg(feature = "oltp")]
+use super::poll::retrieve_poll_status;
#[cfg(feature = "olap")]
use super::routing as cloud_routing;
#[cfg(feature = "olap")]
@@ -42,8 +50,6 @@ use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*};
use super::{currency, payment_methods::*};
#[cfg(feature = "oltp")]
use super::{ephemeral_key::*, webhooks::*};
-#[cfg(feature = "oltp")]
-use super::{pm_auth, poll::retrieve_poll_status};
#[cfg(feature = "olap")]
pub use crate::analytics::opensearch::OpenSearchClient;
#[cfg(feature = "olap")]
@@ -790,7 +796,27 @@ impl Routing {
pub struct Customers;
-#[cfg(any(feature = "olap", feature = "oltp"))]
+#[cfg(all(
+ feature = "v2",
+ feature = "customer_v2",
+ any(feature = "olap", feature = "oltp")
+))]
+impl Customers {
+ pub fn server(state: AppState) -> Scope {
+ let mut route = web::scope("/v2/customers").app_data(web::Data::new(state));
+ #[cfg(all(feature = "oltp", feature = "v2", feature = "customer_v2"))]
+ {
+ route = route.service(web::resource("").route(web::post().to(customers_create)))
+ }
+ route
+ }
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "customer_v2"),
+ any(feature = "olap", feature = "oltp")
+))]
impl Customers {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/customers").app_data(web::Data::new(state));
@@ -902,7 +928,11 @@ impl Payouts {
pub struct PaymentMethods;
-#[cfg(any(feature = "olap", feature = "oltp"))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ any(feature = "olap", feature = "oltp"),
+ not(feature = "customer_v2")
+))]
impl PaymentMethods {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/payment_methods").app_data(web::Data::new(state));
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 4684edbd18..cf89f2f547 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -1,4 +1,7 @@
-use actix_web::{web, HttpRequest, HttpResponse, Responder};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use actix_web::Responder;
+use actix_web::{web, HttpRequest, HttpResponse};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::id_type;
use router_env::{instrument, tracing, Flow};
@@ -32,6 +35,7 @@ pub async fn customers_create(
.await
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customers_retrieve(
state: web::Data<AppState>,
@@ -39,9 +43,10 @@ pub async fn customers_retrieve(
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
let flow = Flow::CustomersRetrieve;
- let payload = web::Json(customers::CustomerId {
- customer_id: path.into_inner(),
- })
+
+ let payload = web::Json(customers::CustomerId::new_customer_id_struct(
+ path.into_inner(),
+ ))
.into_inner();
let auth = if auth::is_jwt_auth(req.headers()) {
@@ -65,6 +70,7 @@ pub async fn customers_retrieve(
.await
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
pub async fn customers_list(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::CustomersList;
@@ -87,6 +93,7 @@ pub async fn customers_list(state: web::Data<AppState>, req: HttpRequest) -> Htt
.await
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customers_update(
state: web::Data<AppState>,
@@ -113,6 +120,7 @@ pub async fn customers_update(
.await
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customers_delete(
state: web::Data<AppState>,
@@ -140,6 +148,8 @@ pub async fn customers_delete(
))
.await
}
+
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all, fields(flow = ?Flow::CustomersGetMandates))]
pub async fn get_customer_mandates(
state: web::Data<AppState>,
diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs
index bfe7c353c2..9b10093846 100644
--- a/crates/router/src/routes/ephemeral_key.rs
+++ b/crates/router/src/routes/ephemeral_key.rs
@@ -22,13 +22,18 @@ pub async fn ephemeral_key_create(
&req,
payload,
|state, auth, req, _| {
- helpers::make_ephemeral_key(state, req.customer_id, auth.merchant_account.merchant_id)
+ helpers::make_ephemeral_key(
+ state,
+ req.get_merchant_reference_id(),
+ auth.merchant_account.merchant_id,
+ )
},
&auth::ApiKeyAuth,
api_locking::LockAction::NotApplicable,
)
.await
}
+
#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))]
pub async fn ephemeral_key_delete(
state: web::Data<AppState>,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 25df0ef643..17a3a21d0e 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -1,3 +1,7 @@
+#[cfg(all(
+ any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
+ not(feature = "customer_v2")
+))]
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use common_utils::{errors::CustomResult, id_type};
@@ -9,21 +13,26 @@ use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
use crate::{
core::{
- api_locking, customers, errors,
+ api_locking, errors,
errors::utils::StorageErrorExt,
- payment_methods::{self as payment_methods_routes, cards, migration},
+ payment_methods::{self as payment_methods_routes, cards},
},
services::{api, authentication as auth, authorization::permissions::Permission},
types::{
- api::{
- customers::CustomerRequest,
- payment_methods::{self, PaymentMethodId},
- },
+ api::payment_methods::{self, PaymentMethodId},
domain,
storage::payment_method::PaymentTokenData,
},
utils::Encode,
};
+#[cfg(all(
+ any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
+ not(feature = "customer_v2")
+))]
+use crate::{
+ core::{customers, payment_methods::migration},
+ types::api::customers::CustomerRequest,
+};
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
@@ -107,6 +116,10 @@ async fn get_merchant_account(
Ok((key_store, merchant_account))
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),
+ not(feature = "customer_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_methods(
state: web::Data<AppState>,
diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs
index e0ef95bcb0..b851b8d458 100644
--- a/crates/router/src/types/api/customers.rs
+++ b/crates/router/src/types/api/customers.rs
@@ -1,9 +1,15 @@
use api_models::customers;
pub use api_models::customers::{CustomerDeleteResponse, CustomerId, CustomerRequest};
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+use hyperswitch_domain_models::customer;
use serde::Serialize;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use super::payments;
-use crate::{newtype, types::domain};
+use crate::{
+ newtype,
+ types::{domain, ForeignFrom},
+};
newtype!(
pub CustomerResponse = customers::CustomerResponse,
@@ -16,8 +22,9 @@ impl common_utils::events::ApiEventMetric for CustomerResponse {
}
}
-impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse {
- fn from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self {
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+impl ForeignFrom<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse {
+ fn foreign_from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self {
customers::CustomerResponse {
customer_id: cust.customer_id,
name: cust.name,
@@ -33,3 +40,23 @@ impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResp
.into()
}
}
+
+#[cfg(all(feature = "v2", feature = "customer_v2"))]
+impl ForeignFrom<customer::Customer> for CustomerResponse {
+ fn foreign_from(cust: domain::Customer) -> Self {
+ customers::CustomerResponse {
+ merchant_reference_id: Some(cust.customer_id),
+ name: cust.name,
+ email: cust.email,
+ phone: cust.phone,
+ phone_country_code: cust.phone_country_code,
+ description: cust.description,
+ created_at: cust.created_at,
+ metadata: cust.metadata,
+ default_billing_address: None,
+ default_shipping_address: None,
+ default_payment_method_id: cust.default_payment_method_id,
+ }
+ .into()
+ }
+}
diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs
index b7ed05e350..6f42cae0b4 100644
--- a/crates/router/src/types/domain/customer.rs
+++ b/crates/router/src/types/domain/customer.rs
@@ -1,186 +1 @@
-use api_models::customers::CustomerRequestWithEncryption;
-use common_utils::{
- crypto, date_time,
- encryption::Encryption,
- id_type, pii,
- types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
-};
-use diesel_models::customers::CustomerUpdateInternal;
-use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
-use time::PrimitiveDateTime;
-
-use super::types;
-use crate::errors::{CustomResult, ValidationError};
-
-#[derive(Clone, Debug)]
-pub struct Customer {
- pub id: Option<i32>,
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
- pub name: crypto::OptionalEncryptableName,
- pub email: crypto::OptionalEncryptableEmail,
- pub phone: crypto::OptionalEncryptablePhone,
- pub phone_country_code: Option<String>,
- pub description: Option<String>,
- pub created_at: PrimitiveDateTime,
- pub metadata: Option<pii::SecretSerdeValue>,
- pub modified_at: PrimitiveDateTime,
- pub connector_customer: Option<serde_json::Value>,
- pub address_id: Option<String>,
- pub default_payment_method_id: Option<String>,
- pub updated_by: Option<String>,
-}
-
-#[async_trait::async_trait]
-impl super::behaviour::Conversion for Customer {
- type DstType = diesel_models::customers::Customer;
- type NewDstType = diesel_models::customers::CustomerNew;
- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
- Ok(diesel_models::customers::Customer {
- id: self.id.ok_or(ValidationError::MissingRequiredField {
- field_name: "id".to_string(),
- })?,
- customer_id: self.customer_id,
- merchant_id: self.merchant_id,
- name: self.name.map(|value| value.into()),
- email: self.email.map(|value| value.into()),
- phone: self.phone.map(Encryption::from),
- phone_country_code: self.phone_country_code,
- description: self.description,
- created_at: self.created_at,
- metadata: self.metadata,
- modified_at: self.modified_at,
- connector_customer: self.connector_customer,
- address_id: self.address_id,
- default_payment_method_id: self.default_payment_method_id,
- updated_by: self.updated_by,
- })
- }
-
- async fn convert_back(
- state: &KeyManagerState,
- item: Self::DstType,
- key: &Secret<Vec<u8>>,
- _key_store_ref_id: String,
- ) -> CustomResult<Self, ValidationError>
- where
- Self: Sized,
- {
- let decrypted = types::batch_decrypt(
- state,
- CustomerRequestWithEncryption::to_encryptable(CustomerRequestWithEncryption {
- name: item.name.clone(),
- phone: item.phone.clone(),
- email: item.email.clone(),
- }),
- Identifier::Merchant(item.merchant_id.clone()),
- key.peek(),
- )
- .await
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting customer data".to_string(),
- })?;
- let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted)
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting customer data".to_string(),
- })?;
-
- Ok(Self {
- id: Some(item.id),
- customer_id: item.customer_id,
- merchant_id: item.merchant_id,
- name: encryptable_customer.name,
- email: encryptable_customer.email,
- phone: encryptable_customer.phone,
- phone_country_code: item.phone_country_code,
- description: item.description,
- created_at: item.created_at,
- metadata: item.metadata,
- modified_at: item.modified_at,
- connector_customer: item.connector_customer,
- address_id: item.address_id,
- default_payment_method_id: item.default_payment_method_id,
- updated_by: item.updated_by,
- })
- }
-
- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
- let now = date_time::now();
- Ok(diesel_models::customers::CustomerNew {
- customer_id: self.customer_id,
- merchant_id: self.merchant_id,
- name: self.name.map(Encryption::from),
- email: self.email.map(Encryption::from),
- phone: self.phone.map(Encryption::from),
- description: self.description,
- phone_country_code: self.phone_country_code,
- metadata: self.metadata,
- created_at: now,
- modified_at: now,
- connector_customer: self.connector_customer,
- address_id: self.address_id,
- updated_by: self.updated_by,
- })
- }
-}
-
-#[derive(Clone, Debug)]
-pub enum CustomerUpdate {
- Update {
- name: crypto::OptionalEncryptableName,
- email: crypto::OptionalEncryptableEmail,
- phone: Box<crypto::OptionalEncryptablePhone>,
- description: Option<String>,
- phone_country_code: Option<String>,
- metadata: Option<pii::SecretSerdeValue>,
- connector_customer: Option<serde_json::Value>,
- address_id: Option<String>,
- },
- ConnectorCustomer {
- connector_customer: Option<serde_json::Value>,
- },
- UpdateDefaultPaymentMethod {
- default_payment_method_id: Option<Option<String>>,
- },
-}
-
-impl From<CustomerUpdate> for CustomerUpdateInternal {
- fn from(customer_update: CustomerUpdate) -> Self {
- match customer_update {
- CustomerUpdate::Update {
- name,
- email,
- phone,
- description,
- phone_country_code,
- metadata,
- connector_customer,
- address_id,
- } => Self {
- name: name.map(Encryption::from),
- email: email.map(Encryption::from),
- phone: phone.map(Encryption::from),
- description,
- phone_country_code,
- metadata,
- connector_customer,
- modified_at: Some(date_time::now()),
- address_id,
- ..Default::default()
- },
- CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
- connector_customer,
- modified_at: Some(date_time::now()),
- ..Default::default()
- },
- CustomerUpdate::UpdateDefaultPaymentMethod {
- default_payment_method_id,
- } => Self {
- default_payment_method_id,
- modified_at: Some(date_time::now()),
- ..Default::default()
- },
- }
- }
-}
+pub use hyperswitch_domain_models::customer::*;
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index a36aee4593..cd1019f4a0 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -11,27 +11,32 @@ pub mod user;
pub mod user_role;
#[cfg(feature = "olap")]
pub mod verify_connector;
-
use std::fmt::Debug;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use api_models::payments::AddressDetailsWithPhone;
use api_models::{
enums,
- payments::{self, AddressDetailsWithPhone},
+ payments::{self},
webhooks,
};
use base64::Engine;
+use common_utils::types::keymanager::KeyManagerState;
pub use common_utils::{
crypto,
ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt},
fp_utils::when,
validation::validate_email,
};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::{
id_type,
- types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
+ types::keymanager::{Identifier, ToEncryptable},
};
use error_stack::ResultExt;
-use hyperswitch_domain_models::{payments::PaymentIntent, type_encryption::batch_encrypt};
+use hyperswitch_domain_models::payments::PaymentIntent;
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use hyperswitch_domain_models::type_encryption::batch_encrypt;
use image::Luma;
use nanoid::nanoid;
use qrcode;
@@ -42,6 +47,8 @@ use tracing_futures::Instrument;
use uuid::Uuid;
pub use self::ext_traits::{OptionExt, ValidateCall};
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
+use crate::types::storage;
use crate::{
consts,
core::{
@@ -52,7 +59,7 @@ use crate::{
logger,
routes::{metrics, SessionState},
services,
- types::{self, domain, storage, transformers::ForeignFrom},
+ types::{self, domain, transformers::ForeignFrom},
};
pub mod error_parser {
@@ -661,6 +668,7 @@ pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) {
}
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[async_trait::async_trait]
pub trait CustomerAddress {
async fn get_address_update(
@@ -683,6 +691,7 @@ pub trait CustomerAddress {
) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>;
}
+#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[async_trait::async_trait]
impl CustomerAddress for api_models::customers::CustomerRequest {
async fn get_address_update(
diff --git a/justfile b/justfile
index b5f282dc9a..9b9ad5a854 100644
--- a/justfile
+++ b/justfile
@@ -27,7 +27,7 @@ clippy *FLAGS:
jq -r '
[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array
| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates
- | del( .[] | select( any( . ; . == ("v2", "merchant_account_v2", "payment_v2") ) ) ) # Exclude some features from features list
+ | del( .[] | select( any( . ; . == ("v2", "merchant_account_v2", "payment_v2", "customer_v2") ) ) ) # Exclude some features from features list
| join(",") # Construct a comma-separated string of features for passing to `cargo`
')"
@@ -108,7 +108,7 @@ euclid-wasm features='dummy_connector':
precommit: fmt clippy
# Check compilation of v2 feature on base dependencies
-v2_intermediate_features := "merchant_account_v2,payment_v2"
+v2_intermediate_features := "merchant_account_v2,payment_v2,customer_v2"
hack_v2:
cargo hack check --feature-powerset --ignore-unknown-features --at-least-one-of "v2 " --include-features "v2" --include-features {{ v2_intermediate_features }} --package "hyperswitch_domain_models" --package "diesel_models" --package "api_models"
cargo hack check --features "v2,payment_v2" -p storage_impl
diff --git a/scripts/ci-checks.sh b/scripts/ci-checks.sh
index 69bc56a623..219bde3c68 100755
--- a/scripts/ci-checks.sh
+++ b/scripts/ci-checks.sh
@@ -69,7 +69,7 @@ crates_with_v1_feature="$(
--null-input \
'$crates_with_features[]
| select( IN("v1"; .features[])) # Select crates with `v1` feature
- | { name, features: (.features - ["v1", "v2", "default", "payment_v2", "merchant_account_v2"]) } # Remove specific features to generate feature combinations
+ | { name, features: (.features - ["v1", "v2", "default", "payment_v2", "merchant_account_v2","customer_v2"]) } # Remove specific features to generate feature combinations
| { name, features: ( .features | map([., "v1"] | join(",")) ) } # Add `v1` to remaining features and join them by comma
| .name as $name | .features[] | { $name, features: . } # Expand nested features object to have package - features combinations
| "\(.name) \(.features)" # Print out package name and features separated by space'