diff --git "a/diffs/pr_6687/90fef34/diff.json" "b/diffs/pr_6687/90fef34/diff.json" new file mode 100644--- /dev/null +++ "b/diffs/pr_6687/90fef34/diff.json" @@ -0,0 +1,72 @@ +{ + "commit_sha": "90fef342c821e7b10ceaa64c6fa2a286737b9a23", + "pr_number": 6687, + "rust_files": [ + "crates/router/src/core/payment_methods/cards.rs", + "crates/router/src/core/payments/helpers.rs", + "crates/router/src/core/payments/operations/payment_response.rs", + "crates/router/src/core/webhooks/incoming.rs" + ], + "diffs": [ + { + "id": "crates/router/src/core/payment_methods/cards.rs::function::list_customer_payment_method", + "file": "crates/router/src/core/payment_methods/cards.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub async fn list_customer_payment_method(\n state: &routes::SessionState,\n merchant_account: domain::MerchantAccount,\n key_store: domain::MerchantKeyStore,\n payment_intent: Option,\n customer_id: &id_type::CustomerId,\n limit: Option,\n) -> errors::RouterResponse {\n let db = &*state.store;\n let key_manager_state = &state.into();\n let off_session_payment_flag = payment_intent\n .as_ref()\n .map(|pi| {\n matches!(\n pi.setup_future_usage,\n Some(common_enums::FutureUsage::OffSession)\n )\n })\n .unwrap_or(false);\n\n let customer = db\n .find_customer_by_customer_id_merchant_id(\n &state.into(),\n customer_id,\n merchant_account.get_id(),\n &key_store,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;\n\n let is_requires_cvv = db\n .find_config_by_key_unwrap_or(\n &merchant_account.get_id().get_requires_cvv_key(),\n Some(\"true\".to_string()),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to fetch requires_cvv config\")?;\n\n let requires_cvv = is_requires_cvv.config != \"false\";\n\n let resp = db\n .find_payment_method_by_customer_id_merchant_id_status(\n &(state.into()),\n &key_store,\n customer_id,\n merchant_account.get_id(),\n common_enums::PaymentMethodStatus::Active,\n limit,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;\n let mut customer_pms = Vec::new();\n\n let profile_id = payment_intent\n .as_ref()\n .map(|payment_intent| {\n payment_intent\n .profile_id\n .clone()\n .get_required_value(\"profile_id\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"profile_id is not set in payment_intent\")\n })\n .transpose()?;\n\n let business_profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n profile_id.as_ref(),\n merchant_account.get_id(),\n )\n .await?;\n\n let is_connector_agnostic_mit_enabled = business_profile\n .as_ref()\n .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)\n .unwrap_or(false);\n\n for pm in resp.into_iter() {\n let parent_payment_method_token = generate_id(consts::ID_LENGTH, \"token\");\n\n let payment_method = pm\n .get_payment_method_type()\n .get_required_value(\"payment_method\")?;\n\n let pm_list_context = get_pm_list_context(\n state,\n &payment_method,\n &key_store,\n &pm,\n Some(parent_payment_method_token.clone()),\n true,\n )\n .await?;\n\n if pm_list_context.is_none() {\n continue;\n }\n\n let pm_list_context = pm_list_context.get_required_value(\"PaymentMethodListContext\")?;\n\n // Retrieve the masked bank details to be sent as a response\n let bank_details = if payment_method == enums::PaymentMethod::BankDebit {\n get_masked_bank_details(&pm).await.unwrap_or_else(|error| {\n logger::error!(?error);\n None\n })\n } else {\n None\n };\n\n let payment_method_billing = pm\n .payment_method_billing_address\n .clone()\n .map(|decrypted_data| decrypted_data.into_inner().expose())\n .map(|decrypted_value| decrypted_value.parse_value(\"payment method billing address\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to decrypt payment method billing address details\")?;\n let connector_mandate_details = pm\n .connector_mandate_details\n .clone()\n .map(|val| {\n val.clone()\n .parse_value::(\"CommonMandateReference\")\n .or_else(|_| {\n val.parse_value::(\n \"PaymentsMandateReference\",\n )\n .map(|payments| {\n diesel_models::CommonMandateReference {\n payments: Some(payments),\n payouts: None,\n }\n })\n })\n })\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference \")?;\n let mca_enabled = get_mca_status(\n state,\n &key_store,\n profile_id.clone(),\n merchant_account.get_id(),\n is_connector_agnostic_mit_enabled,\n connector_mandate_details,\n pm.network_transaction_id.as_ref(),\n )\n .await?;\n\n let requires_cvv = if is_connector_agnostic_mit_enabled {\n requires_cvv\n && !(off_session_payment_flag\n && (pm.connector_mandate_details.is_some()\n || pm.network_transaction_id.is_some()))\n } else {\n requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())\n };\n // Need validation for enabled payment method ,querying MCA\n let pma = api::CustomerPaymentMethod {\n payment_token: parent_payment_method_token.to_owned(),\n payment_method_id: pm.payment_method_id.clone(),\n customer_id: pm.customer_id.clone(),\n payment_method,\n payment_method_type: pm.get_payment_method_subtype(),\n payment_method_issuer: pm.payment_method_issuer,\n card: pm_list_context.card_details,\n metadata: pm.metadata,\n payment_method_issuer_code: pm.payment_method_issuer_code,\n recurring_enabled: mca_enabled,\n installment_payment_enabled: false,\n payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),\n created: Some(pm.created_at),\n #[cfg(feature = \"payouts\")]\n bank_transfer: pm_list_context.bank_transfer_details,\n bank: bank_details,\n surcharge_details: None,\n requires_cvv,\n last_used_at: Some(pm.last_used_at),\n default_payment_method_set: customer.default_payment_method_id.is_some()\n && customer.default_payment_method_id == Some(pm.payment_method_id),\n billing: payment_method_billing,\n };\n if requires_cvv || mca_enabled {\n customer_pms.push(pma.to_owned());\n }\n\n let redis_conn = state\n .store\n .get_redis_conn()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to get redis connection\")?;\n\n let intent_fulfillment_time = business_profile\n .as_ref()\n .and_then(|b_profile| b_profile.get_order_fulfillment_time())\n .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);\n\n let hyperswitch_token_data = pm_list_context\n .hyperswitch_token_data\n .get_required_value(\"PaymentTokenData\")?;\n\n ParentPaymentMethodToken::create_key_for_token((\n &parent_payment_method_token,\n pma.payment_method,\n ))\n .insert(intent_fulfillment_time, hyperswitch_token_data, state)\n .await?;\n\n if let Some(metadata) = pma.metadata {\n let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata\n .parse_value(\"PaymentMethodMetadata\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"Failed to deserialize metadata to PaymentmethodMetadata struct\",\n )?;\n\n for pm_metadata in pm_metadata_vec.payment_method_tokenization {\n let key = format!(\n \"pm_token_{}_{}_{}\",\n parent_payment_method_token, pma.payment_method, pm_metadata.0\n );\n\n redis_conn\n .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time)\n .await\n .change_context(errors::StorageError::KVError)\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to add data in redis\")?;\n }\n }\n }\n\n let mut response = api::CustomerPaymentMethodsListResponse {\n customer_payment_methods: customer_pms,\n is_guest_customer: payment_intent.as_ref().map(|_| false), //to return this key only when the request is tied to a payment intent\n };\n\n Box::pin(perform_surcharge_ops(\n payment_intent,\n state,\n merchant_account,\n key_store,\n business_profile,\n &mut response,\n ))\n .await?;\n\n Ok(services::ApplicationResponse::Json(response))\n}", + "after_code": "pub async fn list_customer_payment_method(\n state: &routes::SessionState,\n merchant_account: domain::MerchantAccount,\n key_store: domain::MerchantKeyStore,\n payment_intent: Option,\n customer_id: &id_type::CustomerId,\n limit: Option,\n) -> errors::RouterResponse {\n let db = &*state.store;\n let key_manager_state = &state.into();\n let off_session_payment_flag = payment_intent\n .as_ref()\n .map(|pi| {\n matches!(\n pi.setup_future_usage,\n Some(common_enums::FutureUsage::OffSession)\n )\n })\n .unwrap_or(false);\n\n let customer = db\n .find_customer_by_customer_id_merchant_id(\n &state.into(),\n customer_id,\n merchant_account.get_id(),\n &key_store,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;\n\n let is_requires_cvv = db\n .find_config_by_key_unwrap_or(\n &merchant_account.get_id().get_requires_cvv_key(),\n Some(\"true\".to_string()),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to fetch requires_cvv config\")?;\n\n let requires_cvv = is_requires_cvv.config != \"false\";\n\n let resp = db\n .find_payment_method_by_customer_id_merchant_id_status(\n &(state.into()),\n &key_store,\n customer_id,\n merchant_account.get_id(),\n common_enums::PaymentMethodStatus::Active,\n limit,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;\n let mut customer_pms = Vec::new();\n\n let profile_id = payment_intent\n .as_ref()\n .map(|payment_intent| {\n payment_intent\n .profile_id\n .clone()\n .get_required_value(\"profile_id\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"profile_id is not set in payment_intent\")\n })\n .transpose()?;\n\n let business_profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n profile_id.as_ref(),\n merchant_account.get_id(),\n )\n .await?;\n\n let is_connector_agnostic_mit_enabled = business_profile\n .as_ref()\n .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)\n .unwrap_or(false);\n\n for pm in resp.into_iter() {\n let parent_payment_method_token = generate_id(consts::ID_LENGTH, \"token\");\n\n let payment_method = pm\n .get_payment_method_type()\n .get_required_value(\"payment_method\")?;\n\n let pm_list_context = get_pm_list_context(\n state,\n &payment_method,\n &key_store,\n &pm,\n Some(parent_payment_method_token.clone()),\n true,\n )\n .await?;\n\n if pm_list_context.is_none() {\n continue;\n }\n\n let pm_list_context = pm_list_context.get_required_value(\"PaymentMethodListContext\")?;\n\n // Retrieve the masked bank details to be sent as a response\n let bank_details = if payment_method == enums::PaymentMethod::BankDebit {\n get_masked_bank_details(&pm).await.unwrap_or_else(|error| {\n logger::error!(?error);\n None\n })\n } else {\n None\n };\n\n let payment_method_billing = pm\n .payment_method_billing_address\n .clone()\n .map(|decrypted_data| decrypted_data.into_inner().expose())\n .map(|decrypted_value| decrypted_value.parse_value(\"payment method billing address\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to decrypt payment method billing address details\")?;\n let connector_mandate_details = storage::PaymentMethod::get_common_mandate_reference(\n pm.connector_mandate_details.clone(),\n )\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference \")?;\n let mca_enabled = get_mca_status(\n state,\n &key_store,\n profile_id.clone(),\n merchant_account.get_id(),\n is_connector_agnostic_mit_enabled,\n Some(connector_mandate_details),\n pm.network_transaction_id.as_ref(),\n )\n .await?;\n\n let requires_cvv = if is_connector_agnostic_mit_enabled {\n requires_cvv\n && !(off_session_payment_flag\n && (pm.connector_mandate_details.is_some()\n || pm.network_transaction_id.is_some()))\n } else {\n requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())\n };\n // Need validation for enabled payment method ,querying MCA\n let pma = api::CustomerPaymentMethod {\n payment_token: parent_payment_method_token.to_owned(),\n payment_method_id: pm.payment_method_id.clone(),\n customer_id: pm.customer_id.clone(),\n payment_method,\n payment_method_type: pm.get_payment_method_subtype(),\n payment_method_issuer: pm.payment_method_issuer,\n card: pm_list_context.card_details,\n metadata: pm.metadata,\n payment_method_issuer_code: pm.payment_method_issuer_code,\n recurring_enabled: mca_enabled,\n installment_payment_enabled: false,\n payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),\n created: Some(pm.created_at),\n #[cfg(feature = \"payouts\")]\n bank_transfer: pm_list_context.bank_transfer_details,\n bank: bank_details,\n surcharge_details: None,\n requires_cvv,\n last_used_at: Some(pm.last_used_at),\n default_payment_method_set: customer.default_payment_method_id.is_some()\n && customer.default_payment_method_id == Some(pm.payment_method_id),\n billing: payment_method_billing,\n };\n if requires_cvv || mca_enabled {\n customer_pms.push(pma.to_owned());\n }\n\n let redis_conn = state\n .store\n .get_redis_conn()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to get redis connection\")?;\n\n let intent_fulfillment_time = business_profile\n .as_ref()\n .and_then(|b_profile| b_profile.get_order_fulfillment_time())\n .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);\n\n let hyperswitch_token_data = pm_list_context\n .hyperswitch_token_data\n .get_required_value(\"PaymentTokenData\")?;\n\n ParentPaymentMethodToken::create_key_for_token((\n &parent_payment_method_token,\n pma.payment_method,\n ))\n .insert(intent_fulfillment_time, hyperswitch_token_data, state)\n .await?;\n\n if let Some(metadata) = pma.metadata {\n let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata\n .parse_value(\"PaymentMethodMetadata\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"Failed to deserialize metadata to PaymentmethodMetadata struct\",\n )?;\n\n for pm_metadata in pm_metadata_vec.payment_method_tokenization {\n let key = format!(\n \"pm_token_{}_{}_{}\",\n parent_payment_method_token, pma.payment_method, pm_metadata.0\n );\n\n redis_conn\n .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time)\n .await\n .change_context(errors::StorageError::KVError)\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to add data in redis\")?;\n }\n }\n }\n\n let mut response = api::CustomerPaymentMethodsListResponse {\n customer_payment_methods: customer_pms,\n is_guest_customer: payment_intent.as_ref().map(|_| false), //to return this key only when the request is tied to a payment intent\n };\n\n Box::pin(perform_surcharge_ops(\n payment_intent,\n state,\n merchant_account,\n key_store,\n business_profile,\n &mut response,\n ))\n .await?;\n\n Ok(services::ApplicationResponse::Json(response))\n}", + "diff_span": { + "before": " .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to decrypt payment method billing address details\")?;\n let connector_mandate_details = pm\n .connector_mandate_details\n .clone()\n .map(|val| {\n val.clone()\n .parse_value::(\"CommonMandateReference\")\n .or_else(|_| {\n val.parse_value::(\n \"PaymentsMandateReference\",\n )\n .map(|payments| {\n diesel_models::CommonMandateReference {\n payments: Some(payments),\n payouts: None,\n }\n })\n })\n })\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference \")?;\n let mca_enabled = get_mca_status(\n state,\n &key_store,\n profile_id.clone(),\n merchant_account.get_id(),\n is_connector_agnostic_mit_enabled,\n connector_mandate_details,\n pm.network_transaction_id.as_ref(),\n )", + "after": " .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to decrypt payment method billing address details\")?;\n let connector_mandate_details = storage::PaymentMethod::get_common_mandate_reference(\n pm.connector_mandate_details.clone(),\n )\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference \")?;\n let mca_enabled = get_mca_status(\n state,\n &key_store,\n profile_id.clone(),\n merchant_account.get_id(),\n is_connector_agnostic_mit_enabled,\n Some(connector_mandate_details),\n pm.network_transaction_id.as_ref(),\n )" + }, + "commit_sha": "90fef342c821e7b10ceaa64c6fa2a286737b9a23" + }, + { + "id": "crates/router/src/core/webhooks/incoming.rs::function::update_connector_mandate_details", + "file": "crates/router/src/core/webhooks/incoming.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "async fn update_connector_mandate_details(\n state: &SessionState,\n merchant_account: &domain::MerchantAccount,\n key_store: &domain::MerchantKeyStore,\n object_ref_id: api::ObjectReferenceId,\n connector: &ConnectorEnum,\n request_details: &IncomingWebhookRequestDetails<'_>,\n) -> CustomResult<(), errors::ApiErrorResponse> {\n let webhook_connector_mandate_details = connector\n .get_mandate_details(request_details)\n .switch()\n .attach_printable(\"Could not find connector mandate details in incoming webhook body\")?;\n\n let webhook_connector_network_transaction_id = connector\n .get_network_txn_id(request_details)\n .switch()\n .attach_printable(\n \"Could not find connector network transaction id in incoming webhook body\",\n )?;\n\n // Either one OR both of the fields are present\n if webhook_connector_mandate_details.is_some()\n || webhook_connector_network_transaction_id.is_some()\n {\n let payment_attempt =\n get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_account)\n .await?;\n if let Some(ref payment_method_id) = payment_attempt.payment_method_id {\n let key_manager_state = &state.into();\n let payment_method_info = state\n .store\n .find_payment_method(\n key_manager_state,\n key_store,\n payment_method_id,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;\n\n // Update connector's mandate details\n let updated_connector_mandate_details =\n if let Some(webhook_mandate_details) = webhook_connector_mandate_details {\n let mandate_details = payment_method_info\n .connector_mandate_details\n .clone()\n .map(|val| {\n val.clone()\n .parse_value::(\n \"CommonMandateReference\",\n )\n .or_else(|_| {\n val.parse_value::(\n \"PaymentsMandateReference\",\n )\n .map(|payments| {\n diesel_models::CommonMandateReference {\n payments: Some(payments),\n payouts: None,\n }\n })\n })\n })\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference\")?;\n\n let merchant_connector_account_id = payment_attempt\n .merchant_connector_id\n .clone()\n .get_required_value(\"merchant_connector_id\")?;\n\n if mandate_details\n .as_ref()\n .map(|details: &diesel_models::CommonMandateReference| {\n !details.payments.as_ref().map_or(false, |payments| {\n payments.0.contains_key(&merchant_connector_account_id)\n })\n })\n .unwrap_or(true)\n {\n // Update the payment attempt to maintain consistency across tables.\n let (mandate_metadata, connector_mandate_request_reference_id) =\n payment_attempt\n .connector_mandate_detail\n .as_ref()\n .map(|details| {\n (\n details.mandate_metadata.clone(),\n details.connector_mandate_request_reference_id.clone(),\n )\n })\n .unwrap_or((None, None));\n\n let connector_mandate_reference_id = ConnectorMandateReferenceId {\n connector_mandate_id: Some(\n webhook_mandate_details\n .connector_mandate_id\n .peek()\n .to_string(),\n ),\n payment_method_id: Some(payment_method_id.to_string()),\n mandate_metadata,\n connector_mandate_request_reference_id,\n };\n\n let attempt_update =\n storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {\n connector_mandate_detail: Some(connector_mandate_reference_id),\n updated_by: merchant_account.storage_scheme.to_string(),\n };\n\n state\n .store\n .update_payment_attempt_with_attempt_id(\n payment_attempt.clone(),\n attempt_update,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n\n insert_mandate_details(\n &payment_attempt,\n &webhook_mandate_details,\n mandate_details,\n )?\n } else {\n logger::info!(\n \"Skipping connector mandate details update since they are already present.\"\n );\n None\n }\n } else {\n None\n };\n\n let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {\n connector_mandate_details: updated_connector_mandate_details.map(masking::Secret::new),\n network_transaction_id: webhook_connector_network_transaction_id\n .map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()),\n };\n\n state\n .store\n .update_payment_method(\n key_manager_state,\n key_store,\n payment_method_info,\n pm_update,\n merchant_account.storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to update payment method in db\")?;\n }\n }\n Ok(())\n}", + "after_code": "async fn update_connector_mandate_details(\n state: &SessionState,\n merchant_account: &domain::MerchantAccount,\n key_store: &domain::MerchantKeyStore,\n object_ref_id: api::ObjectReferenceId,\n connector: &ConnectorEnum,\n request_details: &IncomingWebhookRequestDetails<'_>,\n) -> CustomResult<(), errors::ApiErrorResponse> {\n let webhook_connector_mandate_details = connector\n .get_mandate_details(request_details)\n .switch()\n .attach_printable(\"Could not find connector mandate details in incoming webhook body\")?;\n\n let webhook_connector_network_transaction_id = connector\n .get_network_txn_id(request_details)\n .switch()\n .attach_printable(\n \"Could not find connector network transaction id in incoming webhook body\",\n )?;\n\n // Either one OR both of the fields are present\n if webhook_connector_mandate_details.is_some()\n || webhook_connector_network_transaction_id.is_some()\n {\n let payment_attempt =\n get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_account)\n .await?;\n if let Some(ref payment_method_id) = payment_attempt.payment_method_id {\n let key_manager_state = &state.into();\n let payment_method_info = state\n .store\n .find_payment_method(\n key_manager_state,\n key_store,\n payment_method_id,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;\n\n // Update connector's mandate details\n let updated_connector_mandate_details =\n if let Some(webhook_mandate_details) = webhook_connector_mandate_details {\n let mandate_details = storage::PaymentMethod::get_common_mandate_reference(\n payment_method_info.connector_mandate_details.clone(),\n )\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference\")?;\n\n let merchant_connector_account_id = payment_attempt\n .merchant_connector_id\n .clone()\n .get_required_value(\"merchant_connector_id\")?;\n\n if !mandate_details.payments.as_ref().map_or(false, |payments| {\n payments.0.contains_key(&merchant_connector_account_id)\n }) {\n // Update the payment attempt to maintain consistency across tables.\n let (mandate_metadata, connector_mandate_request_reference_id) =\n payment_attempt\n .connector_mandate_detail\n .as_ref()\n .map(|details| {\n (\n details.mandate_metadata.clone(),\n details.connector_mandate_request_reference_id.clone(),\n )\n })\n .unwrap_or((None, None));\n\n let connector_mandate_reference_id = ConnectorMandateReferenceId {\n connector_mandate_id: Some(\n webhook_mandate_details\n .connector_mandate_id\n .peek()\n .to_string(),\n ),\n payment_method_id: Some(payment_method_id.to_string()),\n mandate_metadata,\n connector_mandate_request_reference_id,\n };\n\n let attempt_update =\n storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {\n connector_mandate_detail: Some(connector_mandate_reference_id),\n updated_by: merchant_account.storage_scheme.to_string(),\n };\n\n state\n .store\n .update_payment_attempt_with_attempt_id(\n payment_attempt.clone(),\n attempt_update,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n\n insert_mandate_details(\n &payment_attempt,\n &webhook_mandate_details,\n Some(mandate_details),\n )?\n } else {\n logger::info!(\n \"Skipping connector mandate details update since they are already present.\"\n );\n None\n }\n } else {\n None\n };\n\n let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {\n connector_mandate_details: updated_connector_mandate_details.map(masking::Secret::new),\n network_transaction_id: webhook_connector_network_transaction_id\n .map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()),\n };\n\n state\n .store\n .update_payment_method(\n key_manager_state,\n key_store,\n payment_method_info,\n pm_update,\n merchant_account.storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to update payment method in db\")?;\n }\n }\n Ok(())\n}", + "diff_span": { + "before": " let updated_connector_mandate_details =\n if let Some(webhook_mandate_details) = webhook_connector_mandate_details {\n let mandate_details = payment_method_info\n .connector_mandate_details\n .clone()\n .map(|val| {\n val.clone()\n .parse_value::(\n \"CommonMandateReference\",\n )\n .or_else(|_| {\n val.parse_value::(\n \"PaymentsMandateReference\",\n )\n .map(|payments| {\n diesel_models::CommonMandateReference {\n payments: Some(payments),\n payouts: None,\n }\n })\n })\n })\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference\")?;\n\n let merchant_connector_account_id = payment_attempt\n .merchant_connector_id\n .clone()\n .get_required_value(\"merchant_connector_id\")?;\n\n if mandate_details\n .as_ref()\n .map(|details: &diesel_models::CommonMandateReference| {\n !details.payments.as_ref().map_or(false, |payments| {\n payments.0.contains_key(&merchant_connector_account_id)\n })\n })\n .unwrap_or(true)\n {\n // Update the payment attempt to maintain consistency across tables.\n let (mandate_metadata, connector_mandate_request_reference_id) =\n payment_attempt\n .connector_mandate_detail\n .as_ref()\n .map(|details| {\n (\n details.mandate_metadata.clone(),\n details.connector_mandate_request_reference_id.clone(),\n )\n })\n .unwrap_or((None, None));\n\n let connector_mandate_reference_id = ConnectorMandateReferenceId {\n connector_mandate_id: Some(\n webhook_mandate_details\n .connector_mandate_id\n .peek()\n .to_string(),\n ),\n payment_method_id: Some(payment_method_id.to_string()),\n mandate_metadata,\n connector_mandate_request_reference_id,\n };\n\n let attempt_update =\n storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {\n connector_mandate_detail: Some(connector_mandate_reference_id),\n updated_by: merchant_account.storage_scheme.to_string(),\n };\n\n state\n .store\n .update_payment_attempt_with_attempt_id(\n payment_attempt.clone(),\n attempt_update,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n\n insert_mandate_details(\n &payment_attempt,\n &webhook_mandate_details,\n mandate_details,\n )?\n } else {", + "after": " let updated_connector_mandate_details =\n if let Some(webhook_mandate_details) = webhook_connector_mandate_details {\n let mandate_details = storage::PaymentMethod::get_common_mandate_reference(\n payment_method_info.connector_mandate_details.clone(),\n )\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize to Payment Mandate Reference\")?;\n\n let merchant_connector_account_id = payment_attempt\n .merchant_connector_id\n .clone()\n .get_required_value(\"merchant_connector_id\")?;\n\n if !mandate_details.payments.as_ref().map_or(false, |payments| {\n payments.0.contains_key(&merchant_connector_account_id)\n }) {\n // Update the payment attempt to maintain consistency across tables.\n let (mandate_metadata, connector_mandate_request_reference_id) =\n payment_attempt\n .connector_mandate_detail\n .as_ref()\n .map(|details| {\n (\n details.mandate_metadata.clone(),\n details.connector_mandate_request_reference_id.clone(),\n )\n })\n .unwrap_or((None, None));\n\n let connector_mandate_reference_id = ConnectorMandateReferenceId {\n connector_mandate_id: Some(\n webhook_mandate_details\n .connector_mandate_id\n .peek()\n .to_string(),\n ),\n payment_method_id: Some(payment_method_id.to_string()),\n mandate_metadata,\n connector_mandate_request_reference_id,\n };\n\n let attempt_update =\n storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {\n connector_mandate_detail: Some(connector_mandate_reference_id),\n updated_by: merchant_account.storage_scheme.to_string(),\n };\n\n state\n .store\n .update_payment_attempt_with_attempt_id(\n payment_attempt.clone(),\n attempt_update,\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n\n insert_mandate_details(\n &payment_attempt,\n &webhook_mandate_details,\n Some(mandate_details),\n )?\n } else {" + }, + "commit_sha": "90fef342c821e7b10ceaa64c6fa2a286737b9a23" + }, + { + "id": "crates/router/src/core/payments/helpers.rs::function::validate_merchant_connector_ids_in_connector_mandate_details", + "file": "crates/router/src/core/payments/helpers.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub async fn validate_merchant_connector_ids_in_connector_mandate_details(\n state: &SessionState,\n key_store: &domain::MerchantKeyStore,\n connector_mandate_details: &api_models::payment_methods::CommonMandateReference,\n merchant_id: &id_type::MerchantId,\n card_network: Option,\n) -> CustomResult<(), errors::ApiErrorResponse> {\n let db = &*state.store;\n let merchant_connector_account_list = db\n .find_merchant_connector_account_by_merchant_id_and_disabled_list(\n &state.into(),\n merchant_id,\n true,\n key_store,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;\n\n let merchant_connector_account_details_hash_map: std::collections::HashMap<\n id_type::MerchantConnectorAccountId,\n domain::MerchantConnectorAccount,\n > = merchant_connector_account_list\n .iter()\n .map(|merchant_connector_account| {\n (\n merchant_connector_account.get_id(),\n merchant_connector_account.clone(),\n )\n })\n .collect();\n\n if let Some(payment_mandate_reference) = &connector_mandate_details.payments {\n let payments_map = payment_mandate_reference.0.clone();\n for (migrating_merchant_connector_id, migrating_connector_mandate_details) in payments_map {\n match (\n card_network.clone(),\n merchant_connector_account_details_hash_map.get(&migrating_merchant_connector_id),\n ) {\n (Some(enums::CardNetwork::Discover), Some(merchant_connector_account_details)) => {\n if let (\"cybersource\", None) = (\n merchant_connector_account_details.connector_name.as_str(),\n migrating_connector_mandate_details\n .original_payment_authorized_amount\n .zip(\n migrating_connector_mandate_details\n .original_payment_authorized_currency,\n ),\n ) {\n return Err(errors::ApiErrorResponse::MissingRequiredFields {\n field_names: vec![\n \"original_payment_authorized_currency\",\n \"original_payment_authorized_amount\",\n ],\n })\n .attach_printable(format!(\n \"Invalid connector_mandate_details provided for connector {:?}\",\n migrating_merchant_connector_id\n ))?;\n }\n }\n (_, Some(_)) => (),\n (_, None) => {\n return Err(errors::ApiErrorResponse::InvalidDataValue {\n field_name: \"merchant_connector_id\",\n })\n .attach_printable_lazy(|| {\n format!(\n \"{:?} invalid merchant connector id in connector_mandate_details\",\n migrating_merchant_connector_id\n )\n })?\n }\n }\n }\n }\n Ok(())\n}", + "after_code": "pub async fn validate_merchant_connector_ids_in_connector_mandate_details(\n state: &SessionState,\n key_store: &domain::MerchantKeyStore,\n connector_mandate_details: &api_models::payment_methods::CommonMandateReference,\n merchant_id: &id_type::MerchantId,\n card_network: Option,\n) -> CustomResult<(), errors::ApiErrorResponse> {\n let db = &*state.store;\n let merchant_connector_account_list = db\n .find_merchant_connector_account_by_merchant_id_and_disabled_list(\n &state.into(),\n merchant_id,\n true,\n key_store,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;\n\n let merchant_connector_account_details_hash_map: std::collections::HashMap<\n id_type::MerchantConnectorAccountId,\n domain::MerchantConnectorAccount,\n > = merchant_connector_account_list\n .iter()\n .map(|merchant_connector_account| {\n (\n merchant_connector_account.get_id(),\n merchant_connector_account.clone(),\n )\n })\n .collect();\n\n if let Some(payment_mandate_reference) = &connector_mandate_details.payments {\n let payments_map = payment_mandate_reference.0.clone();\n for (migrating_merchant_connector_id, migrating_connector_mandate_details) in payments_map {\n match (\n card_network.clone(),\n merchant_connector_account_details_hash_map.get(&migrating_merchant_connector_id),\n ) {\n (Some(enums::CardNetwork::Discover), Some(merchant_connector_account_details)) => {\n if let (\"cybersource\", None) = (\n merchant_connector_account_details.connector_name.as_str(),\n migrating_connector_mandate_details\n .original_payment_authorized_amount\n .zip(\n migrating_connector_mandate_details\n .original_payment_authorized_currency,\n ),\n ) {\n Err(errors::ApiErrorResponse::MissingRequiredFields {\n field_names: vec![\n \"original_payment_authorized_currency\",\n \"original_payment_authorized_amount\",\n ],\n })\n .attach_printable(format!(\n \"Invalid connector_mandate_details provided for connector {:?}\",\n migrating_merchant_connector_id\n ))?\n }\n }\n (_, Some(_)) => (),\n (_, None) => Err(errors::ApiErrorResponse::InvalidDataValue {\n field_name: \"merchant_connector_id\",\n })\n .attach_printable_lazy(|| {\n format!(\n \"{:?} invalid merchant connector id in connector_mandate_details\",\n migrating_merchant_connector_id\n )\n })?,\n }\n }\n }\n Ok(())\n}", + "diff_span": { + "before": " ),\n ) {\n return Err(errors::ApiErrorResponse::MissingRequiredFields {\n field_names: vec![\n \"original_payment_authorized_currency\",\n \"original_payment_authorized_amount\",\n ],\n })\n .attach_printable(format!(\n \"Invalid connector_mandate_details provided for connector {:?}\",\n migrating_merchant_connector_id\n ))?;\n }\n }\n (_, Some(_)) => (),\n (_, None) => {\n return Err(errors::ApiErrorResponse::InvalidDataValue {\n field_name: \"merchant_connector_id\",\n })\n .attach_printable_lazy(|| {\n format!(\n \"{:?} invalid merchant connector id in connector_mandate_details\",\n migrating_merchant_connector_id\n )\n })?\n }\n }\n }", + "after": " ),\n ) {\n Err(errors::ApiErrorResponse::MissingRequiredFields {\n field_names: vec![\n \"original_payment_authorized_currency\",\n \"original_payment_authorized_amount\",\n ],\n })\n .attach_printable(format!(\n \"Invalid connector_mandate_details provided for connector {:?}\",\n migrating_merchant_connector_id\n ))?\n }\n }\n (_, Some(_)) => (),\n (_, None) => Err(errors::ApiErrorResponse::InvalidDataValue {\n field_name: \"merchant_connector_id\",\n })\n .attach_printable_lazy(|| {\n format!(\n \"{:?} invalid merchant connector id in connector_mandate_details\",\n migrating_merchant_connector_id\n )\n })?,\n }\n }" + }, + "commit_sha": "90fef342c821e7b10ceaa64c6fa2a286737b9a23" + }, + { + "id": "crates/router/src/core/payments/operations/payment_response.rs::function::payment_response_update_tracker", + "file": "crates/router/src/core/payments/operations/payment_response.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "async fn payment_response_update_tracker(\n state: &SessionState,\n mut payment_data: PaymentData,\n router_data: types::RouterData,\n key_store: &domain::MerchantKeyStore,\n storage_scheme: enums::MerchantStorageScheme,\n locale: &Option,\n #[cfg(all(feature = \"v1\", feature = \"dynamic_routing\"))] routable_connectors: Vec<\n RoutableConnectorChoice,\n >,\n #[cfg(all(feature = \"v1\", feature = \"dynamic_routing\"))] business_profile: &domain::Profile,\n) -> RouterResult> {\n // Update additional payment data with the payment method response that we received from connector\n // This is for details like whether 3ds was upgraded and which version of 3ds was used\n // also some connectors might send card network details in the response, which is captured and stored\n\n let additional_payment_method_data = match payment_data.payment_method_data.clone() {\n Some(payment_method_data) => match payment_method_data {\n hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardRedirect(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::PayLater(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankDebit(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankTransfer(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Crypto(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::MandatePayment\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::RealTimePayment(\n _,\n )\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::MobilePayment(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Voucher(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::GiftCard(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardToken(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::OpenBanking(_) => {\n update_additional_payment_data_with_connector_response_pm_data(\n payment_data.payment_attempt.payment_method_data.clone(),\n router_data\n .connector_response\n .as_ref()\n .and_then(|connector_response| {\n connector_response.additional_payment_method_data.clone()\n }),\n )?\n }\n hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_) => {\n payment_data.payment_attempt.payment_method_data.clone()\n }\n hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {\n payment_data.payment_attempt.payment_method_data.clone()\n }\n },\n None => None,\n };\n\n router_data.payment_method_status.and_then(|status| {\n payment_data\n .payment_method_info\n .as_mut()\n .map(|info| info.status = status)\n });\n let (capture_update, mut payment_attempt_update) = match router_data.response.clone() {\n Err(err) => {\n let auth_update = if Some(router_data.auth_type)\n != payment_data.payment_attempt.authentication_type\n {\n Some(router_data.auth_type)\n } else {\n None\n };\n let (capture_update, attempt_update) = match payment_data.multiple_capture_data {\n Some(multiple_capture_data) => {\n let capture_update = storage::CaptureUpdate::ErrorUpdate {\n status: match err.status_code {\n 500..=511 => enums::CaptureStatus::Pending,\n _ => enums::CaptureStatus::Failed,\n },\n error_code: Some(err.code),\n error_message: Some(err.message),\n error_reason: err.reason,\n };\n let capture_update_list = vec![(\n multiple_capture_data.get_latest_capture().clone(),\n capture_update,\n )];\n (\n Some((multiple_capture_data, capture_update_list)),\n auth_update.map(|auth_type| {\n storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {\n authentication_type: auth_type,\n updated_by: storage_scheme.to_string(),\n }\n }),\n )\n }\n None => {\n let connector_name = router_data.connector.to_string();\n let flow_name = core_utils::get_flow_name::()?;\n let option_gsm = payments_helpers::get_gsm_record(\n state,\n Some(err.code.clone()),\n Some(err.message.clone()),\n connector_name,\n flow_name.clone(),\n )\n .await;\n\n let gsm_unified_code =\n option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());\n let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);\n\n let (unified_code, unified_message) = if let Some((code, message)) =\n gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref())\n {\n (code.to_owned(), message.to_owned())\n } else {\n (\n consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),\n consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),\n )\n };\n let unified_translated_message = locale\n .as_ref()\n .async_and_then(|locale_str| async {\n payments_helpers::get_unified_translation(\n state,\n unified_code.to_owned(),\n unified_message.to_owned(),\n locale_str.to_owned(),\n )\n .await\n })\n .await\n .or(Some(unified_message));\n\n let status = match err.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None =>\n // mark previous attempt status for technical failures in PSync flow\n {\n if flow_name == \"PSync\" {\n match err.status_code {\n // marking failure for 2xx because this is genuine payment failure\n 200..=299 => enums::AttemptStatus::Failure,\n _ => router_data.status,\n }\n } else if flow_name == \"Capture\" {\n match err.status_code {\n 500..=511 => enums::AttemptStatus::Pending,\n // don't update the status for 429 error status\n 429 => router_data.status,\n _ => enums::AttemptStatus::Failure,\n }\n } else {\n match err.status_code {\n 500..=511 => enums::AttemptStatus::Pending,\n _ => enums::AttemptStatus::Failure,\n }\n }\n }\n };\n (\n None,\n Some(storage::PaymentAttemptUpdate::ErrorUpdate {\n connector: None,\n status,\n error_message: Some(Some(err.message)),\n error_code: Some(Some(err.code)),\n error_reason: Some(err.reason),\n amount_capturable: router_data\n .request\n .get_amount_capturable(&payment_data, status)\n .map(MinorUnit::new),\n updated_by: storage_scheme.to_string(),\n unified_code: Some(Some(unified_code)),\n unified_message: Some(unified_translated_message),\n connector_transaction_id: err.connector_transaction_id,\n payment_method_data: additional_payment_method_data,\n authentication_type: auth_update,\n }),\n )\n }\n };\n (capture_update, attempt_update)\n }\n\n Ok(payments_response) => {\n // match on connector integrity check\n match router_data.integrity_check.clone() {\n Err(err) => {\n let auth_update = if Some(router_data.auth_type)\n != payment_data.payment_attempt.authentication_type\n {\n Some(router_data.auth_type)\n } else {\n None\n };\n let field_name = err.field_names;\n let connector_transaction_id = err.connector_transaction_id;\n (\n None,\n Some(storage::PaymentAttemptUpdate::ErrorUpdate {\n connector: None,\n status: enums::AttemptStatus::Pending,\n error_message: Some(Some(\"Integrity Check Failed!\".to_string())),\n error_code: Some(Some(\"IE\".to_string())),\n error_reason: Some(Some(format!(\n \"Integrity Check Failed! Value mismatched for fields {field_name}\"\n ))),\n amount_capturable: None,\n updated_by: storage_scheme.to_string(),\n unified_code: None,\n unified_message: None,\n connector_transaction_id,\n payment_method_data: None,\n authentication_type: auth_update,\n }),\n )\n }\n Ok(()) => {\n let attempt_status = payment_data.payment_attempt.status.to_owned();\n let connector_status = router_data.status.to_owned();\n let updated_attempt_status = match (\n connector_status,\n attempt_status,\n payment_data.frm_message.to_owned(),\n ) {\n (\n enums::AttemptStatus::Authorized,\n enums::AttemptStatus::Unresolved,\n Some(frm_message),\n ) => match frm_message.frm_status {\n enums::FraudCheckStatus::Fraud\n | enums::FraudCheckStatus::ManualReview => attempt_status,\n _ => router_data.get_attempt_status_for_db_update(&payment_data),\n },\n _ => router_data.get_attempt_status_for_db_update(&payment_data),\n };\n match payments_response {\n types::PaymentsResponseData::PreProcessingResponse {\n pre_processing_id,\n connector_metadata,\n connector_response_reference_id,\n ..\n } => {\n let connector_transaction_id = match pre_processing_id.to_owned() {\n types::PreprocessingResponseId::PreProcessingId(_) => None,\n\n types::PreprocessingResponseId::ConnectorTransactionId(\n connector_txn_id,\n ) => Some(connector_txn_id),\n };\n let preprocessing_step_id = match pre_processing_id {\n types::PreprocessingResponseId::PreProcessingId(\n pre_processing_id,\n ) => Some(pre_processing_id),\n types::PreprocessingResponseId::ConnectorTransactionId(_) => None,\n };\n let payment_attempt_update =\n storage::PaymentAttemptUpdate::PreprocessingUpdate {\n status: updated_attempt_status,\n payment_method_id: payment_data\n .payment_attempt\n .payment_method_id\n .clone(),\n connector_metadata,\n preprocessing_step_id,\n connector_transaction_id,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n };\n\n (None, Some(payment_attempt_update))\n }\n types::PaymentsResponseData::TransactionResponse {\n resource_id,\n redirection_data,\n connector_metadata,\n connector_response_reference_id,\n incremental_authorization_allowed,\n charge_id,\n ..\n } => {\n payment_data\n .payment_intent\n .incremental_authorization_allowed =\n core_utils::get_incremental_authorization_allowed_value(\n incremental_authorization_allowed,\n payment_data\n .payment_intent\n .request_incremental_authorization,\n );\n let connector_transaction_id = match resource_id {\n types::ResponseId::NoResponseId => None,\n types::ResponseId::ConnectorTransactionId(ref id)\n | types::ResponseId::EncodedData(ref id) => Some(id),\n };\n\n let encoded_data = payment_data.payment_attempt.encoded_data.clone();\n\n let authentication_data = (*redirection_data)\n .as_ref()\n .map(Encode::encode_to_value)\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Could not parse the connector response\")?;\n\n let auth_update = if Some(router_data.auth_type)\n != payment_data.payment_attempt.authentication_type\n {\n Some(router_data.auth_type)\n } else {\n None\n };\n\n // incase of success, update error code and error message\n let error_status =\n if router_data.status == enums::AttemptStatus::Charged {\n Some(None)\n } else {\n None\n };\n // update connector_mandate_details in case of Authorized/Charged Payment Status\n if matches!(\n router_data.status,\n enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized\n ) {\n payment_data\n .payment_intent\n .fingerprint_id\n .clone_from(&payment_data.payment_attempt.fingerprint_id);\n\n if let Some(payment_method) =\n payment_data.payment_method_info.clone()\n {\n // Parse value to check for mandates' existence\n let mandate_details = payment_method\n .connector_mandate_details\n .clone()\n .map(|val| {\n val.clone()\n .parse_value::(\"CommonMandateReference\")\n .or_else(|_| {\n val.parse_value::(\"PaymentsMandateReference\")\n .map(|payments| diesel_models::CommonMandateReference {\n payments: Some(payments),\n payouts: None,\n })\n })\n })\n .transpose()\n .change_context(\n errors::ApiErrorResponse::InternalServerError,\n )\n .attach_printable(\n \"Failed to deserialize to Payment Mandate Reference \",\n )?;\n\n if let Some(mca_id) =\n payment_data.payment_attempt.merchant_connector_id.clone()\n {\n // check if the mandate has not already been set to active\n if !mandate_details\n .as_ref()\n .map(|common_mandate_reference| {\n\n common_mandate_reference.payments\n .as_ref()\n .and_then(|payments| payments.0.get(&mca_id))\n .map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active))\n .unwrap_or(false)\n })\n .unwrap_or(false)\n {\n\n let (connector_mandate_id, mandate_metadata,connector_mandate_request_reference_id) = payment_data.payment_attempt.connector_mandate_detail.clone()\n .map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata,cmr.connector_mandate_request_reference_id))\n .unwrap_or((None, None,None));\n // Update the connector mandate details with the payment attempt connector mandate id\n let connector_mandate_details =\n tokenization::update_connector_mandate_details(\n mandate_details,\n payment_data.payment_attempt.payment_method_type,\n Some(\n payment_data\n .payment_attempt\n .net_amount\n .get_total_amount()\n .get_amount_as_i64(),\n ),\n payment_data.payment_attempt.currency,\n payment_data.payment_attempt.merchant_connector_id.clone(),\n connector_mandate_id,\n mandate_metadata,\n connector_mandate_request_reference_id\n )?;\n // Update the payment method table with the active mandate record\n payment_methods::cards::update_payment_method_connector_mandate_details(\n state,\n key_store,\n &*state.store,\n payment_method,\n connector_mandate_details,\n storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to update payment method in db\")?;\n }\n }\n }\n\n metrics::SUCCESSFUL_PAYMENT.add(1, &[]);\n }\n\n let payment_method_id =\n payment_data.payment_attempt.payment_method_id.clone();\n\n utils::add_apple_pay_payment_status_metrics(\n router_data.status,\n router_data.apple_pay_flow.clone(),\n payment_data.payment_attempt.connector.clone(),\n payment_data.payment_attempt.merchant_id.clone(),\n );\n let (capture_updates, payment_attempt_update) = match payment_data\n .multiple_capture_data\n {\n Some(multiple_capture_data) => {\n let (connector_capture_id, connector_capture_data) =\n match resource_id {\n types::ResponseId::NoResponseId => (None, None),\n types::ResponseId::ConnectorTransactionId(id)\n | types::ResponseId::EncodedData(id) => {\n let (txn_id, txn_data) =\n ConnectorTransactionId::form_id_and_data(id);\n (Some(txn_id), txn_data)\n }\n };\n let capture_update = storage::CaptureUpdate::ResponseUpdate {\n status: enums::CaptureStatus::foreign_try_from(\n router_data.status,\n )?,\n connector_capture_id: connector_capture_id.clone(),\n connector_response_reference_id,\n connector_capture_data: connector_capture_data.clone(),\n };\n let capture_update_list = vec![(\n multiple_capture_data.get_latest_capture().clone(),\n capture_update,\n )];\n (Some((multiple_capture_data, capture_update_list)), auth_update.map(|auth_type| {\n storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {\n authentication_type: auth_type,\n updated_by: storage_scheme.to_string(),\n }\n }))\n }\n None => (\n None,\n Some(storage::PaymentAttemptUpdate::ResponseUpdate {\n status: updated_attempt_status,\n connector: None,\n connector_transaction_id: connector_transaction_id.cloned(),\n authentication_type: auth_update,\n amount_capturable: router_data\n .request\n .get_amount_capturable(\n &payment_data,\n updated_attempt_status,\n )\n .map(MinorUnit::new),\n payment_method_id,\n mandate_id: payment_data.payment_attempt.mandate_id.clone(),\n connector_metadata,\n payment_token: None,\n error_code: error_status.clone(),\n error_message: error_status.clone(),\n error_reason: error_status.clone(),\n unified_code: error_status.clone(),\n unified_message: error_status,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n authentication_data,\n encoded_data,\n payment_method_data: additional_payment_method_data,\n charge_id,\n connector_mandate_detail: payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone(),\n }),\n ),\n };\n\n (capture_updates, payment_attempt_update)\n }\n types::PaymentsResponseData::TransactionUnresolvedResponse {\n resource_id,\n reason,\n connector_response_reference_id,\n } => {\n let connector_transaction_id = match resource_id {\n types::ResponseId::NoResponseId => None,\n types::ResponseId::ConnectorTransactionId(id)\n | types::ResponseId::EncodedData(id) => Some(id),\n };\n (\n None,\n Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate {\n status: updated_attempt_status,\n connector: None,\n connector_transaction_id,\n payment_method_id: payment_data\n .payment_attempt\n .payment_method_id\n .clone(),\n error_code: Some(reason.clone().map(|cd| cd.code)),\n error_message: Some(reason.clone().map(|cd| cd.message)),\n error_reason: Some(reason.map(|cd| cd.message)),\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n }),\n )\n }\n types::PaymentsResponseData::SessionResponse { .. } => (None, None),\n types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),\n types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),\n types::PaymentsResponseData::ConnectorCustomerResponse { .. } => {\n (None, None)\n }\n types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {\n (None, None)\n }\n types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None),\n types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => (None, None),\n types::PaymentsResponseData::SessionUpdateResponse { .. } => (None, None),\n types::PaymentsResponseData::MultipleCaptureResponse {\n capture_sync_response_list,\n } => match payment_data.multiple_capture_data {\n Some(multiple_capture_data) => {\n let capture_update_list = response_to_capture_update(\n &multiple_capture_data,\n capture_sync_response_list,\n )?;\n (Some((multiple_capture_data, capture_update_list)), None)\n }\n None => (None, None),\n },\n }\n }\n }\n }\n };\n payment_data.multiple_capture_data = match capture_update {\n Some((mut multiple_capture_data, capture_updates)) => {\n for (capture, capture_update) in capture_updates {\n let updated_capture = state\n .store\n .update_capture_with_capture_id(capture, capture_update, storage_scheme)\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n multiple_capture_data.update_capture(updated_capture);\n }\n\n let authorized_amount = payment_data.payment_attempt.get_total_amount();\n\n payment_attempt_update = Some(storage::PaymentAttemptUpdate::AmountToCaptureUpdate {\n status: multiple_capture_data.get_attempt_status(authorized_amount),\n amount_capturable: authorized_amount\n - multiple_capture_data.get_total_blocked_amount(),\n updated_by: storage_scheme.to_string(),\n });\n Some(multiple_capture_data)\n }\n None => None,\n };\n\n // Stage 1\n\n let payment_attempt = payment_data.payment_attempt.clone();\n\n let m_db = state.clone().store;\n let m_payment_attempt_update = payment_attempt_update.clone();\n let m_payment_attempt = payment_attempt.clone();\n\n let payment_attempt = payment_attempt_update\n .map(|payment_attempt_update| {\n PaymentAttempt::from_storage_model(\n payment_attempt_update\n .to_storage_model()\n .apply_changeset(payment_attempt.clone().to_storage_model()),\n )\n })\n .unwrap_or_else(|| payment_attempt);\n\n let payment_attempt_fut = tokio::spawn(\n async move {\n Box::pin(async move {\n Ok::<_, error_stack::Report>(\n match m_payment_attempt_update {\n Some(payment_attempt_update) => m_db\n .update_payment_attempt_with_attempt_id(\n m_payment_attempt,\n payment_attempt_update,\n storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,\n None => m_payment_attempt,\n },\n )\n })\n .await\n }\n .in_current_span(),\n );\n\n payment_data.payment_attempt = payment_attempt;\n\n payment_data.authentication = match payment_data.authentication {\n Some(authentication) => {\n let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate {\n authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used,\n };\n let updated_authentication = state\n .store\n .update_authentication_by_merchant_id_authentication_id(\n authentication,\n authentication_update,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n Some(updated_authentication)\n }\n None => None,\n };\n\n let amount_captured = get_total_amount_captured(\n &router_data.request,\n router_data.amount_captured.map(MinorUnit::new),\n router_data.status,\n &payment_data,\n );\n\n let payment_intent_update = match &router_data.response {\n Err(_) => storage::PaymentIntentUpdate::PGStatusUpdate {\n status: api_models::enums::IntentStatus::foreign_from(\n payment_data.payment_attempt.status,\n ),\n updated_by: storage_scheme.to_string(),\n // make this false only if initial payment fails, if incremental authorization call fails don't make it false\n incremental_authorization_allowed: Some(false),\n },\n Ok(_) => storage::PaymentIntentUpdate::ResponseUpdate {\n status: api_models::enums::IntentStatus::foreign_from(\n payment_data.payment_attempt.status,\n ),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(),\n incremental_authorization_allowed: payment_data\n .payment_intent\n .incremental_authorization_allowed,\n },\n };\n\n let m_db = state.clone().store;\n let m_key_store = key_store.clone();\n let m_payment_data_payment_intent = payment_data.payment_intent.clone();\n let m_payment_intent_update = payment_intent_update.clone();\n let key_manager_state: KeyManagerState = state.into();\n let payment_intent_fut = tokio::spawn(\n async move {\n m_db.update_payment_intent(\n &key_manager_state,\n m_payment_data_payment_intent,\n m_payment_intent_update,\n &m_key_store,\n storage_scheme,\n )\n .map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))\n .await\n }\n .in_current_span(),\n );\n\n // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize\n let m_db = state.clone().store;\n let m_router_data_merchant_id = router_data.merchant_id.clone();\n let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();\n let m_payment_data_mandate_id =\n payment_data\n .payment_attempt\n .mandate_id\n .clone()\n .or(payment_data\n .mandate_id\n .clone()\n .and_then(|mandate_ids| mandate_ids.mandate_id));\n let m_router_data_response = router_data.response.clone();\n let mandate_update_fut = tokio::spawn(\n async move {\n mandate::update_connector_mandate_id(\n m_db.as_ref(),\n &m_router_data_merchant_id,\n m_payment_data_mandate_id,\n m_payment_method_id,\n m_router_data_response,\n storage_scheme,\n )\n .await\n }\n .in_current_span(),\n );\n\n let (payment_intent, _, payment_attempt) = futures::try_join!(\n utils::flatten_join_error(payment_intent_fut),\n utils::flatten_join_error(mandate_update_fut),\n utils::flatten_join_error(payment_attempt_fut)\n )?;\n\n #[cfg(all(feature = \"v1\", feature = \"dynamic_routing\"))]\n {\n if payment_intent.status.is_in_terminal_state()\n && business_profile.dynamic_routing_algorithm.is_some()\n {\n let state = state.clone();\n let business_profile = business_profile.clone();\n let payment_attempt = payment_attempt.clone();\n let success_based_routing_config_params_interpolator =\n routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(\n payment_attempt.payment_method,\n payment_attempt.payment_method_type,\n payment_attempt.authentication_type,\n payment_attempt.currency,\n payment_data\n .address\n .get_payment_billing()\n .and_then(|address| address.clone().address)\n .and_then(|address| address.country),\n payment_attempt\n .payment_method_data\n .as_ref()\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card\"))\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card_network\"))\n .and_then(|network| network.as_str())\n .map(|network| network.to_string()),\n payment_attempt\n .payment_method_data\n .as_ref()\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card\"))\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card_isin\"))\n .and_then(|card_isin| card_isin.as_str())\n .map(|card_isin| card_isin.to_string()),\n );\n tokio::spawn(\n async move {\n routing_helpers::push_metrics_with_update_window_for_success_based_routing(\n &state,\n &payment_attempt,\n routable_connectors,\n &business_profile,\n success_based_routing_config_params_interpolator,\n )\n .await\n .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))\n .ok();\n }\n .in_current_span(),\n );\n }\n }\n\n payment_data.payment_intent = payment_intent;\n payment_data.payment_attempt = payment_attempt;\n router_data.payment_method_status.and_then(|status| {\n payment_data\n .payment_method_info\n .as_mut()\n .map(|info| info.status = status)\n });\n\n match router_data.integrity_check {\n Ok(()) => Ok(payment_data),\n Err(err) => {\n metrics::INTEGRITY_CHECK_FAILED.add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n payment_data\n .payment_attempt\n .connector\n .clone()\n .unwrap_or_default(),\n ),\n (\n \"merchant_id\",\n payment_data.payment_attempt.merchant_id.clone(),\n )\n ),\n );\n Err(error_stack::Report::new(\n errors::ApiErrorResponse::IntegrityCheckFailed {\n connector_transaction_id: payment_data\n .payment_attempt\n .get_connector_payment_id()\n .map(ToString::to_string),\n reason: payment_data\n .payment_attempt\n .error_message\n .unwrap_or_default(),\n field_names: err.field_names,\n },\n ))\n }\n }\n}", + "after_code": "async fn payment_response_update_tracker(\n state: &SessionState,\n mut payment_data: PaymentData,\n router_data: types::RouterData,\n key_store: &domain::MerchantKeyStore,\n storage_scheme: enums::MerchantStorageScheme,\n locale: &Option,\n #[cfg(all(feature = \"v1\", feature = \"dynamic_routing\"))] routable_connectors: Vec<\n RoutableConnectorChoice,\n >,\n #[cfg(all(feature = \"v1\", feature = \"dynamic_routing\"))] business_profile: &domain::Profile,\n) -> RouterResult> {\n // Update additional payment data with the payment method response that we received from connector\n // This is for details like whether 3ds was upgraded and which version of 3ds was used\n // also some connectors might send card network details in the response, which is captured and stored\n\n let additional_payment_method_data = match payment_data.payment_method_data.clone() {\n Some(payment_method_data) => match payment_method_data {\n hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardRedirect(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::PayLater(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankDebit(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankTransfer(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Crypto(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::MandatePayment\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::RealTimePayment(\n _,\n )\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::MobilePayment(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::Voucher(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::GiftCard(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardToken(_)\n | hyperswitch_domain_models::payment_method_data::PaymentMethodData::OpenBanking(_) => {\n update_additional_payment_data_with_connector_response_pm_data(\n payment_data.payment_attempt.payment_method_data.clone(),\n router_data\n .connector_response\n .as_ref()\n .and_then(|connector_response| {\n connector_response.additional_payment_method_data.clone()\n }),\n )?\n }\n hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_) => {\n payment_data.payment_attempt.payment_method_data.clone()\n }\n hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {\n payment_data.payment_attempt.payment_method_data.clone()\n }\n },\n None => None,\n };\n\n router_data.payment_method_status.and_then(|status| {\n payment_data\n .payment_method_info\n .as_mut()\n .map(|info| info.status = status)\n });\n let (capture_update, mut payment_attempt_update) = match router_data.response.clone() {\n Err(err) => {\n let auth_update = if Some(router_data.auth_type)\n != payment_data.payment_attempt.authentication_type\n {\n Some(router_data.auth_type)\n } else {\n None\n };\n let (capture_update, attempt_update) = match payment_data.multiple_capture_data {\n Some(multiple_capture_data) => {\n let capture_update = storage::CaptureUpdate::ErrorUpdate {\n status: match err.status_code {\n 500..=511 => enums::CaptureStatus::Pending,\n _ => enums::CaptureStatus::Failed,\n },\n error_code: Some(err.code),\n error_message: Some(err.message),\n error_reason: err.reason,\n };\n let capture_update_list = vec![(\n multiple_capture_data.get_latest_capture().clone(),\n capture_update,\n )];\n (\n Some((multiple_capture_data, capture_update_list)),\n auth_update.map(|auth_type| {\n storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {\n authentication_type: auth_type,\n updated_by: storage_scheme.to_string(),\n }\n }),\n )\n }\n None => {\n let connector_name = router_data.connector.to_string();\n let flow_name = core_utils::get_flow_name::()?;\n let option_gsm = payments_helpers::get_gsm_record(\n state,\n Some(err.code.clone()),\n Some(err.message.clone()),\n connector_name,\n flow_name.clone(),\n )\n .await;\n\n let gsm_unified_code =\n option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());\n let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);\n\n let (unified_code, unified_message) = if let Some((code, message)) =\n gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref())\n {\n (code.to_owned(), message.to_owned())\n } else {\n (\n consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),\n consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),\n )\n };\n let unified_translated_message = locale\n .as_ref()\n .async_and_then(|locale_str| async {\n payments_helpers::get_unified_translation(\n state,\n unified_code.to_owned(),\n unified_message.to_owned(),\n locale_str.to_owned(),\n )\n .await\n })\n .await\n .or(Some(unified_message));\n\n let status = match err.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None =>\n // mark previous attempt status for technical failures in PSync flow\n {\n if flow_name == \"PSync\" {\n match err.status_code {\n // marking failure for 2xx because this is genuine payment failure\n 200..=299 => enums::AttemptStatus::Failure,\n _ => router_data.status,\n }\n } else if flow_name == \"Capture\" {\n match err.status_code {\n 500..=511 => enums::AttemptStatus::Pending,\n // don't update the status for 429 error status\n 429 => router_data.status,\n _ => enums::AttemptStatus::Failure,\n }\n } else {\n match err.status_code {\n 500..=511 => enums::AttemptStatus::Pending,\n _ => enums::AttemptStatus::Failure,\n }\n }\n }\n };\n (\n None,\n Some(storage::PaymentAttemptUpdate::ErrorUpdate {\n connector: None,\n status,\n error_message: Some(Some(err.message)),\n error_code: Some(Some(err.code)),\n error_reason: Some(err.reason),\n amount_capturable: router_data\n .request\n .get_amount_capturable(&payment_data, status)\n .map(MinorUnit::new),\n updated_by: storage_scheme.to_string(),\n unified_code: Some(Some(unified_code)),\n unified_message: Some(unified_translated_message),\n connector_transaction_id: err.connector_transaction_id,\n payment_method_data: additional_payment_method_data,\n authentication_type: auth_update,\n }),\n )\n }\n };\n (capture_update, attempt_update)\n }\n\n Ok(payments_response) => {\n // match on connector integrity check\n match router_data.integrity_check.clone() {\n Err(err) => {\n let auth_update = if Some(router_data.auth_type)\n != payment_data.payment_attempt.authentication_type\n {\n Some(router_data.auth_type)\n } else {\n None\n };\n let field_name = err.field_names;\n let connector_transaction_id = err.connector_transaction_id;\n (\n None,\n Some(storage::PaymentAttemptUpdate::ErrorUpdate {\n connector: None,\n status: enums::AttemptStatus::Pending,\n error_message: Some(Some(\"Integrity Check Failed!\".to_string())),\n error_code: Some(Some(\"IE\".to_string())),\n error_reason: Some(Some(format!(\n \"Integrity Check Failed! Value mismatched for fields {field_name}\"\n ))),\n amount_capturable: None,\n updated_by: storage_scheme.to_string(),\n unified_code: None,\n unified_message: None,\n connector_transaction_id,\n payment_method_data: None,\n authentication_type: auth_update,\n }),\n )\n }\n Ok(()) => {\n let attempt_status = payment_data.payment_attempt.status.to_owned();\n let connector_status = router_data.status.to_owned();\n let updated_attempt_status = match (\n connector_status,\n attempt_status,\n payment_data.frm_message.to_owned(),\n ) {\n (\n enums::AttemptStatus::Authorized,\n enums::AttemptStatus::Unresolved,\n Some(frm_message),\n ) => match frm_message.frm_status {\n enums::FraudCheckStatus::Fraud\n | enums::FraudCheckStatus::ManualReview => attempt_status,\n _ => router_data.get_attempt_status_for_db_update(&payment_data),\n },\n _ => router_data.get_attempt_status_for_db_update(&payment_data),\n };\n match payments_response {\n types::PaymentsResponseData::PreProcessingResponse {\n pre_processing_id,\n connector_metadata,\n connector_response_reference_id,\n ..\n } => {\n let connector_transaction_id = match pre_processing_id.to_owned() {\n types::PreprocessingResponseId::PreProcessingId(_) => None,\n\n types::PreprocessingResponseId::ConnectorTransactionId(\n connector_txn_id,\n ) => Some(connector_txn_id),\n };\n let preprocessing_step_id = match pre_processing_id {\n types::PreprocessingResponseId::PreProcessingId(\n pre_processing_id,\n ) => Some(pre_processing_id),\n types::PreprocessingResponseId::ConnectorTransactionId(_) => None,\n };\n let payment_attempt_update =\n storage::PaymentAttemptUpdate::PreprocessingUpdate {\n status: updated_attempt_status,\n payment_method_id: payment_data\n .payment_attempt\n .payment_method_id\n .clone(),\n connector_metadata,\n preprocessing_step_id,\n connector_transaction_id,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n };\n\n (None, Some(payment_attempt_update))\n }\n types::PaymentsResponseData::TransactionResponse {\n resource_id,\n redirection_data,\n connector_metadata,\n connector_response_reference_id,\n incremental_authorization_allowed,\n charge_id,\n ..\n } => {\n payment_data\n .payment_intent\n .incremental_authorization_allowed =\n core_utils::get_incremental_authorization_allowed_value(\n incremental_authorization_allowed,\n payment_data\n .payment_intent\n .request_incremental_authorization,\n );\n let connector_transaction_id = match resource_id {\n types::ResponseId::NoResponseId => None,\n types::ResponseId::ConnectorTransactionId(ref id)\n | types::ResponseId::EncodedData(ref id) => Some(id),\n };\n\n let encoded_data = payment_data.payment_attempt.encoded_data.clone();\n\n let authentication_data = (*redirection_data)\n .as_ref()\n .map(Encode::encode_to_value)\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Could not parse the connector response\")?;\n\n let auth_update = if Some(router_data.auth_type)\n != payment_data.payment_attempt.authentication_type\n {\n Some(router_data.auth_type)\n } else {\n None\n };\n\n // incase of success, update error code and error message\n let error_status =\n if router_data.status == enums::AttemptStatus::Charged {\n Some(None)\n } else {\n None\n };\n // update connector_mandate_details in case of Authorized/Charged Payment Status\n if matches!(\n router_data.status,\n enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized\n ) {\n payment_data\n .payment_intent\n .fingerprint_id\n .clone_from(&payment_data.payment_attempt.fingerprint_id);\n\n if let Some(payment_method) =\n payment_data.payment_method_info.clone()\n {\n // Parse value to check for mandates' existence\n let mandate_details =\n storage::PaymentMethod::get_common_mandate_reference(\n payment_method.connector_mandate_details.clone(),\n )\n .change_context(\n errors::ApiErrorResponse::InternalServerError,\n )\n .attach_printable(\n \"Failed to deserialize to Payment Mandate Reference \",\n )?;\n\n if let Some(mca_id) =\n payment_data.payment_attempt.merchant_connector_id.clone()\n {\n // check if the mandate has not already been set to active\n if !mandate_details.payments\n .as_ref()\n .and_then(|payments| payments.0.get(&mca_id))\n .map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active))\n .unwrap_or(false)\n {\n\n let (connector_mandate_id, mandate_metadata,connector_mandate_request_reference_id) = payment_data.payment_attempt.connector_mandate_detail.clone()\n .map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata,cmr.connector_mandate_request_reference_id))\n .unwrap_or((None, None,None));\n // Update the connector mandate details with the payment attempt connector mandate id\n let connector_mandate_details =\n tokenization::update_connector_mandate_details(\n Some(mandate_details),\n payment_data.payment_attempt.payment_method_type,\n Some(\n payment_data\n .payment_attempt\n .net_amount\n .get_total_amount()\n .get_amount_as_i64(),\n ),\n payment_data.payment_attempt.currency,\n payment_data.payment_attempt.merchant_connector_id.clone(),\n connector_mandate_id,\n mandate_metadata,\n connector_mandate_request_reference_id\n )?;\n // Update the payment method table with the active mandate record\n payment_methods::cards::update_payment_method_connector_mandate_details(\n state,\n key_store,\n &*state.store,\n payment_method,\n connector_mandate_details,\n storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to update payment method in db\")?;\n }\n }\n }\n\n metrics::SUCCESSFUL_PAYMENT.add(1, &[]);\n }\n\n let payment_method_id =\n payment_data.payment_attempt.payment_method_id.clone();\n\n utils::add_apple_pay_payment_status_metrics(\n router_data.status,\n router_data.apple_pay_flow.clone(),\n payment_data.payment_attempt.connector.clone(),\n payment_data.payment_attempt.merchant_id.clone(),\n );\n let (capture_updates, payment_attempt_update) = match payment_data\n .multiple_capture_data\n {\n Some(multiple_capture_data) => {\n let (connector_capture_id, connector_capture_data) =\n match resource_id {\n types::ResponseId::NoResponseId => (None, None),\n types::ResponseId::ConnectorTransactionId(id)\n | types::ResponseId::EncodedData(id) => {\n let (txn_id, txn_data) =\n ConnectorTransactionId::form_id_and_data(id);\n (Some(txn_id), txn_data)\n }\n };\n let capture_update = storage::CaptureUpdate::ResponseUpdate {\n status: enums::CaptureStatus::foreign_try_from(\n router_data.status,\n )?,\n connector_capture_id: connector_capture_id.clone(),\n connector_response_reference_id,\n connector_capture_data: connector_capture_data.clone(),\n };\n let capture_update_list = vec![(\n multiple_capture_data.get_latest_capture().clone(),\n capture_update,\n )];\n (Some((multiple_capture_data, capture_update_list)), auth_update.map(|auth_type| {\n storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {\n authentication_type: auth_type,\n updated_by: storage_scheme.to_string(),\n }\n }))\n }\n None => (\n None,\n Some(storage::PaymentAttemptUpdate::ResponseUpdate {\n status: updated_attempt_status,\n connector: None,\n connector_transaction_id: connector_transaction_id.cloned(),\n authentication_type: auth_update,\n amount_capturable: router_data\n .request\n .get_amount_capturable(\n &payment_data,\n updated_attempt_status,\n )\n .map(MinorUnit::new),\n payment_method_id,\n mandate_id: payment_data.payment_attempt.mandate_id.clone(),\n connector_metadata,\n payment_token: None,\n error_code: error_status.clone(),\n error_message: error_status.clone(),\n error_reason: error_status.clone(),\n unified_code: error_status.clone(),\n unified_message: error_status,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n authentication_data,\n encoded_data,\n payment_method_data: additional_payment_method_data,\n charge_id,\n connector_mandate_detail: payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone(),\n }),\n ),\n };\n\n (capture_updates, payment_attempt_update)\n }\n types::PaymentsResponseData::TransactionUnresolvedResponse {\n resource_id,\n reason,\n connector_response_reference_id,\n } => {\n let connector_transaction_id = match resource_id {\n types::ResponseId::NoResponseId => None,\n types::ResponseId::ConnectorTransactionId(id)\n | types::ResponseId::EncodedData(id) => Some(id),\n };\n (\n None,\n Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate {\n status: updated_attempt_status,\n connector: None,\n connector_transaction_id,\n payment_method_id: payment_data\n .payment_attempt\n .payment_method_id\n .clone(),\n error_code: Some(reason.clone().map(|cd| cd.code)),\n error_message: Some(reason.clone().map(|cd| cd.message)),\n error_reason: Some(reason.map(|cd| cd.message)),\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n }),\n )\n }\n types::PaymentsResponseData::SessionResponse { .. } => (None, None),\n types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),\n types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),\n types::PaymentsResponseData::ConnectorCustomerResponse { .. } => {\n (None, None)\n }\n types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {\n (None, None)\n }\n types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None),\n types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => (None, None),\n types::PaymentsResponseData::SessionUpdateResponse { .. } => (None, None),\n types::PaymentsResponseData::MultipleCaptureResponse {\n capture_sync_response_list,\n } => match payment_data.multiple_capture_data {\n Some(multiple_capture_data) => {\n let capture_update_list = response_to_capture_update(\n &multiple_capture_data,\n capture_sync_response_list,\n )?;\n (Some((multiple_capture_data, capture_update_list)), None)\n }\n None => (None, None),\n },\n }\n }\n }\n }\n };\n payment_data.multiple_capture_data = match capture_update {\n Some((mut multiple_capture_data, capture_updates)) => {\n for (capture, capture_update) in capture_updates {\n let updated_capture = state\n .store\n .update_capture_with_capture_id(capture, capture_update, storage_scheme)\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n multiple_capture_data.update_capture(updated_capture);\n }\n\n let authorized_amount = payment_data.payment_attempt.get_total_amount();\n\n payment_attempt_update = Some(storage::PaymentAttemptUpdate::AmountToCaptureUpdate {\n status: multiple_capture_data.get_attempt_status(authorized_amount),\n amount_capturable: authorized_amount\n - multiple_capture_data.get_total_blocked_amount(),\n updated_by: storage_scheme.to_string(),\n });\n Some(multiple_capture_data)\n }\n None => None,\n };\n\n // Stage 1\n\n let payment_attempt = payment_data.payment_attempt.clone();\n\n let m_db = state.clone().store;\n let m_payment_attempt_update = payment_attempt_update.clone();\n let m_payment_attempt = payment_attempt.clone();\n\n let payment_attempt = payment_attempt_update\n .map(|payment_attempt_update| {\n PaymentAttempt::from_storage_model(\n payment_attempt_update\n .to_storage_model()\n .apply_changeset(payment_attempt.clone().to_storage_model()),\n )\n })\n .unwrap_or_else(|| payment_attempt);\n\n let payment_attempt_fut = tokio::spawn(\n async move {\n Box::pin(async move {\n Ok::<_, error_stack::Report>(\n match m_payment_attempt_update {\n Some(payment_attempt_update) => m_db\n .update_payment_attempt_with_attempt_id(\n m_payment_attempt,\n payment_attempt_update,\n storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,\n None => m_payment_attempt,\n },\n )\n })\n .await\n }\n .in_current_span(),\n );\n\n payment_data.payment_attempt = payment_attempt;\n\n payment_data.authentication = match payment_data.authentication {\n Some(authentication) => {\n let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate {\n authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used,\n };\n let updated_authentication = state\n .store\n .update_authentication_by_merchant_id_authentication_id(\n authentication,\n authentication_update,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n Some(updated_authentication)\n }\n None => None,\n };\n\n let amount_captured = get_total_amount_captured(\n &router_data.request,\n router_data.amount_captured.map(MinorUnit::new),\n router_data.status,\n &payment_data,\n );\n\n let payment_intent_update = match &router_data.response {\n Err(_) => storage::PaymentIntentUpdate::PGStatusUpdate {\n status: api_models::enums::IntentStatus::foreign_from(\n payment_data.payment_attempt.status,\n ),\n updated_by: storage_scheme.to_string(),\n // make this false only if initial payment fails, if incremental authorization call fails don't make it false\n incremental_authorization_allowed: Some(false),\n },\n Ok(_) => storage::PaymentIntentUpdate::ResponseUpdate {\n status: api_models::enums::IntentStatus::foreign_from(\n payment_data.payment_attempt.status,\n ),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(),\n incremental_authorization_allowed: payment_data\n .payment_intent\n .incremental_authorization_allowed,\n },\n };\n\n let m_db = state.clone().store;\n let m_key_store = key_store.clone();\n let m_payment_data_payment_intent = payment_data.payment_intent.clone();\n let m_payment_intent_update = payment_intent_update.clone();\n let key_manager_state: KeyManagerState = state.into();\n let payment_intent_fut = tokio::spawn(\n async move {\n m_db.update_payment_intent(\n &key_manager_state,\n m_payment_data_payment_intent,\n m_payment_intent_update,\n &m_key_store,\n storage_scheme,\n )\n .map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))\n .await\n }\n .in_current_span(),\n );\n\n // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize\n let m_db = state.clone().store;\n let m_router_data_merchant_id = router_data.merchant_id.clone();\n let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();\n let m_payment_data_mandate_id =\n payment_data\n .payment_attempt\n .mandate_id\n .clone()\n .or(payment_data\n .mandate_id\n .clone()\n .and_then(|mandate_ids| mandate_ids.mandate_id));\n let m_router_data_response = router_data.response.clone();\n let mandate_update_fut = tokio::spawn(\n async move {\n mandate::update_connector_mandate_id(\n m_db.as_ref(),\n &m_router_data_merchant_id,\n m_payment_data_mandate_id,\n m_payment_method_id,\n m_router_data_response,\n storage_scheme,\n )\n .await\n }\n .in_current_span(),\n );\n\n let (payment_intent, _, payment_attempt) = futures::try_join!(\n utils::flatten_join_error(payment_intent_fut),\n utils::flatten_join_error(mandate_update_fut),\n utils::flatten_join_error(payment_attempt_fut)\n )?;\n\n #[cfg(all(feature = \"v1\", feature = \"dynamic_routing\"))]\n {\n if payment_intent.status.is_in_terminal_state()\n && business_profile.dynamic_routing_algorithm.is_some()\n {\n let state = state.clone();\n let business_profile = business_profile.clone();\n let payment_attempt = payment_attempt.clone();\n let success_based_routing_config_params_interpolator =\n routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(\n payment_attempt.payment_method,\n payment_attempt.payment_method_type,\n payment_attempt.authentication_type,\n payment_attempt.currency,\n payment_data\n .address\n .get_payment_billing()\n .and_then(|address| address.clone().address)\n .and_then(|address| address.country),\n payment_attempt\n .payment_method_data\n .as_ref()\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card\"))\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card_network\"))\n .and_then(|network| network.as_str())\n .map(|network| network.to_string()),\n payment_attempt\n .payment_method_data\n .as_ref()\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card\"))\n .and_then(|data| data.as_object())\n .and_then(|card| card.get(\"card_isin\"))\n .and_then(|card_isin| card_isin.as_str())\n .map(|card_isin| card_isin.to_string()),\n );\n tokio::spawn(\n async move {\n routing_helpers::push_metrics_with_update_window_for_success_based_routing(\n &state,\n &payment_attempt,\n routable_connectors,\n &business_profile,\n success_based_routing_config_params_interpolator,\n )\n .await\n .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))\n .ok();\n }\n .in_current_span(),\n );\n }\n }\n\n payment_data.payment_intent = payment_intent;\n payment_data.payment_attempt = payment_attempt;\n router_data.payment_method_status.and_then(|status| {\n payment_data\n .payment_method_info\n .as_mut()\n .map(|info| info.status = status)\n });\n\n match router_data.integrity_check {\n Ok(()) => Ok(payment_data),\n Err(err) => {\n metrics::INTEGRITY_CHECK_FAILED.add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n payment_data\n .payment_attempt\n .connector\n .clone()\n .unwrap_or_default(),\n ),\n (\n \"merchant_id\",\n payment_data.payment_attempt.merchant_id.clone(),\n )\n ),\n );\n Err(error_stack::Report::new(\n errors::ApiErrorResponse::IntegrityCheckFailed {\n connector_transaction_id: payment_data\n .payment_attempt\n .get_connector_payment_id()\n .map(ToString::to_string),\n reason: payment_data\n .payment_attempt\n .error_message\n .unwrap_or_default(),\n field_names: err.field_names,\n },\n ))\n }\n }\n}", + "diff_span": { + "before": " {\n // Parse value to check for mandates' existence\n let mandate_details = payment_method\n .connector_mandate_details\n .clone()\n .map(|val| {\n val.clone()\n .parse_value::(\"CommonMandateReference\")\n .or_else(|_| {\n val.parse_value::(\"PaymentsMandateReference\")\n .map(|payments| diesel_models::CommonMandateReference {\n payments: Some(payments),\n payouts: None,\n })\n })\n })\n .transpose()\n .change_context(\n errors::ApiErrorResponse::InternalServerError,\n )\n .attach_printable(\n \"Failed to deserialize to Payment Mandate Reference \",\n )?;\n\n if let Some(mca_id) =\n payment_data.payment_attempt.merchant_connector_id.clone()\n {\n // check if the mandate has not already been set to active\n if !mandate_details\n .as_ref()\n .map(|common_mandate_reference| {\n\n common_mandate_reference.payments\n .as_ref()\n .and_then(|payments| payments.0.get(&mca_id))\n .map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active))\n .unwrap_or(false)\n })\n .unwrap_or(false)\n {\n\n let (connector_mandate_id, mandate_metadata,connector_mandate_request_reference_id) = payment_data.payment_attempt.connector_mandate_detail.clone()\n .map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata,cmr.connector_mandate_request_reference_id))\n .unwrap_or((None, None,None));\n // Update the connector mandate details with the payment attempt connector mandate id\n let connector_mandate_details =\n tokenization::update_connector_mandate_details(\n mandate_details,\n payment_data.payment_attempt.payment_method_type,\n Some(", + "after": " {\n // Parse value to check for mandates' existence\n let mandate_details =\n storage::PaymentMethod::get_common_mandate_reference(\n payment_method.connector_mandate_details.clone(),\n )\n .change_context(\n errors::ApiErrorResponse::InternalServerError,\n )\n .attach_printable(\n \"Failed to deserialize to Payment Mandate Reference \",\n )?;\n\n if let Some(mca_id) =\n payment_data.payment_attempt.merchant_connector_id.clone()\n {\n // check if the mandate has not already been set to active\n if !mandate_details.payments\n .as_ref()\n .and_then(|payments| payments.0.get(&mca_id))\n .map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active))\n .unwrap_or(false)\n {\n\n let (connector_mandate_id, mandate_metadata,connector_mandate_request_reference_id) = payment_data.payment_attempt.connector_mandate_detail.clone()\n .map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata,cmr.connector_mandate_request_reference_id))\n .unwrap_or((None, None,None));\n // Update the connector mandate details with the payment attempt connector mandate id\n let connector_mandate_details =\n tokenization::update_connector_mandate_details(\n Some(mandate_details),\n payment_data.payment_attempt.payment_method_type,\n Some(" + }, + "commit_sha": "90fef342c821e7b10ceaa64c6fa2a286737b9a23" + } + ] +} \ No newline at end of file