diff --git "a/diffs/pr_10074/c028b95/diff.json" "b/diffs/pr_10074/c028b95/diff.json" new file mode 100644--- /dev/null +++ "b/diffs/pr_10074/c028b95/diff.json" @@ -0,0 +1,174 @@ +{ + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111", + "pr_number": 10074, + "rust_files": [ + "crates/common_enums/src/enums.rs", + "crates/diesel_models/src/payment_attempt.rs", + "crates/router/src/core/payments/operations/payment_confirm.rs", + "crates/router/src/core/payments/operations/payment_response.rs", + "crates/router/src/core/utils.rs" + ], + "diffs": [ + { + "id": "crates/router/src/core/utils.rs::function::get_incremental_authorization_allowed_value", + "file": "crates/router/src/core/utils.rs", + "kind": "function_item", + "status": "modified", + "code_changed": false, + "imports_changed": true, + "before_code": "pub fn get_incremental_authorization_allowed_value(\n incremental_authorization_allowed: Option,\n request_incremental_authorization: Option,\n) -> Option {\n if request_incremental_authorization == Some(RequestIncrementalAuthorization::False) {\n Some(false)\n } else {\n incremental_authorization_allowed\n }\n}", + "after_code": "pub fn get_incremental_authorization_allowed_value(\n incremental_authorization_allowed: Option,\n request_incremental_authorization: Option,\n) -> Option {\n if request_incremental_authorization == Some(RequestIncrementalAuthorization::False) {\n Some(false)\n } else {\n incremental_authorization_allowed\n }\n}", + "diff_span": { + "before": "", + "after": "" + }, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111", + "before_imports": [ + "use crate::{\n configs::Settings,\n consts,\n core::{\n errors::{self, RouterResult, StorageErrorExt},\n payments::PaymentData,\n },\n db::StorageInterface,\n routes::SessionState,\n types::{\n self, api, domain,\n storage::{self, enums},\n PollConfig,\n },\n utils::{generate_id, OptionExt, ValueExt},\n};", + "use hyperswitch_domain_models::{\n merchant_connector_account::MerchantConnectorAccount,\n payment_address::PaymentAddress,\n router_data::ErrorResponse,\n router_data_v2::flow_common_types::VaultConnectorFlowData,\n router_request_types,\n types::{OrderDetailsWithAmount, VaultRouterDataV2},\n};", + "use common_enums::{IntentStatus, RequestIncrementalAuthorization, Tokenization};" + ], + "after_imports": [ + "use crate::{\n configs::Settings,\n consts,\n core::{\n errors::{self, RouterResult, StorageErrorExt},\n payments::PaymentData,\n },\n db::StorageInterface,\n routes::SessionState,\n types::{\n self, api, domain,\n storage::{self, enums},\n PollConfig,\n },\n utils::{generate_id, OptionExt, ValueExt},\n};", + "use hyperswitch_domain_models::{\n merchant_connector_account::MerchantConnectorAccount,\n payment_address::PaymentAddress,\n router_data::ErrorResponse,\n router_data_v2::flow_common_types::VaultConnectorFlowData,\n router_request_types,\n types::{OrderDetailsWithAmount, VaultRouterDataV2},\n};", + "use common_enums::{IntentStatus, RequestIncrementalAuthorization};" + ] + }, + { + "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_data = payment_data.payment_attempt.get_payment_method_data();\n\n let additional_payment_method_data = match payment_data.payment_method_data.clone() {\n Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_))\n | Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) => {\n payment_data.payment_attempt.payment_method_data.clone()\n }\n _ => {\n additional_payment_data\n .map(|_| {\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 .transpose()?\n .flatten()\n }\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 payment_data.whole_connector_response = router_data.raw_connector_response.clone();\n\n // TODO: refactor of gsm_error_category with respective feature flag\n #[allow(unused_variables)]\n let (capture_update, mut payment_attempt_update, gsm_error_category) = match router_data\n .response\n .clone()\n {\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, gsm_error_category) =\n 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 None,\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 =\n option_gsm.clone().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 and ExtendAuthorization flow\n {\n if flow_name == \"PSync\" || flow_name == \"ExtendAuthorization\" {\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.clone())),\n error_code: Some(Some(err.code.clone())),\n error_reason: Some(err.reason.clone()),\n amount_capturable: router_data\n .request\n .get_amount_capturable(\n &payment_data,\n router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\n status,\n )\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.clone(),\n payment_method_data: additional_payment_method_data,\n authentication_type: auth_update,\n issuer_error_code: err.network_decline_code.clone(),\n issuer_error_message: err.network_error_message.clone(),\n network_details: Some(ForeignFrom::foreign_from(&err)),\n }),\n option_gsm.and_then(|option_gsm| option_gsm.error_category),\n )\n }\n };\n (capture_update, attempt_update, gsm_error_category)\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::IntegrityFailure,\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 issuer_error_code: None,\n issuer_error_message: None,\n network_details: None,\n }),\n None,\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(\n &payment_data,\n router_data.amount_captured,\n router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\n )?,\n },\n _ => router_data.get_attempt_status_for_db_update(\n &payment_data,\n router_data.amount_captured,\n router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\n )?,\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), None)\n }\n types::PaymentsResponseData::TransactionResponse {\n resource_id,\n redirection_data,\n connector_metadata,\n connector_response_reference_id,\n incremental_authorization_allowed,\n charges,\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 let resp_network_transaction_id = router_data.response.as_ref()\n .map_err(|err| {\n logger::error!(error = ?err, \"Failed to obtain the network_transaction_id from payment response\");\n })\n .ok()\n .and_then(|resp| resp.get_network_transaction_id());\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\n | enums::AttemptStatus::Authorized\n | enums::AttemptStatus::PartiallyAuthorized\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 .get_common_mandate_reference()\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 let debit_routing_savings =\n payment_data.payment_method_data.as_ref().and_then(|data| {\n payments_helpers::get_debit_routing_savings_amount(\n data,\n &payment_data.payment_attempt,\n )\n });\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 is_overcapture_enabled = router_data\n .connector_response\n .as_ref()\n .and_then(|connector_response| {\n connector_response.is_overcapture_enabled()\n }).or_else(|| {\n payment_data.payment_intent\n .enable_overcapture\n .as_ref()\n .map(|enable_overcapture| common_types::primitive_wrappers::OvercaptureEnabledBool::new(*enable_overcapture.deref()))\n });\n\n let (\n capture_before,\n extended_authorization_applied,\n extended_authorization_last_applied_at,\n ) = router_data\n .connector_response\n .as_ref()\n .and_then(|connector_response| {\n connector_response.get_extended_authorization_response_data()\n })\n .map(|extended_auth_resp| {\n (\n extended_auth_resp.capture_before,\n extended_auth_resp.extended_authentication_applied,\n extended_auth_resp.extended_authorization_last_applied_at,\n )\n })\n .unwrap_or((None, None, None));\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, processor_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 processor_capture_data: processor_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 router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\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 capture_before,\n extended_authorization_applied,\n extended_authorization_last_applied_at,\n connector_mandate_detail: payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone(),\n charges,\n setup_future_usage_applied: payment_data\n .payment_attempt\n .setup_future_usage_applied,\n debit_routing_savings,\n network_transaction_id: resp_network_transaction_id,\n is_overcapture_enabled,\n authorized_amount: router_data.authorized_amount,\n tokenization: core_utils::determine_tokenization_value(\n payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone()\n .as_ref(),\n payment_data\n .payment_attempt\n .setup_future_usage_applied\n .clone(),\n ),\n }),\n ),\n };\n\n (capture_updates, payment_attempt_update, None)\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 None,\n )\n }\n types::PaymentsResponseData::SessionResponse { .. } => (None, None, None),\n types::PaymentsResponseData::SessionTokenResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::TokenizationResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::ConnectorCustomerResponse(..) => {\n (None, None, None)\n }\n types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::PostProcessingResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => (None, None, None),\n types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => {\n (None, None, None)\n }\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 (\n Some((multiple_capture_data, capture_update_list)),\n None,\n None,\n )\n }\n None => (None, None, None),\n },\n types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => {\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\n .payment_attempt\n .authorized_amount\n .unwrap_or_else(|| 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(mut authentication_store) => {\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_store.authentication,\n authentication_update,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n authentication_store.authentication = updated_authentication;\n Some(authentication_store)\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 feature_metadata: payment_data\n .payment_intent\n .feature_metadata\n .clone()\n .map(masking::Secret::new),\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 feature_metadata: payment_data\n .payment_intent\n .feature_metadata\n .clone()\n .map(masking::Secret::new),\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 dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"DynamicRoutingAlgorithmRef not found in profile\")?;\n\n let state = state.clone();\n let profile_id = business_profile.get_id().to_owned();\n let payment_attempt = payment_attempt.clone();\n let dynamic_routing_config_params_interpolator =\n routing_helpers::DynamicRoutingConfigParamsInterpolator::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 let should_route_to_open_router =\n state.conf.open_router.dynamic_routing_enabled;\n let is_success_rate_based = matches!(\n payment_attempt.routing_approach,\n Some(enums::RoutingApproach::SuccessRateExploitation)\n | Some(enums::RoutingApproach::SuccessRateExploration)\n );\n\n if should_route_to_open_router && is_success_rate_based {\n routing_helpers::update_gateway_score_helper_with_open_router(\n &state,\n &payment_attempt,\n &profile_id,\n dynamic_routing_algo_ref.clone(),\n )\n .await\n .map_err(|e| logger::error!(open_router_update_gateway_score_err=?e))\n .ok();\n } else {\n routing_helpers::push_metrics_with_update_window_for_success_based_routing(\n &state,\n &payment_attempt,\n routable_connectors.clone(),\n &profile_id,\n dynamic_routing_algo_ref.clone(),\n dynamic_routing_config_params_interpolator.clone(),\n )\n .await\n .map_err(|e| logger::error!(success_based_routing_metrics_error=?e))\n .ok();\n\n if let Some(gsm_error_category) = gsm_error_category {\n if gsm_error_category.should_perform_elimination_routing() {\n logger::info!(\"Performing update window for elimination routing\");\n routing_helpers::update_window_for_elimination_routing(\n &state,\n &payment_attempt,\n &profile_id,\n dynamic_routing_algo_ref.clone(),\n dynamic_routing_config_params_interpolator.clone(),\n gsm_error_category,\n )\n .await\n .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))\n .ok();\n };\n };\n\n routing_helpers::push_metrics_with_update_window_for_contract_based_routing(\n &state,\n &payment_attempt,\n routable_connectors,\n &profile_id,\n dynamic_routing_algo_ref,\n dynamic_routing_config_params_interpolator,\n )\n .await\n .map_err(|e| logger::error!(contract_based_routing_metrics_error=?e))\n .ok();\n }\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 if payment_data.payment_attempt.status == enums::AttemptStatus::Failure {\n let _ = card_testing_guard_utils::increment_blocked_count_in_cache(\n state,\n payment_data.card_testing_guard_data.clone(),\n )\n .await;\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_data = payment_data.payment_attempt.get_payment_method_data();\n\n let additional_payment_method_data = match payment_data.payment_method_data.clone() {\n Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_))\n | Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) => {\n payment_data.payment_attempt.payment_method_data.clone()\n }\n _ => {\n additional_payment_data\n .map(|_| {\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 .transpose()?\n .flatten()\n }\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 payment_data.whole_connector_response = router_data.raw_connector_response.clone();\n\n // TODO: refactor of gsm_error_category with respective feature flag\n #[allow(unused_variables)]\n let (capture_update, mut payment_attempt_update, gsm_error_category) = match router_data\n .response\n .clone()\n {\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, gsm_error_category) =\n 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 None,\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 =\n option_gsm.clone().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 and ExtendAuthorization flow\n {\n if flow_name == \"PSync\" || flow_name == \"ExtendAuthorization\" {\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.clone())),\n error_code: Some(Some(err.code.clone())),\n error_reason: Some(err.reason.clone()),\n amount_capturable: router_data\n .request\n .get_amount_capturable(\n &payment_data,\n router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\n status,\n )\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.clone(),\n payment_method_data: additional_payment_method_data,\n authentication_type: auth_update,\n issuer_error_code: err.network_decline_code.clone(),\n issuer_error_message: err.network_error_message.clone(),\n network_details: Some(ForeignFrom::foreign_from(&err)),\n }),\n option_gsm.and_then(|option_gsm| option_gsm.error_category),\n )\n }\n };\n (capture_update, attempt_update, gsm_error_category)\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::IntegrityFailure,\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 issuer_error_code: None,\n issuer_error_message: None,\n network_details: None,\n }),\n None,\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(\n &payment_data,\n router_data.amount_captured,\n router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\n )?,\n },\n _ => router_data.get_attempt_status_for_db_update(\n &payment_data,\n router_data.amount_captured,\n router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\n )?,\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), None)\n }\n types::PaymentsResponseData::TransactionResponse {\n resource_id,\n redirection_data,\n connector_metadata,\n connector_response_reference_id,\n incremental_authorization_allowed,\n charges,\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 let resp_network_transaction_id = router_data.response.as_ref()\n .map_err(|err| {\n logger::error!(error = ?err, \"Failed to obtain the network_transaction_id from payment response\");\n })\n .ok()\n .and_then(|resp| resp.get_network_transaction_id());\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\n | enums::AttemptStatus::Authorized\n | enums::AttemptStatus::PartiallyAuthorized\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 .get_common_mandate_reference()\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 let debit_routing_savings =\n payment_data.payment_method_data.as_ref().and_then(|data| {\n payments_helpers::get_debit_routing_savings_amount(\n data,\n &payment_data.payment_attempt,\n )\n });\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 is_overcapture_enabled = router_data\n .connector_response\n .as_ref()\n .and_then(|connector_response| {\n connector_response.is_overcapture_enabled()\n }).or_else(|| {\n payment_data.payment_intent\n .enable_overcapture\n .as_ref()\n .map(|enable_overcapture| common_types::primitive_wrappers::OvercaptureEnabledBool::new(*enable_overcapture.deref()))\n });\n\n let (\n capture_before,\n extended_authorization_applied,\n extended_authorization_last_applied_at,\n ) = router_data\n .connector_response\n .as_ref()\n .and_then(|connector_response| {\n connector_response.get_extended_authorization_response_data()\n })\n .map(|extended_auth_resp| {\n (\n extended_auth_resp.capture_before,\n extended_auth_resp.extended_authentication_applied,\n extended_auth_resp.extended_authorization_last_applied_at,\n )\n })\n .unwrap_or((None, None, None));\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, processor_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 processor_capture_data: processor_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 router_data\n .minor_amount_capturable\n .map(MinorUnit::get_amount_as_i64),\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 capture_before,\n extended_authorization_applied,\n extended_authorization_last_applied_at,\n connector_mandate_detail: payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone(),\n charges,\n setup_future_usage_applied: payment_data\n .payment_attempt\n .setup_future_usage_applied,\n debit_routing_savings,\n network_transaction_id: resp_network_transaction_id,\n is_overcapture_enabled,\n authorized_amount: router_data.authorized_amount,\n tokenization: payment_data\n .payment_attempt\n .connector_mandate_detail\n .as_ref()\n .and_then(|detail| {\n detail.get_tokenization_strategy(\n payment_data\n .payment_attempt\n .setup_future_usage_applied,\n )\n }),\n }),\n ),\n };\n\n (capture_updates, payment_attempt_update, None)\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 None,\n )\n }\n types::PaymentsResponseData::SessionResponse { .. } => (None, None, None),\n types::PaymentsResponseData::SessionTokenResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::TokenizationResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::ConnectorCustomerResponse(..) => {\n (None, None, None)\n }\n types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::PostProcessingResponse { .. } => {\n (None, None, None)\n }\n types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => (None, None, None),\n types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => {\n (None, None, None)\n }\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 (\n Some((multiple_capture_data, capture_update_list)),\n None,\n None,\n )\n }\n None => (None, None, None),\n },\n types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => {\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\n .payment_attempt\n .authorized_amount\n .unwrap_or_else(|| 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(mut authentication_store) => {\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_store.authentication,\n authentication_update,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n authentication_store.authentication = updated_authentication;\n Some(authentication_store)\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 feature_metadata: payment_data\n .payment_intent\n .feature_metadata\n .clone()\n .map(masking::Secret::new),\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 feature_metadata: payment_data\n .payment_intent\n .feature_metadata\n .clone()\n .map(masking::Secret::new),\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 dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"DynamicRoutingAlgorithmRef not found in profile\")?;\n\n let state = state.clone();\n let profile_id = business_profile.get_id().to_owned();\n let payment_attempt = payment_attempt.clone();\n let dynamic_routing_config_params_interpolator =\n routing_helpers::DynamicRoutingConfigParamsInterpolator::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 let should_route_to_open_router =\n state.conf.open_router.dynamic_routing_enabled;\n let is_success_rate_based = matches!(\n payment_attempt.routing_approach,\n Some(enums::RoutingApproach::SuccessRateExploitation)\n | Some(enums::RoutingApproach::SuccessRateExploration)\n );\n\n if should_route_to_open_router && is_success_rate_based {\n routing_helpers::update_gateway_score_helper_with_open_router(\n &state,\n &payment_attempt,\n &profile_id,\n dynamic_routing_algo_ref.clone(),\n )\n .await\n .map_err(|e| logger::error!(open_router_update_gateway_score_err=?e))\n .ok();\n } else {\n routing_helpers::push_metrics_with_update_window_for_success_based_routing(\n &state,\n &payment_attempt,\n routable_connectors.clone(),\n &profile_id,\n dynamic_routing_algo_ref.clone(),\n dynamic_routing_config_params_interpolator.clone(),\n )\n .await\n .map_err(|e| logger::error!(success_based_routing_metrics_error=?e))\n .ok();\n\n if let Some(gsm_error_category) = gsm_error_category {\n if gsm_error_category.should_perform_elimination_routing() {\n logger::info!(\"Performing update window for elimination routing\");\n routing_helpers::update_window_for_elimination_routing(\n &state,\n &payment_attempt,\n &profile_id,\n dynamic_routing_algo_ref.clone(),\n dynamic_routing_config_params_interpolator.clone(),\n gsm_error_category,\n )\n .await\n .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))\n .ok();\n };\n };\n\n routing_helpers::push_metrics_with_update_window_for_contract_based_routing(\n &state,\n &payment_attempt,\n routable_connectors,\n &profile_id,\n dynamic_routing_algo_ref,\n dynamic_routing_config_params_interpolator,\n )\n .await\n .map_err(|e| logger::error!(contract_based_routing_metrics_error=?e))\n .ok();\n }\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 if payment_data.payment_attempt.status == enums::AttemptStatus::Failure {\n let _ = card_testing_guard_utils::increment_blocked_count_in_cache(\n state,\n payment_data.card_testing_guard_data.clone(),\n )\n .await;\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": " is_overcapture_enabled,\n authorized_amount: router_data.authorized_amount,\n tokenization: core_utils::determine_tokenization_value(\n payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone()\n .as_ref(),\n payment_data\n .payment_attempt\n .setup_future_usage_applied\n .clone(),\n ),\n }),\n ),", + "after": " is_overcapture_enabled,\n authorized_amount: router_data.authorized_amount,\n tokenization: payment_data\n .payment_attempt\n .connector_mandate_detail\n .as_ref()\n .and_then(|detail| {\n detail.get_tokenization_strategy(\n payment_data\n .payment_attempt\n .setup_future_usage_applied,\n )\n }),\n }),\n )," + }, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111" + }, + { + "id": "crates/diesel_models/src/payment_attempt.rs::impl::ConnectorMandateReferenceId", + "file": "crates/diesel_models/src/payment_attempt.rs", + "kind": "impl_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "impl ConnectorMandateReferenceId {\n pub fn get_connector_mandate_request_reference_id(&self) -> Option {\n self.connector_mandate_request_reference_id.clone()\n }\n}", + "after_code": "impl ConnectorMandateReferenceId {\n pub fn get_connector_mandate_request_reference_id(&self) -> Option {\n self.connector_mandate_request_reference_id.clone()\n }\n\n pub fn get_tokenization_strategy(\n &self,\n setup_future_usage: Option,\n ) -> Option {\n match setup_future_usage {\n Some(common_enums::FutureUsage::OnSession) | None => None,\n Some(common_enums::FutureUsage::OffSession) => {\n if self.connector_mandate_id.is_some() {\n Some(common_enums::Tokenization::TokenizeAtPsp)\n } else {\n Some(common_enums::Tokenization::SkipPsp)\n }\n }\n }\n }\n}", + "diff_span": { + "before": "", + "after": " self.connector_mandate_request_reference_id.clone()\n }\n\n pub fn get_tokenization_strategy(\n &self,\n setup_future_usage: Option,\n ) -> Option {\n match setup_future_usage {\n Some(common_enums::FutureUsage::OnSession) | None => None,\n Some(common_enums::FutureUsage::OffSession) => {\n if self.connector_mandate_id.is_some() {\n Some(common_enums::Tokenization::TokenizeAtPsp)\n } else {\n Some(common_enums::Tokenization::SkipPsp)\n }\n }\n }\n }\n}" + }, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111" + }, + { + "id": "crates/router/src/core/utils.rs::function::get_request_incremental_authorization_value", + "file": "crates/router/src/core/utils.rs", + "kind": "function_item", + "status": "modified", + "code_changed": false, + "imports_changed": true, + "before_code": "pub fn get_request_incremental_authorization_value(\n request_incremental_authorization: Option,\n capture_method: Option,\n) -> RouterResult> {\n Some(request_incremental_authorization\n .map(|request_incremental_authorization| {\n if request_incremental_authorization {\n if matches!(\n capture_method,\n Some(common_enums::CaptureMethod::Automatic) | Some(common_enums::CaptureMethod::SequentialAutomatic)\n ) {\n Err(errors::ApiErrorResponse::NotSupported { message: \"incremental authorization is not supported when capture_method is automatic\".to_owned() })?\n }\n Ok(RequestIncrementalAuthorization::True)\n } else {\n Ok(RequestIncrementalAuthorization::False)\n }\n })\n .unwrap_or(Ok(RequestIncrementalAuthorization::default()))).transpose()\n}", + "after_code": "pub fn get_request_incremental_authorization_value(\n request_incremental_authorization: Option,\n capture_method: Option,\n) -> RouterResult> {\n Some(request_incremental_authorization\n .map(|request_incremental_authorization| {\n if request_incremental_authorization {\n if matches!(\n capture_method,\n Some(common_enums::CaptureMethod::Automatic) | Some(common_enums::CaptureMethod::SequentialAutomatic)\n ) {\n Err(errors::ApiErrorResponse::NotSupported { message: \"incremental authorization is not supported when capture_method is automatic\".to_owned() })?\n }\n Ok(RequestIncrementalAuthorization::True)\n } else {\n Ok(RequestIncrementalAuthorization::False)\n }\n })\n .unwrap_or(Ok(RequestIncrementalAuthorization::default()))).transpose()\n}", + "diff_span": { + "before": "", + "after": "" + }, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111", + "before_imports": [ + "use crate::{\n configs::Settings,\n consts,\n core::{\n errors::{self, RouterResult, StorageErrorExt},\n payments::PaymentData,\n },\n db::StorageInterface,\n routes::SessionState,\n types::{\n self, api, domain,\n storage::{self, enums},\n PollConfig,\n },\n utils::{generate_id, OptionExt, ValueExt},\n};", + "use hyperswitch_domain_models::{\n merchant_connector_account::MerchantConnectorAccount,\n payment_address::PaymentAddress,\n router_data::ErrorResponse,\n router_data_v2::flow_common_types::VaultConnectorFlowData,\n router_request_types,\n types::{OrderDetailsWithAmount, VaultRouterDataV2},\n};", + "use common_enums::{IntentStatus, RequestIncrementalAuthorization, Tokenization};" + ], + "after_imports": [ + "use crate::{\n configs::Settings,\n consts,\n core::{\n errors::{self, RouterResult, StorageErrorExt},\n payments::PaymentData,\n },\n db::StorageInterface,\n routes::SessionState,\n types::{\n self, api, domain,\n storage::{self, enums},\n PollConfig,\n },\n utils::{generate_id, OptionExt, ValueExt},\n};", + "use hyperswitch_domain_models::{\n merchant_connector_account::MerchantConnectorAccount,\n payment_address::PaymentAddress,\n router_data::ErrorResponse,\n router_data_v2::flow_common_types::VaultConnectorFlowData,\n router_request_types,\n types::{OrderDetailsWithAmount, VaultRouterDataV2},\n};", + "use common_enums::{IntentStatus, RequestIncrementalAuthorization};" + ] + }, + { + "id": "crates/router/src/core/utils.rs::function::get_html_redirect_response_for_external_authentication", + "file": "crates/router/src/core/utils.rs", + "kind": "function_item", + "status": "modified", + "code_changed": false, + "imports_changed": true, + "before_code": "pub fn get_html_redirect_response_for_external_authentication(\n return_url_with_query_params: String,\n payment_response: &api_models::payments::PaymentsResponse,\n payment_id: common_utils::id_type::PaymentId,\n poll_config: &PollConfig,\n) -> RouterResult {\n // if intent_status is requires_customer_action then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url\n let html = match payment_response.status {\n IntentStatus::RequiresCustomerAction => {\n // Request poll id sent to client for retrieve_poll_status api\n let req_poll_id = get_external_authentication_request_poll_id(&payment_id);\n let poll_frequency = poll_config.frequency;\n let poll_delay_in_secs = poll_config.delay_in_secs;\n html! {\n head {\n title { \"Redirect Form\" }\n (PreEscaped(format!(r#\"\n \n \"#)))\n }\n }\n .into_string()\n },\n _ => {\n html! {\n head {\n title { \"Redirect Form\" }\n (PreEscaped(format!(r#\"\n \n \"#)))\n }\n }\n .into_string()\n },\n };\n Ok(html)\n}", + "after_code": "pub fn get_html_redirect_response_for_external_authentication(\n return_url_with_query_params: String,\n payment_response: &api_models::payments::PaymentsResponse,\n payment_id: common_utils::id_type::PaymentId,\n poll_config: &PollConfig,\n) -> RouterResult {\n // if intent_status is requires_customer_action then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url\n let html = match payment_response.status {\n IntentStatus::RequiresCustomerAction => {\n // Request poll id sent to client for retrieve_poll_status api\n let req_poll_id = get_external_authentication_request_poll_id(&payment_id);\n let poll_frequency = poll_config.frequency;\n let poll_delay_in_secs = poll_config.delay_in_secs;\n html! {\n head {\n title { \"Redirect Form\" }\n (PreEscaped(format!(r#\"\n \n \"#)))\n }\n }\n .into_string()\n },\n _ => {\n html! {\n head {\n title { \"Redirect Form\" }\n (PreEscaped(format!(r#\"\n \n \"#)))\n }\n }\n .into_string()\n },\n };\n Ok(html)\n}", + "diff_span": { + "before": "", + "after": "" + }, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111", + "before_imports": [ + "use super::*;", + "use common_enums::{IntentStatus, RequestIncrementalAuthorization, Tokenization};", + "use maud::{html, PreEscaped};", + "use hyperswitch_domain_models::{\n merchant_connector_account::MerchantConnectorAccount,\n payment_address::PaymentAddress,\n router_data::ErrorResponse,\n router_data_v2::flow_common_types::VaultConnectorFlowData,\n router_request_types,\n types::{OrderDetailsWithAmount, VaultRouterDataV2},\n};", + "use crate::{\n configs::Settings,\n consts,\n core::{\n errors::{self, RouterResult, StorageErrorExt},\n payments::PaymentData,\n },\n db::StorageInterface,\n routes::SessionState,\n types::{\n self, api, domain,\n storage::{self, enums},\n PollConfig,\n },\n utils::{generate_id, OptionExt, ValueExt},\n};", + "use crate::core::payments;" + ], + "after_imports": [ + "use super::*;", + "use common_enums::{IntentStatus, RequestIncrementalAuthorization};", + "use maud::{html, PreEscaped};", + "use hyperswitch_domain_models::{\n merchant_connector_account::MerchantConnectorAccount,\n payment_address::PaymentAddress,\n router_data::ErrorResponse,\n router_data_v2::flow_common_types::VaultConnectorFlowData,\n router_request_types,\n types::{OrderDetailsWithAmount, VaultRouterDataV2},\n};", + "use crate::{\n configs::Settings,\n consts,\n core::{\n errors::{self, RouterResult, StorageErrorExt},\n payments::PaymentData,\n },\n db::StorageInterface,\n routes::SessionState,\n types::{\n self, api, domain,\n storage::{self, enums},\n PollConfig,\n },\n utils::{generate_id, OptionExt, ValueExt},\n};", + "use crate::core::payments;" + ] + }, + { + "id": "crates/router/src/core/payments/operations/payment_confirm.rs::PaymentConfirm::function::update_trackers", + "file": "crates/router/src/core/payments/operations/payment_confirm.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "async fn update_trackers<'b>(\n &'b self,\n state: &'b SessionState,\n req_state: ReqState,\n mut payment_data: PaymentData,\n customer: Option,\n storage_scheme: storage_enums::MerchantStorageScheme,\n updated_customer: Option,\n key_store: &domain::MerchantKeyStore,\n frm_suggestion: Option,\n header_payload: hyperswitch_domain_models::payments::HeaderPayload,\n ) -> RouterResult<(\n BoxedOperation<'b, F, api::PaymentsRequest, PaymentData>,\n PaymentData,\n )>\n where\n F: 'b + Send,\n {\n let payment_method = payment_data.payment_attempt.payment_method;\n let browser_info = payment_data.payment_attempt.browser_info.clone();\n let frm_message = payment_data.frm_message.clone();\n let capture_method = payment_data.payment_attempt.capture_method;\n\n let default_status_result = (\n storage_enums::IntentStatus::Processing,\n storage_enums::AttemptStatus::Pending,\n (None, None),\n );\n let status_handler_for_frm_results = |frm_suggestion: FrmSuggestion| match frm_suggestion {\n FrmSuggestion::FrmCancelTransaction => (\n storage_enums::IntentStatus::Failed,\n storage_enums::AttemptStatus::Failure,\n frm_message.map_or((None, None), |fraud_check| {\n (\n Some(Some(fraud_check.frm_status.to_string())),\n Some(fraud_check.frm_reason.map(|reason| reason.to_string())),\n )\n }),\n ),\n FrmSuggestion::FrmManualReview => (\n storage_enums::IntentStatus::RequiresMerchantAction,\n storage_enums::AttemptStatus::Unresolved,\n (None, None),\n ),\n FrmSuggestion::FrmAuthorizeTransaction => (\n storage_enums::IntentStatus::RequiresCapture,\n storage_enums::AttemptStatus::Authorized,\n (None, None),\n ),\n };\n\n let status_handler_for_authentication_results =\n |authentication: &storage::Authentication| {\n if authentication.authentication_status.is_failed() {\n (\n storage_enums::IntentStatus::Failed,\n storage_enums::AttemptStatus::Failure,\n (\n Some(Some(\"EXTERNAL_AUTHENTICATION_FAILURE\".to_string())),\n Some(Some(\"external authentication failure\".to_string())),\n ),\n )\n } else if authentication.is_separate_authn_required() {\n (\n storage_enums::IntentStatus::RequiresCustomerAction,\n storage_enums::AttemptStatus::AuthenticationPending,\n (None, None),\n )\n } else {\n default_status_result.clone()\n }\n };\n\n let (intent_status, attempt_status, (error_code, error_message)) =\n match (frm_suggestion, payment_data.authentication.as_ref()) {\n (Some(frm_suggestion), _) => status_handler_for_frm_results(frm_suggestion),\n (_, Some(authentication_details)) => status_handler_for_authentication_results(\n &authentication_details.authentication,\n ),\n _ => default_status_result,\n };\n\n let connector = payment_data.payment_attempt.connector.clone();\n let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();\n let connector_request_reference_id = payment_data\n .payment_attempt\n .connector_request_reference_id\n .clone();\n\n let straight_through_algorithm = payment_data\n .payment_attempt\n .straight_through_algorithm\n .clone();\n let payment_token = payment_data.token.clone();\n let payment_method_type = payment_data.payment_attempt.payment_method_type;\n let profile_id = payment_data\n .payment_intent\n .profile_id\n .as_ref()\n .get_required_value(\"profile_id\")\n .change_context(errors::ApiErrorResponse::InternalServerError)?;\n\n let payment_experience = payment_data.payment_attempt.payment_experience;\n let additional_pm_data = payment_data\n .payment_method_data\n .as_ref()\n .async_map(|payment_method_data| async {\n helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)\n .await\n })\n .await\n .transpose()?\n .flatten();\n\n let encoded_additional_pm_data = additional_pm_data\n .as_ref()\n .map(Encode::encode_to_value)\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to encode additional pm data\")?;\n\n let customer_details = payment_data.payment_intent.customer_details.clone();\n let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();\n let authentication_type = payment_data.payment_attempt.authentication_type;\n\n let (shipping_address_id, billing_address_id, payment_method_billing_address_id) = (\n payment_data.payment_intent.shipping_address_id.clone(),\n payment_data.payment_intent.billing_address_id.clone(),\n payment_data\n .payment_attempt\n .payment_method_billing_address_id\n .clone(),\n );\n\n let customer_id = customer.clone().map(|c| c.customer_id);\n let return_url = payment_data.payment_intent.return_url.take();\n let setup_future_usage = payment_data.payment_intent.setup_future_usage;\n let business_label = payment_data.payment_intent.business_label.clone();\n let business_country = payment_data.payment_intent.business_country;\n let description = payment_data.payment_intent.description.take();\n let statement_descriptor_name =\n payment_data.payment_intent.statement_descriptor_name.take();\n let statement_descriptor_suffix = payment_data\n .payment_intent\n .statement_descriptor_suffix\n .take();\n let order_details = payment_data.payment_intent.order_details.clone();\n let metadata = payment_data.payment_intent.metadata.clone();\n let frm_metadata = payment_data.payment_intent.frm_metadata.clone();\n\n let client_source = header_payload\n .client_source\n .clone()\n .or(payment_data.payment_attempt.client_source.clone());\n let client_version = header_payload\n .client_version\n .clone()\n .or(payment_data.payment_attempt.client_version.clone());\n\n let m_payment_data_payment_attempt = payment_data.payment_attempt.clone();\n let m_payment_method_id =\n payment_data\n .payment_attempt\n .payment_method_id\n .clone()\n .or(payment_data\n .payment_method_info\n .as_ref()\n .map(|payment_method| payment_method.payment_method_id.clone()));\n let m_browser_info = browser_info.clone();\n let m_connector = connector.clone();\n let m_capture_method = capture_method;\n let m_payment_token = payment_token.clone();\n let m_additional_pm_data = encoded_additional_pm_data\n .clone()\n .or(payment_data.payment_attempt.payment_method_data.clone());\n let m_business_sub_label = business_sub_label.clone();\n let m_straight_through_algorithm = straight_through_algorithm.clone();\n let m_error_code = error_code.clone();\n let m_error_message = error_message.clone();\n let m_fingerprint_id = payment_data.payment_attempt.fingerprint_id.clone();\n let m_db = state.clone().store;\n let surcharge_amount = payment_data\n .surcharge_details\n .as_ref()\n .map(|surcharge_details| surcharge_details.surcharge_amount);\n let tax_amount = payment_data\n .surcharge_details\n .as_ref()\n .map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);\n\n let (\n external_three_ds_authentication_attempted,\n authentication_connector,\n authentication_id,\n ) = match payment_data.authentication.as_ref() {\n Some(authentication_store) => (\n Some(\n authentication_store\n .authentication\n .is_separate_authn_required(),\n ),\n authentication_store\n .authentication\n .authentication_connector\n .clone(),\n Some(\n authentication_store\n .authentication\n .authentication_id\n .clone(),\n ),\n ),\n None => (None, None, None),\n };\n\n let card_discovery = payment_data.get_card_discovery_for_card_payment_method();\n let is_stored_credential = helpers::is_stored_credential(\n &payment_data.recurring_details,\n &payment_data.pm_token,\n payment_data.mandate_id.is_some(),\n payment_data.payment_attempt.is_stored_credential,\n );\n let payment_attempt_fut =\n tokio::spawn(\n async move {\n m_db.update_payment_attempt_with_attempt_id(\n m_payment_data_payment_attempt,\n storage::PaymentAttemptUpdate::ConfirmUpdate {\n currency: payment_data.currency,\n status: attempt_status,\n payment_method,\n authentication_type,\n capture_method: m_capture_method,\n browser_info: m_browser_info,\n connector: m_connector,\n payment_token: m_payment_token,\n payment_method_data: m_additional_pm_data,\n payment_method_type,\n payment_experience,\n business_sub_label: m_business_sub_label,\n straight_through_algorithm: m_straight_through_algorithm,\n error_code: m_error_code,\n error_message: m_error_message,\n updated_by: storage_scheme.to_string(),\n merchant_connector_id,\n external_three_ds_authentication_attempted,\n authentication_connector,\n authentication_id,\n payment_method_billing_address_id,\n fingerprint_id: m_fingerprint_id,\n payment_method_id: m_payment_method_id,\n client_source,\n client_version,\n customer_acceptance: payment_data.payment_attempt.customer_acceptance,\n net_amount:\n hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(\n payment_data.payment_attempt.net_amount.get_order_amount(),\n payment_data.payment_intent.shipping_cost,\n payment_data\n .payment_attempt\n .net_amount\n .get_order_tax_amount(),\n surcharge_amount,\n tax_amount,\n ),\n\n connector_mandate_detail: payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone(),\n card_discovery,\n routing_approach: payment_data.payment_attempt.routing_approach,\n connector_request_reference_id,\n network_transaction_id: payment_data\n .payment_attempt\n .network_transaction_id\n .clone(),\n is_stored_credential,\n request_extended_authorization: payment_data\n .payment_attempt\n .request_extended_authorization,\n tokenization: core_utils::determine_tokenization_value(\n payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone()\n .as_ref(),\n payment_data\n .payment_attempt.setup_future_usage_applied.clone()\n ),\n },\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 let billing_address = payment_data.address.get_payment_billing();\n let key_manager_state = state.into();\n let billing_details = billing_address\n .async_map(|billing_details| {\n create_encrypted_data(&key_manager_state, key_store, billing_details)\n })\n .await\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to encrypt billing details\")?;\n\n let shipping_address = payment_data.address.get_shipping();\n let shipping_details = shipping_address\n .async_map(|shipping_details| {\n create_encrypted_data(&key_manager_state, key_store, shipping_details)\n })\n .await\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to encrypt shipping details\")?;\n\n let m_payment_data_payment_intent = payment_data.payment_intent.clone();\n let m_customer_id = customer_id.clone();\n let m_shipping_address_id = shipping_address_id.clone();\n let m_billing_address_id = billing_address_id.clone();\n let m_return_url = return_url.clone();\n let m_business_label = business_label.clone();\n let m_description = description.clone();\n let m_statement_descriptor_name = statement_descriptor_name.clone();\n let m_statement_descriptor_suffix = statement_descriptor_suffix.clone();\n let m_order_details = order_details.clone();\n let m_metadata = metadata.clone();\n let m_frm_metadata = frm_metadata.clone();\n let m_db = state.clone().store;\n let m_storage_scheme = storage_scheme.to_string();\n let session_expiry = m_payment_data_payment_intent.session_expiry;\n let m_key_store = key_store.clone();\n let key_manager_state = state.into();\n let is_payment_processor_token_flow =\n payment_data.payment_intent.is_payment_processor_token_flow;\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 storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {\n amount: payment_data.payment_intent.amount,\n currency: payment_data.currency,\n setup_future_usage,\n status: intent_status,\n customer_id: m_customer_id,\n shipping_address_id: m_shipping_address_id,\n billing_address_id: m_billing_address_id,\n return_url: m_return_url,\n business_country,\n business_label: m_business_label,\n description: m_description,\n statement_descriptor_name: m_statement_descriptor_name,\n statement_descriptor_suffix: m_statement_descriptor_suffix,\n order_details: m_order_details,\n metadata: m_metadata,\n payment_confirm_source: header_payload.payment_confirm_source,\n updated_by: m_storage_scheme,\n fingerprint_id: None,\n session_expiry,\n request_external_three_ds_authentication: None,\n frm_metadata: m_frm_metadata,\n customer_details,\n merchant_order_reference_id: None,\n billing_details,\n shipping_details,\n is_payment_processor_token_flow,\n tax_details: None,\n force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,\n is_iframe_redirection_enabled: payment_data\n .payment_intent\n .is_iframe_redirection_enabled,\n is_confirm_operation: true, // Indicates that this is a confirm operation\n payment_channel: payment_data.payment_intent.payment_channel,\n feature_metadata: payment_data\n .payment_intent\n .feature_metadata\n .clone()\n .map(masking::Secret::new),\n tax_status: payment_data.payment_intent.tax_status,\n discount_amount: payment_data.payment_intent.discount_amount,\n order_date: payment_data.payment_intent.order_date,\n shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,\n duty_amount: payment_data.payment_intent.duty_amount,\n enable_partial_authorization: payment_data\n .payment_intent\n .enable_partial_authorization,\n enable_overcapture: payment_data.payment_intent.enable_overcapture,\n })),\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 let customer_fut =\n if let Some((updated_customer, customer)) = updated_customer.zip(customer) {\n let m_customer_merchant_id = customer.merchant_id.to_owned();\n let m_key_store = key_store.clone();\n let m_updated_customer = updated_customer.clone();\n let session_state = state.clone();\n let m_db = session_state.store.clone();\n let key_manager_state = state.into();\n tokio::spawn(\n async move {\n let m_customer_customer_id = customer.customer_id.to_owned();\n m_db.update_customer_by_customer_id_merchant_id(\n &key_manager_state,\n m_customer_customer_id,\n m_customer_merchant_id,\n customer,\n m_updated_customer,\n &m_key_store,\n storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to update CustomerConnector in customer\")?;\n\n Ok::<_, error_stack::Report>(())\n }\n .in_current_span(),\n )\n } else {\n tokio::spawn(\n async move { Ok::<_, error_stack::Report>(()) }\n .in_current_span(),\n )\n };\n\n let (payment_intent, payment_attempt, _) = tokio::try_join!(\n utils::flatten_join_error(payment_intent_fut),\n utils::flatten_join_error(payment_attempt_fut),\n utils::flatten_join_error(customer_fut)\n )?;\n\n payment_data.payment_intent = payment_intent;\n payment_data.payment_attempt = payment_attempt;\n\n let client_src = payment_data.payment_attempt.client_source.clone();\n let client_ver = payment_data.payment_attempt.client_version.clone();\n\n let frm_message = payment_data.frm_message.clone();\n req_state\n .event_context\n .event(AuditEvent::new(AuditEventType::PaymentConfirm {\n client_src,\n client_ver,\n frm_message: Box::new(frm_message),\n }))\n .with(payment_data.to_event())\n .emit();\n Ok((Box::new(self), payment_data))\n }", + "after_code": "async fn update_trackers<'b>(\n &'b self,\n state: &'b SessionState,\n req_state: ReqState,\n mut payment_data: PaymentData,\n customer: Option,\n storage_scheme: storage_enums::MerchantStorageScheme,\n updated_customer: Option,\n key_store: &domain::MerchantKeyStore,\n frm_suggestion: Option,\n header_payload: hyperswitch_domain_models::payments::HeaderPayload,\n ) -> RouterResult<(\n BoxedOperation<'b, F, api::PaymentsRequest, PaymentData>,\n PaymentData,\n )>\n where\n F: 'b + Send,\n {\n let payment_method = payment_data.payment_attempt.payment_method;\n let browser_info = payment_data.payment_attempt.browser_info.clone();\n let frm_message = payment_data.frm_message.clone();\n let capture_method = payment_data.payment_attempt.capture_method;\n\n let default_status_result = (\n storage_enums::IntentStatus::Processing,\n storage_enums::AttemptStatus::Pending,\n (None, None),\n );\n let status_handler_for_frm_results = |frm_suggestion: FrmSuggestion| match frm_suggestion {\n FrmSuggestion::FrmCancelTransaction => (\n storage_enums::IntentStatus::Failed,\n storage_enums::AttemptStatus::Failure,\n frm_message.map_or((None, None), |fraud_check| {\n (\n Some(Some(fraud_check.frm_status.to_string())),\n Some(fraud_check.frm_reason.map(|reason| reason.to_string())),\n )\n }),\n ),\n FrmSuggestion::FrmManualReview => (\n storage_enums::IntentStatus::RequiresMerchantAction,\n storage_enums::AttemptStatus::Unresolved,\n (None, None),\n ),\n FrmSuggestion::FrmAuthorizeTransaction => (\n storage_enums::IntentStatus::RequiresCapture,\n storage_enums::AttemptStatus::Authorized,\n (None, None),\n ),\n };\n\n let status_handler_for_authentication_results =\n |authentication: &storage::Authentication| {\n if authentication.authentication_status.is_failed() {\n (\n storage_enums::IntentStatus::Failed,\n storage_enums::AttemptStatus::Failure,\n (\n Some(Some(\"EXTERNAL_AUTHENTICATION_FAILURE\".to_string())),\n Some(Some(\"external authentication failure\".to_string())),\n ),\n )\n } else if authentication.is_separate_authn_required() {\n (\n storage_enums::IntentStatus::RequiresCustomerAction,\n storage_enums::AttemptStatus::AuthenticationPending,\n (None, None),\n )\n } else {\n default_status_result.clone()\n }\n };\n\n let (intent_status, attempt_status, (error_code, error_message)) =\n match (frm_suggestion, payment_data.authentication.as_ref()) {\n (Some(frm_suggestion), _) => status_handler_for_frm_results(frm_suggestion),\n (_, Some(authentication_details)) => status_handler_for_authentication_results(\n &authentication_details.authentication,\n ),\n _ => default_status_result,\n };\n\n let connector = payment_data.payment_attempt.connector.clone();\n let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();\n let connector_request_reference_id = payment_data\n .payment_attempt\n .connector_request_reference_id\n .clone();\n\n let straight_through_algorithm = payment_data\n .payment_attempt\n .straight_through_algorithm\n .clone();\n let payment_token = payment_data.token.clone();\n let payment_method_type = payment_data.payment_attempt.payment_method_type;\n let profile_id = payment_data\n .payment_intent\n .profile_id\n .as_ref()\n .get_required_value(\"profile_id\")\n .change_context(errors::ApiErrorResponse::InternalServerError)?;\n\n let payment_experience = payment_data.payment_attempt.payment_experience;\n let additional_pm_data = payment_data\n .payment_method_data\n .as_ref()\n .async_map(|payment_method_data| async {\n helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)\n .await\n })\n .await\n .transpose()?\n .flatten();\n\n let encoded_additional_pm_data = additional_pm_data\n .as_ref()\n .map(Encode::encode_to_value)\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to encode additional pm data\")?;\n\n let customer_details = payment_data.payment_intent.customer_details.clone();\n let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();\n let authentication_type = payment_data.payment_attempt.authentication_type;\n\n let (shipping_address_id, billing_address_id, payment_method_billing_address_id) = (\n payment_data.payment_intent.shipping_address_id.clone(),\n payment_data.payment_intent.billing_address_id.clone(),\n payment_data\n .payment_attempt\n .payment_method_billing_address_id\n .clone(),\n );\n\n let customer_id = customer.clone().map(|c| c.customer_id);\n let return_url = payment_data.payment_intent.return_url.take();\n let setup_future_usage = payment_data.payment_intent.setup_future_usage;\n let business_label = payment_data.payment_intent.business_label.clone();\n let business_country = payment_data.payment_intent.business_country;\n let description = payment_data.payment_intent.description.take();\n let statement_descriptor_name =\n payment_data.payment_intent.statement_descriptor_name.take();\n let statement_descriptor_suffix = payment_data\n .payment_intent\n .statement_descriptor_suffix\n .take();\n let order_details = payment_data.payment_intent.order_details.clone();\n let metadata = payment_data.payment_intent.metadata.clone();\n let frm_metadata = payment_data.payment_intent.frm_metadata.clone();\n\n let client_source = header_payload\n .client_source\n .clone()\n .or(payment_data.payment_attempt.client_source.clone());\n let client_version = header_payload\n .client_version\n .clone()\n .or(payment_data.payment_attempt.client_version.clone());\n\n let m_payment_data_payment_attempt = payment_data.payment_attempt.clone();\n let m_payment_method_id =\n payment_data\n .payment_attempt\n .payment_method_id\n .clone()\n .or(payment_data\n .payment_method_info\n .as_ref()\n .map(|payment_method| payment_method.payment_method_id.clone()));\n let m_browser_info = browser_info.clone();\n let m_connector = connector.clone();\n let m_capture_method = capture_method;\n let m_payment_token = payment_token.clone();\n let m_additional_pm_data = encoded_additional_pm_data\n .clone()\n .or(payment_data.payment_attempt.payment_method_data.clone());\n let m_business_sub_label = business_sub_label.clone();\n let m_straight_through_algorithm = straight_through_algorithm.clone();\n let m_error_code = error_code.clone();\n let m_error_message = error_message.clone();\n let m_fingerprint_id = payment_data.payment_attempt.fingerprint_id.clone();\n let m_db = state.clone().store;\n let surcharge_amount = payment_data\n .surcharge_details\n .as_ref()\n .map(|surcharge_details| surcharge_details.surcharge_amount);\n let tax_amount = payment_data\n .surcharge_details\n .as_ref()\n .map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);\n\n let (\n external_three_ds_authentication_attempted,\n authentication_connector,\n authentication_id,\n ) = match payment_data.authentication.as_ref() {\n Some(authentication_store) => (\n Some(\n authentication_store\n .authentication\n .is_separate_authn_required(),\n ),\n authentication_store\n .authentication\n .authentication_connector\n .clone(),\n Some(\n authentication_store\n .authentication\n .authentication_id\n .clone(),\n ),\n ),\n None => (None, None, None),\n };\n\n let card_discovery = payment_data.get_card_discovery_for_card_payment_method();\n let is_stored_credential = helpers::is_stored_credential(\n &payment_data.recurring_details,\n &payment_data.pm_token,\n payment_data.mandate_id.is_some(),\n payment_data.payment_attempt.is_stored_credential,\n );\n let payment_attempt_fut =\n tokio::spawn(\n async move {\n m_db.update_payment_attempt_with_attempt_id(\n m_payment_data_payment_attempt,\n storage::PaymentAttemptUpdate::ConfirmUpdate {\n currency: payment_data.currency,\n status: attempt_status,\n payment_method,\n authentication_type,\n capture_method: m_capture_method,\n browser_info: m_browser_info,\n connector: m_connector,\n payment_token: m_payment_token,\n payment_method_data: m_additional_pm_data,\n payment_method_type,\n payment_experience,\n business_sub_label: m_business_sub_label,\n straight_through_algorithm: m_straight_through_algorithm,\n error_code: m_error_code,\n error_message: m_error_message,\n updated_by: storage_scheme.to_string(),\n merchant_connector_id,\n external_three_ds_authentication_attempted,\n authentication_connector,\n authentication_id,\n payment_method_billing_address_id,\n fingerprint_id: m_fingerprint_id,\n payment_method_id: m_payment_method_id,\n client_source,\n client_version,\n customer_acceptance: payment_data.payment_attempt.customer_acceptance,\n net_amount:\n hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(\n payment_data.payment_attempt.net_amount.get_order_amount(),\n payment_data.payment_intent.shipping_cost,\n payment_data\n .payment_attempt\n .net_amount\n .get_order_tax_amount(),\n surcharge_amount,\n tax_amount,\n ),\n\n connector_mandate_detail: payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone(),\n card_discovery,\n routing_approach: payment_data.payment_attempt.routing_approach,\n connector_request_reference_id,\n network_transaction_id: payment_data\n .payment_attempt\n .network_transaction_id\n .clone(),\n is_stored_credential,\n request_extended_authorization: payment_data\n .payment_attempt\n .request_extended_authorization,\n tokenization: payment_data\n .payment_attempt\n .connector_mandate_detail\n .as_ref()\n .and_then(|detail| detail.get_tokenization_strategy(\n payment_data.payment_attempt.setup_future_usage_applied,\n ))\n },\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 let billing_address = payment_data.address.get_payment_billing();\n let key_manager_state = state.into();\n let billing_details = billing_address\n .async_map(|billing_details| {\n create_encrypted_data(&key_manager_state, key_store, billing_details)\n })\n .await\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to encrypt billing details\")?;\n\n let shipping_address = payment_data.address.get_shipping();\n let shipping_details = shipping_address\n .async_map(|shipping_details| {\n create_encrypted_data(&key_manager_state, key_store, shipping_details)\n })\n .await\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to encrypt shipping details\")?;\n\n let m_payment_data_payment_intent = payment_data.payment_intent.clone();\n let m_customer_id = customer_id.clone();\n let m_shipping_address_id = shipping_address_id.clone();\n let m_billing_address_id = billing_address_id.clone();\n let m_return_url = return_url.clone();\n let m_business_label = business_label.clone();\n let m_description = description.clone();\n let m_statement_descriptor_name = statement_descriptor_name.clone();\n let m_statement_descriptor_suffix = statement_descriptor_suffix.clone();\n let m_order_details = order_details.clone();\n let m_metadata = metadata.clone();\n let m_frm_metadata = frm_metadata.clone();\n let m_db = state.clone().store;\n let m_storage_scheme = storage_scheme.to_string();\n let session_expiry = m_payment_data_payment_intent.session_expiry;\n let m_key_store = key_store.clone();\n let key_manager_state = state.into();\n let is_payment_processor_token_flow =\n payment_data.payment_intent.is_payment_processor_token_flow;\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 storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {\n amount: payment_data.payment_intent.amount,\n currency: payment_data.currency,\n setup_future_usage,\n status: intent_status,\n customer_id: m_customer_id,\n shipping_address_id: m_shipping_address_id,\n billing_address_id: m_billing_address_id,\n return_url: m_return_url,\n business_country,\n business_label: m_business_label,\n description: m_description,\n statement_descriptor_name: m_statement_descriptor_name,\n statement_descriptor_suffix: m_statement_descriptor_suffix,\n order_details: m_order_details,\n metadata: m_metadata,\n payment_confirm_source: header_payload.payment_confirm_source,\n updated_by: m_storage_scheme,\n fingerprint_id: None,\n session_expiry,\n request_external_three_ds_authentication: None,\n frm_metadata: m_frm_metadata,\n customer_details,\n merchant_order_reference_id: None,\n billing_details,\n shipping_details,\n is_payment_processor_token_flow,\n tax_details: None,\n force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,\n is_iframe_redirection_enabled: payment_data\n .payment_intent\n .is_iframe_redirection_enabled,\n is_confirm_operation: true, // Indicates that this is a confirm operation\n payment_channel: payment_data.payment_intent.payment_channel,\n feature_metadata: payment_data\n .payment_intent\n .feature_metadata\n .clone()\n .map(masking::Secret::new),\n tax_status: payment_data.payment_intent.tax_status,\n discount_amount: payment_data.payment_intent.discount_amount,\n order_date: payment_data.payment_intent.order_date,\n shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,\n duty_amount: payment_data.payment_intent.duty_amount,\n enable_partial_authorization: payment_data\n .payment_intent\n .enable_partial_authorization,\n enable_overcapture: payment_data.payment_intent.enable_overcapture,\n })),\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 let customer_fut =\n if let Some((updated_customer, customer)) = updated_customer.zip(customer) {\n let m_customer_merchant_id = customer.merchant_id.to_owned();\n let m_key_store = key_store.clone();\n let m_updated_customer = updated_customer.clone();\n let session_state = state.clone();\n let m_db = session_state.store.clone();\n let key_manager_state = state.into();\n tokio::spawn(\n async move {\n let m_customer_customer_id = customer.customer_id.to_owned();\n m_db.update_customer_by_customer_id_merchant_id(\n &key_manager_state,\n m_customer_customer_id,\n m_customer_merchant_id,\n customer,\n m_updated_customer,\n &m_key_store,\n storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to update CustomerConnector in customer\")?;\n\n Ok::<_, error_stack::Report>(())\n }\n .in_current_span(),\n )\n } else {\n tokio::spawn(\n async move { Ok::<_, error_stack::Report>(()) }\n .in_current_span(),\n )\n };\n\n let (payment_intent, payment_attempt, _) = tokio::try_join!(\n utils::flatten_join_error(payment_intent_fut),\n utils::flatten_join_error(payment_attempt_fut),\n utils::flatten_join_error(customer_fut)\n )?;\n\n payment_data.payment_intent = payment_intent;\n payment_data.payment_attempt = payment_attempt;\n\n let client_src = payment_data.payment_attempt.client_source.clone();\n let client_ver = payment_data.payment_attempt.client_version.clone();\n\n let frm_message = payment_data.frm_message.clone();\n req_state\n .event_context\n .event(AuditEvent::new(AuditEventType::PaymentConfirm {\n client_src,\n client_ver,\n frm_message: Box::new(frm_message),\n }))\n .with(payment_data.to_event())\n .emit();\n Ok((Box::new(self), payment_data))\n }", + "diff_span": { + "before": " .payment_attempt\n .request_extended_authorization,\n tokenization: core_utils::determine_tokenization_value(\n payment_data\n .payment_attempt\n .connector_mandate_detail\n .clone()\n .as_ref(),\n payment_data\n .payment_attempt.setup_future_usage_applied.clone()\n ),\n },\n storage_scheme,", + "after": " .payment_attempt\n .request_extended_authorization,\n tokenization: payment_data\n .payment_attempt\n .connector_mandate_detail\n .as_ref()\n .and_then(|detail| detail.get_tokenization_strategy(\n payment_data.payment_attempt.setup_future_usage_applied,\n ))\n },\n storage_scheme," + }, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111" + }, + { + "id": "crates/common_enums/src/enums.rs::enum::Tokenization", + "file": "crates/common_enums/src/enums.rs", + "kind": "enum_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub enum Tokenization {\n /// Skip PSP-level tokenization\n SkipPsp,\n /// Via PSP\n ViaPsp,\n}", + "after_code": "pub enum Tokenization {\n /// Skip PSP-level tokenization\n SkipPsp,\n /// Tokenize at PSP Level\n TokenizeAtPsp,\n}", + "diff_span": { + "before": " /// Skip PSP-level tokenization\n SkipPsp,\n /// Via PSP\n ViaPsp,\n}", + "after": " /// Skip PSP-level tokenization\n SkipPsp,\n /// Tokenize at PSP Level\n TokenizeAtPsp,\n}" + }, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111" + }, + { + "id": "crates/diesel_models/src/payment_attempt.rs::ConnectorMandateReferenceId::function::get_tokenization_strategy", + "file": "crates/diesel_models/src/payment_attempt.rs", + "kind": "function_item", + "status": "added", + "before_code": null, + "after_code": "pub fn get_tokenization_strategy(\n &self,\n setup_future_usage: Option,\n ) -> Option {\n match setup_future_usage {\n Some(common_enums::FutureUsage::OnSession) | None => None,\n Some(common_enums::FutureUsage::OffSession) => {\n if self.connector_mandate_id.is_some() {\n Some(common_enums::Tokenization::TokenizeAtPsp)\n } else {\n Some(common_enums::Tokenization::SkipPsp)\n }\n }\n }\n }", + "diff_span": null, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111" + }, + { + "id": "crates/router/src/core/utils.rs::function::determine_tokenization_value", + "file": "crates/router/src/core/utils.rs", + "kind": "function_item", + "status": "removed", + "before_code": "pub fn determine_tokenization_value(\n connector_mandate_detail: Option<&diesel_models::ConnectorMandateReferenceId>,\n setup_future_usage: Option,\n) -> Option {\n match setup_future_usage {\n Some(common_enums::FutureUsage::OnSession) | None => None,\n Some(common_enums::FutureUsage::OffSession) => connector_mandate_detail\n .map(|detail| {\n if detail.connector_mandate_id.is_some() {\n Tokenization::ViaPsp\n } else {\n Tokenization::SkipPsp\n }\n })\n .or(Some(Tokenization::SkipPsp)),\n }\n}", + "after_code": null, + "diff_span": null, + "commit_sha": "c028b951ac8ad3f1c388710b6cc59d26f57d5111" + } + ] +} \ No newline at end of file