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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(customers): add cell_id field and update customer ID handling (#12643)
Gaurav Rawat8a87ae5eadef
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rsindex df695a4255..0b8e1a4fa1 100644--- a/crates/diesel_models/src/customers.rs+++ b/crates/diesel_models/src/customers.rs@@ -34,7 +34,7 @@ pub struct CustomerNew {pub created_by: Option<String>,pub last_modified_by: Option<String>,pub document_details: Option<Encryption>,- pub id: Option<common_utils::id_type::CustomerId>,+ pub id: Option<String>,}#[cfg(feature = "v1")]@@ -166,7 +166,7 @@ pub struct Customer {pub created_by: Option<String>,pub last_modified_by: Option<String>,pub document_details: Option<Encryption>,- pub id: Option<common_utils::id_type::CustomerId>,+ pub id: Option<String>,}#[cfg(feature = "v2")]diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rsindex 616344e972..8b1f36d9c7 100644--- a/crates/hyperswitch_domain_models/src/customer.rs+++ b/crates/hyperswitch_domain_models/src/customer.rs@@ -58,6 +58,7 @@ pub struct Customer {pub document_details: OptionalEncryptableValue,pub created_by: Option<CreatedBy>,pub last_modified_by: Option<CreatedBy>,+ key: Option<String>,}#[cfg(feature = "v2")]@@ -92,6 +93,50 @@ pub struct Customer {}impl Customer {+ #[cfg(feature = "v1")]+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ customer_id: id_type::CustomerId,+ merchant_id: id_type::MerchantId,+ name: Option<Encryptable<Secret<String>>>,+ email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,+ phone: Option<Encryptable<Secret<String>>>,+ phone_country_code: Option<String>,+ description: Option<Description>,+ metadata: Option<pii::SecretSerdeValue>,+ connector_customer: Option<pii::SecretSerdeValue>,+ address_id: Option<String>,+ tax_registration_id: Option<Encryptable<Secret<String>>>,+ document_details: OptionalEncryptableValue,+ created_by: Option<CreatedBy>,+ last_modified_by: Option<CreatedBy>,+ key: String,+ ) -> Self {+ let now = date_time::now();+ Self {+ customer_id,+ merchant_id,+ name,+ email,+ phone,+ phone_country_code,+ description,+ created_at: now,+ metadata,+ modified_at: now,+ connector_customer,+ address_id,+ default_payment_method_id: None,+ updated_by: None,+ version: common_enums::ApiVersion::V1,+ tax_registration_id,+ document_details,+ created_by,+ last_modified_by,+ key: Some(key),+ }+ }+/// Get the unique identifier of Customer#[cfg(feature = "v1")]pub fn get_id(&self) -> &id_type::CustomerId {@@ -151,6 +196,11 @@ impl Customer {MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,}}++ #[cfg(feature = "v1")]+ pub fn get_global_customer_id(&self) -> &Option<String> {+ &self.key+ }}#[cfg(feature = "v1")]@@ -181,7 +231,7 @@ impl behaviour::Conversion for Customer {last_modified_by: self.last_modified_by.map(|last_modified_by| last_modified_by.to_string()),- id: Some(self.customer_id),+ id: self.key,})}@@ -266,13 +316,14 @@ impl behaviour::Conversion for Customer {last_modified_by: item.last_modified_by.and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ key: item.id,})}async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {let now = date_time::now();Ok(diesel_models::customers::CustomerNew {- id: Some(self.customer_id.clone()),+ id: self.key,customer_id: self.customer_id,merchant_id: self.merchant_id,name: self.name.map(Encryption::from),diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex ac22c17c00..ea6ccb82e6 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -617,7 +617,6 @@ pub(crate) async fn fetch_raw_secrets(locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors,grpc_client: conf.grpc_client,crm: conf.crm,- #[cfg(feature = "v2")]cell_information: conf.cell_information,network_tokenization_supported_card_networks: conf.network_tokenization_supported_card_networks,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex bc20f6658e..8afa6cec40 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -166,7 +166,6 @@ pub struct Settings<S: SecretState> {pub decision: Option<DecisionConfig>,pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,pub grpc_client: GrpcClientSettings,- #[cfg(feature = "v2")]pub cell_information: CellInformation,pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,pub alt_id_required_card_networks_and_connector: AltIdRequiredCardNetworksAndConnector,@@ -1382,6 +1381,20 @@ pub struct CellInformation {pub id: id_type::CellId,}+#[cfg(feature = "v1")]+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]+pub struct CellInformation {+ pub id: String,+}+#[cfg(feature = "v1")]+impl Default for CellInformation {+ fn default() -> Self {+ Self {+ id: String::from("defid"),+ }+ }+}+#[cfg(feature = "v2")]impl Default for CellInformation {fn default() -> Self {diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rsindex ba3191fdad..19165a2b65 100644--- a/crates/router/src/configs/validations.rs+++ b/crates/router/src/configs/validations.rs@@ -209,6 +209,19 @@ impl super::settings::CellInformation {}}+#[cfg(feature = "v1")]+impl super::settings::CellInformation {+ pub fn validate(&self) -> Result<(), ApplicationError> {+ use common_utils::fp_utils::when;++ when(self == &Self::default(), || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "CellId cannot be set to a default".into(),+ ))+ })+ }+}+impl super::settings::NetworkTokenizationService {pub fn validate(&self) -> Result<(), ApplicationError> {use common_utils::fp_utils::when;diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rsindex 6dfde15650..989067417d 100644--- a/crates/router/src/core/customers.rs+++ b/crates/router/src/core/customers.rs@@ -47,6 +47,18 @@ use crate::{pub const REDACTED: &str = "Redacted";+pub fn generate_global_customer_id(cell_id: &str) -> String {+ let prefix = format!("{}_cus", cell_id);+ common_utils::generate_time_ordered_id(&prefix)+}++pub fn is_customer_id_in_global_format(customer_id: &id_type::CustomerId, cell_id: &str) -> bool {+ customer_id+ .get_string_repr()+ .split_once('_')+ .is_some_and(|(prefix, _)| prefix == cell_id)+}+#[instrument(skip(state))]pub async fn create_customer(state: SessionState,@@ -235,35 +247,31 @@ impl CustomerCreateBridge for customers::CustomerRequest {pii::SecretSerdeValue::new(serde_json::Value::Object(map))});- Ok(domain::Customer {- customer_id: merchant_reference_id+ Ok(domain::Customer::new(+ merchant_reference_id.to_owned().ok_or(errors::CustomersErrorResponse::InternalServerError)?,- merchant_id: merchant_id.to_owned(),- name: encryptable_customer.name,- email: encryptable_customer.email.map(|email| {+ merchant_id.to_owned(),+ encryptable_customer.name,+ encryptable_customer.email.map(|email| {let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(email.clone().into_inner().switch_strategy(),email.into_encrypted(),);encryptable}),- phone: encryptable_customer.phone,- description: self.description.clone(),- phone_country_code: self.phone_country_code.clone(),- metadata: self.metadata.clone(),+ encryptable_customer.phone,+ self.phone_country_code.clone(),+ self.description.clone(),+ self.metadata.clone(),connector_customer,- 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,- version: common_types::consts::API_VERSION,- tax_registration_id: encryptable_customer.tax_registration_id,- document_details: document_details_encrypted,- created_by: initiator.and_then(|initiator| initiator.to_created_by()),- last_modified_by: initiator.and_then(|initiator| initiator.to_created_by()),- })+ address_from_db.clone().map(|addr| addr.address_id),+ encryptable_customer.tax_registration_id,+ document_details_encrypted,+ initiator.and_then(|initiator| initiator.to_created_by()),+ initiator.and_then(|initiator| initiator.to_created_by()),+ generate_global_customer_id(&state.conf.cell_information.id),+ ))}fn generate_response<'a>(@@ -1701,3 +1709,31 @@ async fn sync_connector_customer_for_migrated_customer(Ok(())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_is_customer_id_in_global_format() {+ let cell_id = "12345";++ let test_cases = [+ ("12345sbjabjbd", false),+ ("12345_cus_13igbfejs", true),+ ("12354_cus_12iufbeksjeb", false),+ ("efbc2_cus_217846821", false),+ ];++ for (customer_id_str, expected) in test_cases {+ let customer_id =+ id_type::CustomerId::wrap(customer_id_str.to_string()).expect("valid customer id");++ assert_eq!(+ is_customer_id_in_global_format(&customer_id, cell_id),+ expected,+ "failed for customer_id={customer_id_str}",+ );+ }+ }+}diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rsindex 819cdfce17..9c247f0008 100644--- a/crates/router/src/core/errors/utils.rs+++ b/crates/router/src/core/errors/utils.rs@@ -55,6 +55,11 @@ impl<T> StorageErrorExt<T, errors::ApiErrorResponse>errors::StorageError::CustomerRedacted => {errors::ApiErrorResponse::CustomerRedacted}+ errors::StorageError::InvalidDataFormat(err) => {+ errors::ApiErrorResponse::InvalidRequestData {+ message: format!("InvalidRequestData: {}", err),+ }+ }_ => errors::ApiErrorResponse::InternalServerError,};err.change_context(new_err)diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rsindex 64ac69eb20..8417a0e49c 100644--- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs+++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs@@ -20,9 +20,12 @@ use super::{NetworkTokenizationResponse, State, StoreLockerResponse, TransitionTo,};use crate::{- core::payment_methods::{- cards::{add_card_to_vault, PmCards},- transformers as pm_transformers,+ core::{+ customers,+ payment_methods::{+ cards::{add_card_to_vault, PmCards},+ transformers as pm_transformers,+ },},errors::{self, RouterResult},types::{api, domain},@@ -420,32 +423,28 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {.attach_printable("Failed to form EncryptableCustomer")?;let new_customer_id = generate_customer_id_of_default_length();- let domain_customer = domain::Customer {- customer_id: new_customer_id.clone(),- merchant_id: self.merchant_account.get_id().clone(),- name: encryptable_customer.name,- email: encryptable_customer.email.map(|email| {+ let domain_customer = domain::Customer::new(+ new_customer_id.clone(),+ self.merchant_account.get_id().clone(),+ encryptable_customer.name,+ encryptable_customer.email.map(|email| {utils::Encryptable::new(email.clone().into_inner().switch_strategy(),email.into_encrypted(),)}),- phone: encryptable_customer.phone,- description: None,- phone_country_code: self.customer.phone_country_code.to_owned(),- metadata: None,- connector_customer: None,- created_at: common_utils::date_time::now(),- modified_at: common_utils::date_time::now(),- address_id: None,- default_payment_method_id: None,- updated_by: None,- version: common_types::consts::API_VERSION,- tax_registration_id: encryptable_customer.tax_registration_id,- document_details: None,- created_by: initiator.and_then(|initiator| initiator.to_created_by()),- last_modified_by: initiator.and_then(|initiator| initiator.to_created_by()),- };+ encryptable_customer.phone,+ self.customer.phone_country_code.to_owned(),+ None,+ None,+ None,+ None,+ encryptable_customer.tax_registration_id,+ None,+ initiator.and_then(|initiator| initiator.to_created_by()),+ initiator.and_then(|initiator| initiator.to_created_by()),+ customers::generate_global_customer_id(&self.state.conf.cell_information.id),+ );db.insert_customer(domain_customer,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex fd874c3f77..f90be4a74f 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -94,6 +94,7 @@ use crate::{core::{authentication,configs::dimension_state,+ customers,errors::{self, CustomResult, RouterResult, StorageErrorExt},payment_methods::{self,@@ -1970,6 +1971,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(let customer_id = request_customer_details.customer_id.or(payment_data.payment_intent.customer_id.clone());+let db = &*state.store;let key_manager_state = &state.into();let optional_customer = match customer_id {@@ -2109,11 +2111,22 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(}}None => {- let new_customer = domain::Customer {+ // Validate that the customer_id is not in GlobalCustomerId format+ if customers::is_customer_id_in_global_format(+ &customer_id,+ &state.conf.cell_information.id,+ ) {+ Err(report!(errors::StorageError::InvalidDataFormat(format!(+ "customer_id '{}' format is not supported",+ &customer_id.get_string_repr()+ ))))?+ }++ let new_customer = domain::Customer::new(customer_id,- merchant_id: merchant_id.to_owned(),- name: encryptable_customer.name,- email: encryptable_customer.email.map(|email| {+ merchant_id.to_owned(),+ encryptable_customer.name,+ encryptable_customer.email.map(|email| {let encryptable: Encryptable<hyperswitch_masking::Secret<String, pii::EmailStrategy>,> = Encryptable::new(@@ -2122,22 +2135,18 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>();encryptable}),- phone: encryptable_customer.phone,- phone_country_code: request_customer_details.phone_country_code.clone(),- description: None,- created_at: common_utils::date_time::now(),- metadata: None,- modified_at: common_utils::date_time::now(),- connector_customer: None,- address_id: None,- default_payment_method_id: None,- updated_by: None,- version: common_types::consts::API_VERSION,- tax_registration_id: encryptable_customer.tax_registration_id,+ encryptable_customer.phone,+ request_customer_details.phone_country_code.clone(),+ None,+ None,+ None,+ None,+ encryptable_customer.tax_registration_id,document_details,- created_by: initiator.and_then(|initiator| initiator.to_created_by()),- last_modified_by: initiator.and_then(|initiator| initiator.to_created_by()),- };+ initiator.and_then(|initiator| initiator.to_created_by()),+ initiator.and_then(|initiator| initiator.to_created_by()),+ customers::generate_global_customer_id(&state.conf.cell_information.id),+ );metrics::CUSTOMER_CREATED.add(1, &[]);db.insert_customer(new_customer, key_store, storage_scheme).awaitdiff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex 24e2516abd..291baad992 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -25,6 +25,7 @@ use crate::{consts,core::{configs::dimension_state,+ customers,errors::{self, RouterResult, StorageErrorExt},payment_methods::{cards,@@ -990,11 +991,11 @@ pub(super) async fn get_or_create_customer_details(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Unable to encrypt document_details")?;- let customer = domain::Customer {- customer_id: customer_id.clone(),- merchant_id: merchant_id.to_owned().clone(),- name: encryptable_customer.name,- email: encryptable_customer.email.map(|email| {+ let customer = domain::Customer::new(+ customer_id.clone(),+ merchant_id.to_owned().clone(),+ encryptable_customer.name,+ encryptable_customer.email.map(|email| {let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> =Encryptable::new(email.clone().into_inner().switch_strategy(),@@ -1002,26 +1003,22 @@ pub(super) async fn get_or_create_customer_details();encryptable}),- phone: encryptable_customer.phone,- description: None,- phone_country_code: customer_details.phone_country_code.to_owned(),- metadata: None,- connector_customer: None,- created_at: common_utils::date_time::now(),- modified_at: common_utils::date_time::now(),- address_id: None,- default_payment_method_id: None,- updated_by: None,- version: common_types::consts::API_VERSION,- tax_registration_id: encryptable_customer.tax_registration_id,+ encryptable_customer.phone,+ customer_details.phone_country_code.to_owned(),+ None,+ None,+ None,+ None,+ encryptable_customer.tax_registration_id,document_details,- created_by: platform+ platform.get_initiator().and_then(|initiator| initiator.to_created_by()),- last_modified_by: platform+ platform.get_initiator().and_then(|initiator| initiator.to_created_by()), // Same as created_by on creation- };+ customers::generate_global_customer_id(&state.conf.cell_information.id),+ );Ok(Some(db.insert_customer(diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rsindex 38484008ac..9b15ec34d9 100644--- a/crates/storage_impl/src/errors.rs+++ b/crates/storage_impl/src/errors.rs@@ -37,6 +37,8 @@ pub enum StorageError {DecryptionError,#[error("RedisError: {0:?}")]RedisError(error_stack::Report<RedisError>),+ #[error("InvalidDataFormat: {0}")]+ InvalidDataFormat(String),}impl From<error_stack::Report<RedisError>> for StorageError {