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
fix(payment_methods): store connector_customer_id from batch migrate into customers.connector_customer (#12264)
DEEPANSHU BANSAL75216ac4724a
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 2571cf3088..11d774d3b5 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -1340,16 +1340,26 @@ pub struct PaymentMethodCustomerMigrate {}#[cfg(feature = "v1")]-impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)>- for PaymentMethodCustomerMigrate+impl+ TryFrom<(+ payment_methods::PaymentMethodRecord,+ id_type::MerchantId,+ Option<&Vec<id_type::MerchantConnectorAccountId>>,+ )> for PaymentMethodCustomerMigrate{type Error = error_stack::Report<ValidationError>;fn try_from(- value: (payment_methods::PaymentMethodRecord, id_type::MerchantId),+ value: (+ payment_methods::PaymentMethodRecord,+ id_type::MerchantId,+ // merchant_connector_id(s) supplied at the form level (not as CSV columns)+ Option<&Vec<id_type::MerchantConnectorAccountId>>,+ ),) -> Result<Self, Self::Error> {- let (record, merchant_id) = value;+ let (record, merchant_id, fallback_merchant_connector_ids) = value;let connector_customer_details = record.connector_customer_id+ .as_ref().and_then(|connector_customer_id| {// Handle single merchant_connector_idrecord@@ -1393,6 +1403,19 @@ impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)>.collect::<Result<Vec<_>, _>>()})})+ // Fall back to the form-level merchant_connector_id(s) when the CSV row+ // has no merchant_connector_id(s) column+ .or_else(|| {+ fallback_merchant_connector_ids.map(|merchant_connector_ids| {+ Ok(merchant_connector_ids+ .iter()+ .map(|merchant_connector_id| ConnectorCustomerDetails {+ connector_customer_id: connector_customer_id.clone(),+ merchant_connector_id: merchant_connector_id.clone(),+ })+ .collect::<Vec<_>>())+ })+ })}).transpose()?;@@ -1427,18 +1450,31 @@ impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)>}#[cfg(feature = "v1")]-impl ForeignTryFrom<(&[payment_methods::PaymentMethodRecord], id_type::MerchantId)>- for Vec<PaymentMethodCustomerMigrate>+impl+ ForeignTryFrom<(+ &[payment_methods::PaymentMethodRecord],+ id_type::MerchantId,+ Option<&Vec<id_type::MerchantConnectorAccountId>>,+ )> for Vec<PaymentMethodCustomerMigrate>{type Error = error_stack::Report<ValidationError>;fn foreign_try_from(- (records, merchant_id): (&[payment_methods::PaymentMethodRecord], id_type::MerchantId),+ // merchant_connector_ids: form-level connector account id(s), forwarded to each row+ (records, merchant_id, merchant_connector_ids): (+ &[payment_methods::PaymentMethodRecord],+ id_type::MerchantId,+ Option<&Vec<id_type::MerchantConnectorAccountId>>,+ ),) -> Result<Self, Self::Error> {let (customers_migration, migration_errors): (Self, Vec<_>) = records.iter().map(|record| {- PaymentMethodCustomerMigrate::try_from((record.clone(), merchant_id.clone()))+ PaymentMethodCustomerMigrate::try_from((+ record.clone(),+ merchant_id.clone(),+ merchant_connector_ids,+ ))}).fold((Self::new(), Vec::new()), |mut acc, result| {match result {diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rsindex 36f36a271b..6dfde15650 100644--- a/crates/router/src/core/customers.rs+++ b/crates/router/src/core/customers.rs@@ -1582,6 +1582,10 @@ pub async fn migrate_customers(platform: domain::Platform,) -> errors::CustomerResponse<()> {for customer_migration in customers_migration {+ #[cfg(feature = "v1")]+ let customer_id = customer_migration.customer.customer_id.clone();+ #[cfg(feature = "v1")]+ let connector_customer_details = customer_migration.connector_customer_details.clone();match create_customer(state.clone(),platform.get_provider().clone(),@@ -1593,10 +1597,107 @@ pub async fn migrate_customers({Ok(_) => (),Err(e) => match e.current_context() {- errors::CustomersErrorResponse::CustomerAlreadyExists => (),+ // Customer already exists in Hyperswitch: still merge the migrated+ // connector_customer_id(s) into the existing customer's connector_customer.+ errors::CustomersErrorResponse::CustomerAlreadyExists => {+ #[cfg(feature = "v1")]+ sync_connector_customer_for_migrated_customer(+ &state,+ &platform,+ customer_id,+ connector_customer_details,+ )+ .await?;+ }_ => return Err(e),},}}Ok(services::ApplicationResponse::Json(()))}++/// Saves the connector's customer id (from the migration CSV) onto a customer that already+/// exists in Hyperswitch.+///+/// Background, in plain terms:+/// - Each customer row has a `connector_customer` field. Think of it as a small lookup table:+/// "for connector account X, this customer is known as Y on that connector's side".+/// - When the migration creates a brand-new customer, that field is filled in right away.+/// - But when the customer was already in Hyperswitch, the create step is skipped — and so the+/// connector customer id from the CSV would be thrown away. This function handles that case:+/// it opens the existing customer and adds the id in.+///+/// We *add to* the lookup table, we don't wipe it: ids saved for other connector accounts stay,+/// and if there was already an id for this connector account it gets replaced with the one from+/// the CSV. If the CSV row had no connector customer id (or nothing to attach it to), we do+/// nothing.+#[cfg(feature = "v1")]+async fn sync_connector_customer_for_migrated_customer(+ state: &SessionState,+ platform: &domain::Platform,+ customer_id: Option<id_type::CustomerId>,+ connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>,+) -> errors::CustomResult<(), errors::CustomersErrorResponse> {+ // If the CSV row didn't give us a customer id, or gave no connector customer ids to save,+ // there's nothing to do.+ let Some((customer_id, connector_customer_details)) = customer_id+ .zip(connector_customer_details)+ .filter(|(_, details)| !details.is_empty())+ else {+ return Ok(());+ };++ let db: &dyn StorageInterface = state.store.as_ref();+ let provider = platform.get_provider();+ let merchant_id = provider.get_account().get_id();+ let storage_scheme = provider.get_account().storage_scheme;++ // Load the customer that already exists, so we can add to its current list of connector+ // customer ids instead of replacing it.+ let existing_customer = db+ .find_customer_by_customer_id_merchant_id(+ &customer_id,+ merchant_id,+ provider.get_key_store(),+ storage_scheme,+ )+ .await+ .switch()?;++ // Take the customer's current "connector account -> connector customer id" list (empty if+ // it had none yet) and add/overwrite the entries coming from the migration row.+ let mut connector_customer_map = existing_customer+ .connector_customer+ .as_ref()+ .and_then(|connector_customer| connector_customer.peek().as_object().cloned())+ .unwrap_or_default();+ for details in &connector_customer_details {+ connector_customer_map.insert(+ details.merchant_connector_id.get_string_repr().to_string(),+ details.connector_customer_id.clone().into(),+ );+ }++ // Save the updated list back onto the customer. This only changes the `connector_customer`+ // field (and the "last modified" bookkeeping) — the rest of the customer is untouched.+ db.update_customer_by_customer_id_merchant_id(+ customer_id,+ merchant_id.clone(),+ existing_customer,+ storage::CustomerUpdate::ConnectorCustomer {+ connector_customer: Some(pii::SecretSerdeValue::new(serde_json::Value::Object(+ connector_customer_map,+ ))),+ last_modified_by: platform+ .get_initiator()+ .and_then(|initiator| initiator.to_created_by())+ .map(|last_modified_by| last_modified_by.to_string()),+ },+ provider.get_key_store(),+ storage_scheme,+ )+ .await+ .switch()?;++ Ok(())+}diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex f18dc11c83..30982d64af 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -440,9 +440,12 @@ pub async fn migrate_payment_methods();let mut mca_cache = HashMap::new();+ // pass form-level mca id(s) so connector_customer_id is stored even when the+ // CSV has no merchant_connector_id(s) columnlet customers = Vec::<PaymentMethodCustomerMigrate>::foreign_try_from((&req,merchant_id.clone(),+ merchant_connector_ids.as_ref(),)).map_err(|e| errors::ApiErrorResponse::InvalidRequestData {message: e.to_string(),