diff --git "a/diffs/pr_10091/6dbfc73/diff.json" "b/diffs/pr_10091/6dbfc73/diff.json" new file mode 100644--- /dev/null +++ "b/diffs/pr_10091/6dbfc73/diff.json" @@ -0,0 +1,375 @@ +{ + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6", + "pr_number": 10091, + "rust_files": [ + "crates/api_models/src/webhooks.rs", + "crates/common_enums/src/enums.rs", + "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "crates/hyperswitch_connectors/src/connectors/adyenplatform.rs", + "crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs", + "crates/hyperswitch_interfaces/src/connector_integration_interface.rs", + "crates/hyperswitch_interfaces/src/webhooks.rs", + "crates/router/src/core/revenue_recovery.rs", + "crates/router/src/core/webhooks/incoming.rs", + "crates/router/src/core/webhooks/recovery_incoming.rs", + "crates/router/src/types/storage/revenue_recovery_redis_operation.rs", + "crates/router/src/workflows/revenue_recovery.rs" + ], + "diffs": [ + { + "id": "crates/router/src/core/webhooks/incoming.rs::function::process_webhook_business_logic", + "file": "crates/router/src/core/webhooks/incoming.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "async fn process_webhook_business_logic(\n state: &SessionState,\n req_state: ReqState,\n merchant_context: &domain::MerchantContext,\n connector: &ConnectorEnum,\n connector_name: &str,\n event_type: webhooks::IncomingWebhookEvent,\n source_verified_via_ucs: bool,\n webhook_transform_data: &Option>,\n shadow_ucs_data: &mut Option>,\n request_details: &IncomingWebhookRequestDetails<'_>,\n is_relay_webhook: bool,\n) -> errors::RouterResult {\n let object_ref_id = connector\n .get_webhook_object_reference_id(request_details)\n .switch()\n .attach_printable(\"Could not find object reference id in incoming webhook body\")?;\n let connector_enum = Connector::from_str(connector_name)\n .change_context(errors::ApiErrorResponse::InvalidDataValue {\n field_name: \"connector\",\n })\n .attach_printable_lazy(|| format!(\"unable to parse connector name {connector_name:?}\"))?;\n let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;\n\n let merchant_connector_account = match Box::pin(helper_utils::get_mca_from_object_reference_id(\n state,\n object_ref_id.clone(),\n merchant_context,\n connector_name,\n ))\n .await\n {\n Ok(mca) => mca,\n Err(error) => {\n let result = handle_incoming_webhook_error(\n error,\n connector,\n connector_name,\n request_details,\n merchant_context.get_merchant_account().get_id(),\n );\n match result {\n Ok((_, webhook_tracker, _)) => return Ok(webhook_tracker),\n Err(e) => return Err(e),\n }\n }\n };\n\n let source_verified = if source_verified_via_ucs {\n // If UCS handled verification, use that result\n source_verified_via_ucs\n } else {\n // Fall back to traditional source verification\n if connectors_with_source_verification_call\n .connectors_with_webhook_source_verification_call\n .contains(&connector_enum)\n {\n verify_webhook_source_verification_call(\n connector.clone(),\n state,\n merchant_context,\n merchant_connector_account.clone(),\n connector_name,\n request_details,\n )\n .await\n .or_else(|error| match error.current_context() {\n errors::ConnectorError::WebhookSourceVerificationFailed => {\n logger::error!(?error, \"Source Verification Failed\");\n Ok(false)\n }\n _ => Err(error),\n })\n .switch()\n .attach_printable(\"There was an issue in incoming webhook source verification\")?\n } else {\n connector\n .clone()\n .verify_webhook_source(\n request_details,\n merchant_context.get_merchant_account().get_id(),\n merchant_connector_account.connector_webhook_details.clone(),\n merchant_connector_account.connector_account_details.clone(),\n connector_name,\n )\n .await\n .or_else(|error| match error.current_context() {\n errors::ConnectorError::WebhookSourceVerificationFailed => {\n logger::error!(?error, \"Source Verification Failed\");\n Ok(false)\n }\n _ => Err(error),\n })\n .switch()\n .attach_printable(\"There was an issue in incoming webhook source verification\")?\n }\n };\n\n if source_verified {\n metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(\n 1,\n router_env::metric_attributes!((\n MERCHANT_ID,\n merchant_context.get_merchant_account().get_id().clone()\n )),\n );\n } else if connector.is_webhook_source_verification_mandatory() {\n // if webhook consumption is mandatory for connector, fail webhook\n // so that merchant can retrigger it after updating merchant_secret\n return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into());\n }\n\n logger::info!(source_verified=?source_verified);\n\n let event_object: Box = match webhook_transform_data {\n Some(webhook_transform_data) => {\n // Extract resource_object from UCS webhook content\n webhook_transform_data\n .webhook_content\n .as_ref()\n .map(|webhook_response_content| {\n get_ucs_webhook_resource_object(webhook_response_content)\n })\n .unwrap_or_else(|| {\n // Fall back to connector extraction\n connector\n .get_webhook_resource_object(request_details)\n .switch()\n .attach_printable(\"Could not find resource object in incoming webhook body\")\n })?\n }\n None => {\n // Use traditional connector extraction\n connector\n .get_webhook_resource_object(request_details)\n .switch()\n .attach_printable(\"Could not find resource object in incoming webhook body\")?\n }\n };\n\n let webhook_details = api::IncomingWebhookDetails {\n object_reference_id: object_ref_id.clone(),\n resource_object: serde_json::to_vec(&event_object)\n .change_context(errors::ParsingError::EncodeError(\"byte-vec\"))\n .attach_printable(\"Unable to convert webhook payload to a value\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"There was an issue when encoding the incoming webhook body to bytes\",\n )?,\n };\n\n // Create shadow_event_object and shadow_webhook_details using shadow UCS data\n let shadow_event_object: Option> =\n shadow_ucs_data.as_ref().and_then(|shadow_data| {\n // Create shadow event object using UCS transform data and shadow request details\n let shadow_event_result = shadow_data\n .ucs_transform_data\n .webhook_content\n .as_ref()\n .map(|webhook_response_content| {\n get_ucs_webhook_resource_object(webhook_response_content)\n })\n .unwrap_or_else(|| {\n // Fall back to connector extraction using shadow request details\n connector\n .get_webhook_resource_object(shadow_data.request_details)\n .switch()\n .attach_printable(\n \"Could not find resource object in shadow incoming webhook body\",\n )\n });\n\n match shadow_event_result {\n Ok(shadow_obj) => Some(shadow_obj),\n Err(error) => {\n logger::warn!(\n connector = connector_name,\n merchant_id = ?merchant_context.get_merchant_account().get_id(),\n error = ?error,\n \"Failed to create shadow event object from UCS transform data\"\n );\n None\n }\n }\n });\n\n let shadow_webhook_details: Option =\n shadow_event_object.as_ref().and_then(|shadow_obj| {\n let resource_object_result = serde_json::to_vec(shadow_obj)\n .change_context(errors::ParsingError::EncodeError(\"byte-vec\"))\n .attach_printable(\"Unable to convert shadow webhook payload to a value\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"There was an issue when encoding the shadow incoming webhook body to bytes\",\n );\n\n match resource_object_result {\n Ok(resource_object) => Some(api::IncomingWebhookDetails {\n object_reference_id: object_ref_id.clone(),\n resource_object,\n }),\n Err(error) => {\n logger::warn!(\n connector = connector_name,\n merchant_id = ?merchant_context.get_merchant_account().get_id(),\n error = ?error,\n \"Failed to serialize shadow webhook payload to bytes\"\n );\n None\n }\n }\n });\n\n // Assign shadow_webhook_details to shadow_ucs_data\n if let Some(shadow_data) = shadow_ucs_data.as_mut() {\n shadow_data.webhook_details = shadow_webhook_details;\n }\n\n let profile_id = &merchant_connector_account.profile_id;\n let key_manager_state = &(state).into();\n\n let business_profile = state\n .store\n .find_business_profile_by_profile_id(\n key_manager_state,\n merchant_context.get_merchant_key_store(),\n profile_id,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow\n let result_response = if is_relay_webhook {\n let relay_webhook_response = Box::pin(relay_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n event_type,\n source_verified,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for relay failed\");\n\n // Using early return ensures unsupported webhooks are acknowledged to the connector\n if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response\n .as_ref()\n .err()\n .map(|a| a.current_context())\n {\n logger::error!(\n webhook_payload =? request_details.body,\n \"Failed while identifying the event type\",\n );\n\n let _response = connector\n .get_webhook_api_response(request_details, None)\n .switch()\n .attach_printable(\n \"Failed while early return in case of not supported event type in relay webhooks\",\n )?;\n\n return Ok(WebhookResponseTracker::NoEffect);\n };\n\n relay_webhook_response\n } else {\n let flow_type: api::WebhookFlow = event_type.into();\n match flow_type {\n api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n connector,\n request_details,\n event_type,\n webhook_transform_data,\n shadow_ucs_data,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for payments failed\"),\n\n api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n connector_name,\n source_verified,\n event_type,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for refunds failed\"),\n\n api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n connector,\n request_details,\n event_type,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for disputes failed\"),\n\n api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n ))\n .await\n .attach_printable(\"Incoming bank-transfer webhook flow failed\"),\n\n api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect),\n\n api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n event_type,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for mandates failed\"),\n\n api::WebhookFlow::ExternalAuthentication => {\n Box::pin(external_authentication_incoming_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n source_verified,\n event_type,\n request_details,\n connector,\n object_ref_id,\n business_profile,\n merchant_connector_account,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for external authentication failed\")\n }\n api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n source_verified,\n event_type,\n object_ref_id,\n business_profile,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for fraud check failed\"),\n\n #[cfg(feature = \"payouts\")]\n api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n event_type,\n source_verified,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for payouts failed\"),\n\n api::WebhookFlow::Subscription => {\n Box::pin(subscriptions::webhooks::incoming_webhook_flow(\n state.clone().into(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n connector,\n request_details,\n event_type,\n merchant_connector_account,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for subscription failed\")\n }\n\n _ => Err(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unsupported Flow Type received in incoming webhooks\"),\n }\n };\n\n match result_response {\n Ok(response) => Ok(response),\n Err(error) => {\n let result = handle_incoming_webhook_error(\n error,\n connector,\n connector_name,\n request_details,\n merchant_context.get_merchant_account().get_id(),\n );\n match result {\n Ok((_, webhook_tracker, _)) => Ok(webhook_tracker),\n Err(e) => Err(e),\n }\n }\n }\n}", + "after_code": "async fn process_webhook_business_logic(\n state: &SessionState,\n req_state: ReqState,\n merchant_context: &domain::MerchantContext,\n connector: &ConnectorEnum,\n connector_name: &str,\n event_type: webhooks::IncomingWebhookEvent,\n source_verified_via_ucs: bool,\n webhook_transform_data: &Option>,\n shadow_ucs_data: &mut Option>,\n request_details: &IncomingWebhookRequestDetails<'_>,\n is_relay_webhook: bool,\n) -> errors::RouterResult {\n let object_ref_id = connector\n .get_webhook_object_reference_id(request_details)\n .switch()\n .attach_printable(\"Could not find object reference id in incoming webhook body\")?;\n let connector_enum = Connector::from_str(connector_name)\n .change_context(errors::ApiErrorResponse::InvalidDataValue {\n field_name: \"connector\",\n })\n .attach_printable_lazy(|| format!(\"unable to parse connector name {connector_name:?}\"))?;\n let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;\n\n let merchant_connector_account = match Box::pin(helper_utils::get_mca_from_object_reference_id(\n state,\n object_ref_id.clone(),\n merchant_context,\n connector_name,\n ))\n .await\n {\n Ok(mca) => mca,\n Err(error) => {\n let result = handle_incoming_webhook_error(\n error,\n connector,\n connector_name,\n request_details,\n merchant_context.get_merchant_account().get_id(),\n );\n match result {\n Ok((_, webhook_tracker, _)) => return Ok(webhook_tracker),\n Err(e) => return Err(e),\n }\n }\n };\n\n let source_verified = if source_verified_via_ucs {\n // If UCS handled verification, use that result\n source_verified_via_ucs\n } else {\n // Fall back to traditional source verification\n if connectors_with_source_verification_call\n .connectors_with_webhook_source_verification_call\n .contains(&connector_enum)\n {\n verify_webhook_source_verification_call(\n connector.clone(),\n state,\n merchant_context,\n merchant_connector_account.clone(),\n connector_name,\n request_details,\n )\n .await\n .or_else(|error| match error.current_context() {\n errors::ConnectorError::WebhookSourceVerificationFailed => {\n logger::error!(?error, \"Source Verification Failed\");\n Ok(false)\n }\n _ => Err(error),\n })\n .switch()\n .attach_printable(\"There was an issue in incoming webhook source verification\")?\n } else {\n connector\n .clone()\n .verify_webhook_source(\n request_details,\n merchant_context.get_merchant_account().get_id(),\n merchant_connector_account.connector_webhook_details.clone(),\n merchant_connector_account.connector_account_details.clone(),\n connector_name,\n )\n .await\n .or_else(|error| match error.current_context() {\n errors::ConnectorError::WebhookSourceVerificationFailed => {\n logger::error!(?error, \"Source Verification Failed\");\n Ok(false)\n }\n _ => Err(error),\n })\n .switch()\n .attach_printable(\"There was an issue in incoming webhook source verification\")?\n }\n };\n\n if source_verified {\n metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(\n 1,\n router_env::metric_attributes!((\n MERCHANT_ID,\n merchant_context.get_merchant_account().get_id().clone()\n )),\n );\n } else if connector.is_webhook_source_verification_mandatory() {\n // if webhook consumption is mandatory for connector, fail webhook\n // so that merchant can retrigger it after updating merchant_secret\n return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into());\n }\n\n logger::info!(source_verified=?source_verified);\n\n let event_object: Box = match webhook_transform_data {\n Some(webhook_transform_data) => {\n // Extract resource_object from UCS webhook content\n webhook_transform_data\n .webhook_content\n .as_ref()\n .map(|webhook_response_content| {\n get_ucs_webhook_resource_object(webhook_response_content)\n })\n .unwrap_or_else(|| {\n // Fall back to connector extraction\n connector\n .get_webhook_resource_object(request_details)\n .switch()\n .attach_printable(\"Could not find resource object in incoming webhook body\")\n })?\n }\n None => {\n // Use traditional connector extraction\n connector\n .get_webhook_resource_object(request_details)\n .switch()\n .attach_printable(\"Could not find resource object in incoming webhook body\")?\n }\n };\n\n let webhook_details = api::IncomingWebhookDetails {\n object_reference_id: object_ref_id.clone(),\n resource_object: serde_json::to_vec(&event_object)\n .change_context(errors::ParsingError::EncodeError(\"byte-vec\"))\n .attach_printable(\"Unable to convert webhook payload to a value\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"There was an issue when encoding the incoming webhook body to bytes\",\n )?,\n };\n\n // Create shadow_event_object and shadow_webhook_details using shadow UCS data\n let shadow_event_object: Option> =\n shadow_ucs_data.as_ref().and_then(|shadow_data| {\n // Create shadow event object using UCS transform data and shadow request details\n let shadow_event_result = shadow_data\n .ucs_transform_data\n .webhook_content\n .as_ref()\n .map(|webhook_response_content| {\n get_ucs_webhook_resource_object(webhook_response_content)\n })\n .unwrap_or_else(|| {\n // Fall back to connector extraction using shadow request details\n connector\n .get_webhook_resource_object(shadow_data.request_details)\n .switch()\n .attach_printable(\n \"Could not find resource object in shadow incoming webhook body\",\n )\n });\n\n match shadow_event_result {\n Ok(shadow_obj) => Some(shadow_obj),\n Err(error) => {\n logger::warn!(\n connector = connector_name,\n merchant_id = ?merchant_context.get_merchant_account().get_id(),\n error = ?error,\n \"Failed to create shadow event object from UCS transform data\"\n );\n None\n }\n }\n });\n\n let shadow_webhook_details: Option =\n shadow_event_object.as_ref().and_then(|shadow_obj| {\n let resource_object_result = serde_json::to_vec(shadow_obj)\n .change_context(errors::ParsingError::EncodeError(\"byte-vec\"))\n .attach_printable(\"Unable to convert shadow webhook payload to a value\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"There was an issue when encoding the shadow incoming webhook body to bytes\",\n );\n\n match resource_object_result {\n Ok(resource_object) => Some(api::IncomingWebhookDetails {\n object_reference_id: object_ref_id.clone(),\n resource_object,\n }),\n Err(error) => {\n logger::warn!(\n connector = connector_name,\n merchant_id = ?merchant_context.get_merchant_account().get_id(),\n error = ?error,\n \"Failed to serialize shadow webhook payload to bytes\"\n );\n None\n }\n }\n });\n\n // Assign shadow_webhook_details to shadow_ucs_data\n if let Some(shadow_data) = shadow_ucs_data.as_mut() {\n shadow_data.webhook_details = shadow_webhook_details;\n }\n\n let profile_id = &merchant_connector_account.profile_id;\n let key_manager_state = &(state).into();\n\n let business_profile = state\n .store\n .find_business_profile_by_profile_id(\n key_manager_state,\n merchant_context.get_merchant_key_store(),\n profile_id,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow\n let result_response = if is_relay_webhook {\n let relay_webhook_response = Box::pin(relay_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n event_type,\n source_verified,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for relay failed\");\n\n // Using early return ensures unsupported webhooks are acknowledged to the connector\n if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response\n .as_ref()\n .err()\n .map(|a| a.current_context())\n {\n logger::error!(\n webhook_payload =? request_details.body,\n \"Failed while identifying the event type\",\n );\n\n let _response = connector\n .get_webhook_api_response(request_details, None)\n .switch()\n .attach_printable(\n \"Failed while early return in case of not supported event type in relay webhooks\",\n )?;\n\n return Ok(WebhookResponseTracker::NoEffect);\n };\n\n relay_webhook_response\n } else {\n let flow_type: api::WebhookFlow = event_type.into();\n match flow_type {\n api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n connector,\n request_details,\n event_type,\n webhook_transform_data,\n shadow_ucs_data,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for payments failed\"),\n\n api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n connector_name,\n source_verified,\n event_type,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for refunds failed\"),\n\n api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n connector,\n request_details,\n event_type,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for disputes failed\"),\n\n api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n ))\n .await\n .attach_printable(\"Incoming bank-transfer webhook flow failed\"),\n\n api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect),\n\n api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n event_type,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for mandates failed\"),\n\n api::WebhookFlow::ExternalAuthentication => {\n Box::pin(external_authentication_incoming_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n source_verified,\n event_type,\n request_details,\n connector,\n object_ref_id,\n business_profile,\n merchant_connector_account,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for external authentication failed\")\n }\n api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow(\n state.clone(),\n req_state,\n merchant_context.clone(),\n source_verified,\n event_type,\n object_ref_id,\n business_profile,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for fraud check failed\"),\n\n #[cfg(feature = \"payouts\")]\n api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(\n state.clone(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n event_type,\n source_verified,\n request_details,\n connector,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for payouts failed\"),\n\n api::WebhookFlow::Subscription => {\n Box::pin(subscriptions::webhooks::incoming_webhook_flow(\n state.clone().into(),\n merchant_context.clone(),\n business_profile,\n webhook_details,\n source_verified,\n connector,\n request_details,\n event_type,\n merchant_connector_account,\n ))\n .await\n .attach_printable(\"Incoming webhook flow for subscription failed\")\n }\n\n _ => Err(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unsupported Flow Type received in incoming webhooks\"),\n }\n };\n\n match result_response {\n Ok(response) => Ok(response),\n Err(error) => {\n let result = handle_incoming_webhook_error(\n error,\n connector,\n connector_name,\n request_details,\n merchant_context.get_merchant_account().get_id(),\n );\n match result {\n Ok((_, webhook_tracker, _)) => Ok(webhook_tracker),\n Err(e) => Err(e),\n }\n }\n }\n}", + "diff_span": { + "before": "", + "after": " event_type,\n source_verified,\n request_details,\n connector,\n ))\n .await" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs::struct::AdyenplatformTrackingData", + "file": "crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs", + "kind": "struct_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub struct AdyenplatformTrackingData {\n status: TrackingStatus,\n estimated_arrival_time: Option,\n}", + "after_code": "pub struct AdyenplatformTrackingData {\n pub status: TrackingStatus,\n pub reason: Option,\n pub estimated_arrival_time: Option,\n}", + "diff_span": { + "before": "pub struct AdyenplatformTrackingData {\n status: TrackingStatus,\n estimated_arrival_time: Option,\n}", + "after": "pub struct AdyenplatformTrackingData {\n pub status: TrackingStatus,\n pub reason: Option,\n pub estimated_arrival_time: Option,\n}" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs::AdyenRefundRequest::function::try_from", + "file": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "fn try_from(item: &AdyenRouterData<&RefundsRouterData>) -> Result {\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let (store, splits) = match item\n .router_data\n .request\n .split_refunds\n .as_ref()\n {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (None, None),\n };\n\n Ok(Self {\n merchant_account: auth_type.merchant_account,\n amount: Amount {\n currency: item.router_data.request.currency,\n value: item.amount,\n },\n merchant_refund_reason: item\n .router_data\n .request\n .reason\n .as_ref()\n .map(|reason| AdyenRefundRequestReason::from_str(reason))\n .transpose()?,\n reference: item.router_data.request.refund_id.clone(),\n store,\n splits,\n })\n }", + "after_code": "fn try_from(item: &AdyenRouterData<&RefundsRouterData>) -> Result {\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let (store, splits) = match item\n .router_data\n .request\n .split_refunds\n .as_ref()\n {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .refund_connector_metadata\n .clone()\n .and_then(|metadata| get_store_id(metadata.expose())),\n None,\n ),\n };\n\n Ok(Self {\n merchant_account: auth_type.merchant_account,\n amount: Amount {\n currency: item.router_data.request.currency,\n value: item.amount,\n },\n merchant_refund_reason: item\n .router_data\n .request\n .reason\n .as_ref()\n .map(|reason| AdyenRefundRequestReason::from_str(reason))\n .transpose()?,\n reference: item.router_data.request.refund_id.clone(),\n store,\n splits,\n })\n }", + "diff_span": { + "before": " {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (None, None),\n };\n", + "after": " {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .refund_connector_metadata\n .clone()\n .and_then(|metadata| get_store_id(metadata.expose())),\n None,\n ),\n };\n" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/router/src/workflows/revenue_recovery.rs::function::get_best_psp_token_available_for_smart_retry", + "file": "crates/router/src/workflows/revenue_recovery.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub async fn get_best_psp_token_available_for_smart_retry(\n state: &SessionState,\n connector_customer_id: &str,\n payment_intent: &PaymentIntent,\n) -> CustomResult {\n // Lock using payment_id\n let locked = RedisTokenManager::lock_connector_customer_status(\n state,\n connector_customer_id,\n &payment_intent.id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n match locked {\n false => {\n let token_details =\n RedisTokenManager::get_payment_processor_metadata_for_connector_customer(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n // Check token with schedule time in Redis\n let token_info_with_schedule_time = token_details\n .values()\n .find(|info| info.token_status.scheduled_at.is_some());\n\n // Check for hard decline if info is none\n let hard_decline_status = token_details\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false));\n\n let mut payment_processor_token_response = PaymentProcessorTokenResponse::None;\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = match token_info_with_schedule_time\n .as_ref()\n .and_then(|t| t.token_status.scheduled_at)\n {\n Some(scheduled_time) => PaymentProcessorTokenResponse::NextAvailableTime {\n next_available_time: scheduled_time,\n },\n None => PaymentProcessorTokenResponse::None,\n };\n }\n\n Ok(payment_processor_token_response)\n }\n\n true => {\n // Get existing tokens from Redis\n let existing_tokens =\n RedisTokenManager::get_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let active_tokens: HashMap<_, _> = existing_tokens\n .into_iter()\n .filter(|(_, token_status)| token_status.is_active != Some(false))\n .collect();\n\n let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &active_tokens);\n\n let payment_processor_token_response =\n call_decider_for_payment_processor_tokens_select_closest_time(\n state,\n &result,\n payment_intent,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n Ok(payment_processor_token_response)\n }\n }\n}", + "after_code": "pub async fn get_best_psp_token_available_for_smart_retry(\n state: &SessionState,\n connector_customer_id: &str,\n payment_intent: &PaymentIntent,\n) -> CustomResult {\n // Lock using payment_id\n let locked_acquired = RedisTokenManager::lock_connector_customer_status(\n state,\n connector_customer_id,\n &payment_intent.id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n match locked_acquired {\n false => {\n let token_details =\n RedisTokenManager::get_payment_processor_metadata_for_connector_customer(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n // Check token with schedule time in Redis\n let token_info_with_schedule_time = token_details\n .values()\n .find(|info| info.token_status.scheduled_at.is_some());\n\n // Check for hard decline if info is none\n let hard_decline_status = token_details\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false));\n\n let mut payment_processor_token_response = PaymentProcessorTokenResponse::None;\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = match token_info_with_schedule_time\n .as_ref()\n .and_then(|t| t.token_status.scheduled_at)\n {\n Some(scheduled_time) => PaymentProcessorTokenResponse::NextAvailableTime {\n next_available_time: scheduled_time,\n },\n None => PaymentProcessorTokenResponse::None,\n };\n }\n\n Ok(payment_processor_token_response)\n }\n\n true => {\n // Get existing tokens from Redis\n let existing_tokens =\n RedisTokenManager::get_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let active_tokens: HashMap<_, _> = existing_tokens\n .into_iter()\n .filter(|(_, token_status)| token_status.is_active != Some(false))\n .collect();\n\n let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &active_tokens);\n\n let payment_processor_token_response =\n call_decider_for_payment_processor_tokens_select_closest_time(\n state,\n &result,\n payment_intent,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n Ok(payment_processor_token_response)\n }\n }\n}", + "diff_span": { + "before": ") -> CustomResult {\n // Lock using payment_id\n let locked = RedisTokenManager::lock_connector_customer_status(\n state,\n connector_customer_id,\n &payment_intent.id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n match locked {\n false => {\n let token_details =", + "after": ") -> CustomResult {\n // Lock using payment_id\n let locked_acquired = RedisTokenManager::lock_connector_customer_status(\n state,\n connector_customer_id,\n &payment_intent.id,\n )\n .await\n .change_context(errors::ProcessTrackerError::ERedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n match locked_acquired {\n false => {\n let token_details =" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::impl::RedisTokenManager", + "file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs", + "kind": "impl_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap,\n ) -> HashMap {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let modified_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n (existing_token.modified_at < modified_at).then(|| {\n existing_token.modified_at = modified_at;\n error_code.map(|err| existing_token.error_code = Some(err));\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option,\n is_hard_decline: &Option,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option,\n ) -> CustomResult {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}", + "after_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap,\n ) -> HashMap {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option,\n is_hard_decline: &Option,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option,\n ) -> CustomResult {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}", + "diff_span": { + "before": " let error_code = token_data.error_code.clone();\n\n let modified_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n (existing_token.modified_at < modified_at).then(|| {\n existing_token.modified_at = modified_at;\n error_code.map(|err| existing_token.error_code = Some(err));\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {", + "after": " let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs::impl::AdyenPaymentRequest<'_>", + "file": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "kind": "impl_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "impl\n TryFrom<(\n &AdyenRouterData<&PaymentsAuthorizeRouterData>,\n &NetworkTokenData,\n )> for AdyenPaymentRequest<'_>\n{\n type Error = Error;\n fn try_from(\n value: (\n &AdyenRouterData<&PaymentsAuthorizeRouterData>,\n &NetworkTokenData,\n ),\n ) -> Result {\n let (item, token_data) = value;\n let amount = get_amount_data(item);\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let shopper_interaction = AdyenShopperInteraction::from(item.router_data);\n let shopper_reference = build_shopper_reference(item.router_data);\n let (recurring_processing_model, store_payment_method, _) =\n get_recurring_processing_model(item.router_data)?;\n let browser_info = get_browser_info(item.router_data)?;\n let billing_address =\n get_address_info(item.router_data.get_optional_billing()).transpose()?;\n let country_code = get_country_code(item.router_data.get_optional_billing());\n let additional_data = get_additional_data(item.router_data);\n let return_url = item.router_data.request.get_router_return_url()?;\n let testing_data = item\n .router_data\n .request\n .get_connector_testing_data()\n .map(AdyenTestingData::try_from)\n .transpose()?;\n let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name);\n let card_holder_name =\n test_holder_name.or(item.router_data.get_optional_billing_full_name());\n let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new(\n AdyenPaymentMethod::try_from((token_data, card_holder_name))?,\n ));\n\n let shopper_email = item.router_data.request.email.clone();\n let shopper_name = get_shopper_name(item.router_data.get_optional_billing());\n let mpi_data = AdyenMpiData {\n directory_response: \"Y\".to_string(),\n authentication_response: \"Y\".to_string(),\n cavv: None,\n token_authentication_verification_value: Some(\n token_data.get_cryptogram().clone().unwrap_or_default(),\n ),\n eci: Some(\"02\".to_string()),\n };\n let (store, splits) = match item.router_data.request.split_payments.as_ref() {\n Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(\n adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (None, None),\n };\n let device_fingerprint = item\n .router_data\n .request\n .metadata\n .clone()\n .and_then(get_device_fingerprint);\n\n let delivery_address =\n get_address_info(item.router_data.get_optional_shipping()).and_then(Result::ok);\n let telephone_number = item.router_data.get_optional_billing_phone_number();\n\n Ok(AdyenPaymentRequest {\n amount,\n merchant_account: auth_type.merchant_account,\n payment_method,\n reference: item.router_data.connector_request_reference_id.clone(),\n return_url,\n shopper_interaction,\n recurring_processing_model,\n browser_info,\n additional_data,\n telephone_number,\n shopper_name,\n shopper_email,\n shopper_locale: item.router_data.request.locale.clone(),\n social_security_number: None,\n billing_address,\n delivery_address,\n country_code,\n line_items: None,\n shopper_reference,\n store_payment_method,\n channel: None,\n shopper_statement: item.router_data.request.statement_descriptor.clone(),\n shopper_ip: item.router_data.request.get_ip_address_as_optional(),\n merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(),\n mpi_data: Some(mpi_data),\n store,\n splits,\n device_fingerprint,\n session_validity: None,\n metadata: item.router_data.request.metadata.clone(),\n })\n }\n}", + "after_code": "impl\n TryFrom<(\n &AdyenRouterData<&PaymentsAuthorizeRouterData>,\n &NetworkTokenData,\n )> for AdyenPaymentRequest<'_>\n{\n type Error = Error;\n fn try_from(\n value: (\n &AdyenRouterData<&PaymentsAuthorizeRouterData>,\n &NetworkTokenData,\n ),\n ) -> Result {\n let (item, token_data) = value;\n let amount = get_amount_data(item);\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let shopper_interaction = AdyenShopperInteraction::from(item.router_data);\n let shopper_reference = build_shopper_reference(item.router_data);\n let (recurring_processing_model, store_payment_method, _) =\n get_recurring_processing_model(item.router_data)?;\n let browser_info = get_browser_info(item.router_data)?;\n let billing_address =\n get_address_info(item.router_data.get_optional_billing()).transpose()?;\n let country_code = get_country_code(item.router_data.get_optional_billing());\n let additional_data = get_additional_data(item.router_data);\n let return_url = item.router_data.request.get_router_return_url()?;\n let testing_data = item\n .router_data\n .request\n .get_connector_testing_data()\n .map(AdyenTestingData::try_from)\n .transpose()?;\n let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name);\n let card_holder_name =\n test_holder_name.or(item.router_data.get_optional_billing_full_name());\n let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new(\n AdyenPaymentMethod::try_from((token_data, card_holder_name))?,\n ));\n\n let shopper_email = item.router_data.request.email.clone();\n let shopper_name = get_shopper_name(item.router_data.get_optional_billing());\n let mpi_data = AdyenMpiData {\n directory_response: \"Y\".to_string(),\n authentication_response: \"Y\".to_string(),\n cavv: None,\n token_authentication_verification_value: Some(\n token_data.get_cryptogram().clone().unwrap_or_default(),\n ),\n eci: Some(\"02\".to_string()),\n };\n let (store, splits) = match item.router_data.request.split_payments.as_ref() {\n Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(\n adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .metadata\n .clone()\n .and_then(get_store_id),\n None,\n ),\n };\n let device_fingerprint = item\n .router_data\n .request\n .metadata\n .clone()\n .and_then(get_device_fingerprint);\n\n let delivery_address =\n get_address_info(item.router_data.get_optional_shipping()).and_then(Result::ok);\n let telephone_number = item.router_data.get_optional_billing_phone_number();\n\n Ok(AdyenPaymentRequest {\n amount,\n merchant_account: auth_type.merchant_account,\n payment_method,\n reference: item.router_data.connector_request_reference_id.clone(),\n return_url,\n shopper_interaction,\n recurring_processing_model,\n browser_info,\n additional_data,\n telephone_number,\n shopper_name,\n shopper_email,\n shopper_locale: item.router_data.request.locale.clone(),\n social_security_number: None,\n billing_address,\n delivery_address,\n country_code,\n line_items: None,\n shopper_reference,\n store_payment_method,\n channel: None,\n shopper_statement: item.router_data.request.statement_descriptor.clone(),\n shopper_ip: item.router_data.request.get_ip_address_as_optional(),\n merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(),\n mpi_data: Some(mpi_data),\n store,\n splits,\n device_fingerprint,\n session_validity: None,\n metadata: item.router_data.request.metadata.clone(),\n })\n }\n}", + "diff_span": { + "before": " adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (None, None),\n };\n let device_fingerprint = item", + "after": " adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .metadata\n .clone()\n .and_then(get_store_id),\n None,\n ),\n };\n let device_fingerprint = item" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_interfaces/src/webhooks.rs::trait::IncomingWebhook", + "file": "crates/hyperswitch_interfaces/src/webhooks.rs", + "kind": "trait_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub trait IncomingWebhook: ConnectorCommon + Sync {\n /// fn get_webhook_body_decoding_algorithm\n fn get_webhook_body_decoding_algorithm(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Box::new(crypto::NoAlgorithm))\n }\n\n /// fn get_webhook_body_decoding_message\n fn get_webhook_body_decoding_message(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(request.body.to_vec())\n }\n\n /// fn decode_webhook_body\n async fn decode_webhook_body(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_webhook_details: Option,\n connector_name: &str,\n ) -> CustomResult, errors::ConnectorError> {\n let algorithm = self.get_webhook_body_decoding_algorithm(request)?;\n\n let message = self\n .get_webhook_body_decoding_message(request)\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n let secret = self\n .get_webhook_source_verification_merchant_secret(\n merchant_id,\n connector_name,\n connector_webhook_details,\n )\n .await\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n algorithm\n .decode_message(&secret.secret, message.into())\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)\n }\n\n /// fn get_webhook_source_verification_algorithm\n fn get_webhook_source_verification_algorithm(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Box::new(crypto::NoAlgorithm))\n }\n\n /// fn get_webhook_source_verification_merchant_secret\n async fn get_webhook_source_verification_merchant_secret(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_name: &str,\n connector_webhook_details: Option,\n ) -> CustomResult {\n let debug_suffix =\n format!(\"For merchant_id: {merchant_id:?}, and connector_name: {connector_name}\");\n let default_secret = \"default_secret\".to_string();\n let merchant_secret = match connector_webhook_details {\n Some(merchant_connector_webhook_details) => {\n let connector_webhook_details = merchant_connector_webhook_details\n .parse_value::(\n \"MerchantConnectorWebhookDetails\",\n )\n .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)\n .attach_printable_lazy(|| {\n format!(\n \"Deserializing MerchantConnectorWebhookDetails failed {debug_suffix}\",\n )\n })?;\n api_models::webhooks::ConnectorWebhookSecrets {\n secret: connector_webhook_details\n .merchant_secret\n .expose()\n .into_bytes(),\n additional_secret: connector_webhook_details.additional_secret,\n }\n }\n\n None => api_models::webhooks::ConnectorWebhookSecrets {\n secret: default_secret.into_bytes(),\n additional_secret: None,\n },\n };\n\n //need to fetch merchant secret from config table with caching in future for enhanced performance\n\n //If merchant has not set the secret for webhook source verification, \"default_secret\" is returned.\n //So it will fail during verification step and goes to psync flow.\n Ok(merchant_secret)\n }\n\n /// fn get_webhook_source_verification_signature\n fn get_webhook_source_verification_signature(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Vec::new())\n }\n\n /// fn get_webhook_source_verification_message\n fn get_webhook_source_verification_message(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _merchant_id: &common_utils::id_type::MerchantId,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Vec::new())\n }\n\n /// fn verify_webhook_source\n async fn verify_webhook_source(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_webhook_details: Option,\n _connector_account_details: crypto::Encryptable>,\n connector_name: &str,\n ) -> CustomResult {\n let algorithm = self\n .get_webhook_source_verification_algorithm(request)\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n let connector_webhook_secrets = self\n .get_webhook_source_verification_merchant_secret(\n merchant_id,\n connector_name,\n connector_webhook_details,\n )\n .await\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n let signature = self\n .get_webhook_source_verification_signature(request, &connector_webhook_secrets)\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n let message = self\n .get_webhook_source_verification_message(\n request,\n merchant_id,\n &connector_webhook_secrets,\n )\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n algorithm\n .verify_signature(&connector_webhook_secrets.secret, &signature, &message)\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)\n }\n\n /// fn get_webhook_object_reference_id\n fn get_webhook_object_reference_id(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult;\n\n /// fn get_webhook_event_type\n fn get_webhook_event_type(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult;\n\n /// fn get_webhook_resource_object\n fn get_webhook_resource_object(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError>;\n\n /// fn get_webhook_api_response\n fn get_webhook_api_response(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _error_kind: Option,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(ApplicationResponse::StatusOk)\n }\n\n /// fn get_dispute_details\n fn get_dispute_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_dispute_details method\".to_string()).into())\n }\n\n /// fn get_external_authentication_details\n fn get_external_authentication_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult\n {\n Err(errors::ConnectorError::NotImplemented(\n \"get_external_authentication_details method\".to_string(),\n )\n .into())\n }\n\n /// fn get_mandate_details\n fn get_mandate_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n Option,\n errors::ConnectorError,\n > {\n Ok(None)\n }\n\n /// fn get_network_txn_id\n fn get_network_txn_id(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n Option,\n errors::ConnectorError,\n > {\n Ok(None)\n }\n\n #[cfg(all(feature = \"revenue_recovery\", feature = \"v2\"))]\n /// get revenue recovery invoice details\n fn get_revenue_recovery_attempt_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData,\n errors::ConnectorError,\n > {\n Err(errors::ConnectorError::NotImplemented(\n \"get_revenue_recovery_attempt_details method\".to_string(),\n )\n .into())\n }\n #[cfg(all(feature = \"revenue_recovery\", feature = \"v2\"))]\n /// get revenue recovery transaction details\n fn get_revenue_recovery_invoice_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData,\n errors::ConnectorError,\n > {\n Err(errors::ConnectorError::NotImplemented(\n \"get_revenue_recovery_invoice_details method\".to_string(),\n )\n .into())\n }\n\n /// get subscription MIT payment data from webhook\n fn get_subscription_mit_payment_data(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData,\n errors::ConnectorError,\n > {\n Err(errors::ConnectorError::NotImplemented(\n \"get_subscription_mit_payment_data method\".to_string(),\n )\n .into())\n }\n}", + "after_code": "pub trait IncomingWebhook: ConnectorCommon + Sync {\n /// fn get_webhook_body_decoding_algorithm\n fn get_webhook_body_decoding_algorithm(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Box::new(crypto::NoAlgorithm))\n }\n\n /// fn get_webhook_body_decoding_message\n fn get_webhook_body_decoding_message(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(request.body.to_vec())\n }\n\n /// fn decode_webhook_body\n async fn decode_webhook_body(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_webhook_details: Option,\n connector_name: &str,\n ) -> CustomResult, errors::ConnectorError> {\n let algorithm = self.get_webhook_body_decoding_algorithm(request)?;\n\n let message = self\n .get_webhook_body_decoding_message(request)\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n let secret = self\n .get_webhook_source_verification_merchant_secret(\n merchant_id,\n connector_name,\n connector_webhook_details,\n )\n .await\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n algorithm\n .decode_message(&secret.secret, message.into())\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)\n }\n\n /// fn get_webhook_source_verification_algorithm\n fn get_webhook_source_verification_algorithm(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Box::new(crypto::NoAlgorithm))\n }\n\n /// fn get_webhook_source_verification_merchant_secret\n async fn get_webhook_source_verification_merchant_secret(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_name: &str,\n connector_webhook_details: Option,\n ) -> CustomResult {\n let debug_suffix =\n format!(\"For merchant_id: {merchant_id:?}, and connector_name: {connector_name}\");\n let default_secret = \"default_secret\".to_string();\n let merchant_secret = match connector_webhook_details {\n Some(merchant_connector_webhook_details) => {\n let connector_webhook_details = merchant_connector_webhook_details\n .parse_value::(\n \"MerchantConnectorWebhookDetails\",\n )\n .change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)\n .attach_printable_lazy(|| {\n format!(\n \"Deserializing MerchantConnectorWebhookDetails failed {debug_suffix}\",\n )\n })?;\n api_models::webhooks::ConnectorWebhookSecrets {\n secret: connector_webhook_details\n .merchant_secret\n .expose()\n .into_bytes(),\n additional_secret: connector_webhook_details.additional_secret,\n }\n }\n\n None => api_models::webhooks::ConnectorWebhookSecrets {\n secret: default_secret.into_bytes(),\n additional_secret: None,\n },\n };\n\n //need to fetch merchant secret from config table with caching in future for enhanced performance\n\n //If merchant has not set the secret for webhook source verification, \"default_secret\" is returned.\n //So it will fail during verification step and goes to psync flow.\n Ok(merchant_secret)\n }\n\n /// fn get_webhook_source_verification_signature\n fn get_webhook_source_verification_signature(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Vec::new())\n }\n\n /// fn get_webhook_source_verification_message\n fn get_webhook_source_verification_message(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _merchant_id: &common_utils::id_type::MerchantId,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Vec::new())\n }\n\n /// fn verify_webhook_source\n async fn verify_webhook_source(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_webhook_details: Option,\n _connector_account_details: crypto::Encryptable>,\n connector_name: &str,\n ) -> CustomResult {\n let algorithm = self\n .get_webhook_source_verification_algorithm(request)\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n let connector_webhook_secrets = self\n .get_webhook_source_verification_merchant_secret(\n merchant_id,\n connector_name,\n connector_webhook_details,\n )\n .await\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n let signature = self\n .get_webhook_source_verification_signature(request, &connector_webhook_secrets)\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n let message = self\n .get_webhook_source_verification_message(\n request,\n merchant_id,\n &connector_webhook_secrets,\n )\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n\n algorithm\n .verify_signature(&connector_webhook_secrets.secret, &signature, &message)\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)\n }\n\n /// fn get_webhook_object_reference_id\n fn get_webhook_object_reference_id(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult;\n\n /// fn get_status_update_object\n #[cfg(feature = \"payouts\")]\n fn get_payout_webhook_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Ok(api_models::webhooks::PayoutWebhookUpdate {\n error_code: None,\n error_message: None,\n })\n }\n\n /// fn get_webhook_event_type\n fn get_webhook_event_type(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult;\n\n /// fn get_webhook_resource_object\n fn get_webhook_resource_object(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError>;\n\n /// fn get_webhook_api_response\n fn get_webhook_api_response(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _error_kind: Option,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(ApplicationResponse::StatusOk)\n }\n\n /// fn get_dispute_details\n fn get_dispute_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_dispute_details method\".to_string()).into())\n }\n\n /// fn get_external_authentication_details\n fn get_external_authentication_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult\n {\n Err(errors::ConnectorError::NotImplemented(\n \"get_external_authentication_details method\".to_string(),\n )\n .into())\n }\n\n /// fn get_mandate_details\n fn get_mandate_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n Option,\n errors::ConnectorError,\n > {\n Ok(None)\n }\n\n /// fn get_network_txn_id\n fn get_network_txn_id(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n Option,\n errors::ConnectorError,\n > {\n Ok(None)\n }\n\n #[cfg(all(feature = \"revenue_recovery\", feature = \"v2\"))]\n /// get revenue recovery invoice details\n fn get_revenue_recovery_attempt_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData,\n errors::ConnectorError,\n > {\n Err(errors::ConnectorError::NotImplemented(\n \"get_revenue_recovery_attempt_details method\".to_string(),\n )\n .into())\n }\n #[cfg(all(feature = \"revenue_recovery\", feature = \"v2\"))]\n /// get revenue recovery transaction details\n fn get_revenue_recovery_invoice_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData,\n errors::ConnectorError,\n > {\n Err(errors::ConnectorError::NotImplemented(\n \"get_revenue_recovery_invoice_details method\".to_string(),\n )\n .into())\n }\n\n /// get subscription MIT payment data from webhook\n fn get_subscription_mit_payment_data(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult<\n hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData,\n errors::ConnectorError,\n > {\n Err(errors::ConnectorError::NotImplemented(\n \"get_subscription_mit_payment_data method\".to_string(),\n )\n .into())\n }\n}", + "diff_span": { + "before": "", + "after": " ) -> CustomResult;\n\n /// fn get_status_update_object\n #[cfg(feature = \"payouts\")]\n fn get_payout_webhook_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Ok(api_models::webhooks::PayoutWebhookUpdate {\n error_code: None,\n error_message: None,\n })\n }\n\n /// fn get_webhook_event_type\n fn get_webhook_event_type(" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/router/src/workflows/revenue_recovery.rs::function::call_decider_for_payment_processor_tokens_select_closest_time", + "file": "crates/router/src/workflows/revenue_recovery.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult {\n let mut tokens_with_schedule_time: Vec = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(state, token_with_retry_info, payment_intent)\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false));\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}", + "after_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult {\n let mut tokens_with_schedule_time: Vec = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(state, token_with_retry_info, payment_intent)\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}", + "diff_span": { + "before": " let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false));\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)", + "after": " let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/router/src/core/webhooks/incoming.rs::function::payouts_incoming_webhook_flow", + "file": "crates/router/src/core/webhooks/incoming.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": true, + "before_code": "async fn payouts_incoming_webhook_flow(\n state: SessionState,\n merchant_context: domain::MerchantContext,\n business_profile: domain::Profile,\n webhook_details: api::IncomingWebhookDetails,\n event_type: webhooks::IncomingWebhookEvent,\n source_verified: bool,\n) -> CustomResult {\n metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(1, &[]);\n if source_verified {\n let db = &*state.store;\n //find payout_attempt by object_reference_id\n let payout_attempt = match webhook_details.object_reference_id {\n webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type {\n webhooks::PayoutIdType::PayoutAttemptId(id) => db\n .find_payout_attempt_by_merchant_id_payout_attempt_id(\n merchant_context.get_merchant_account().get_id(),\n &id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout attempt\")?,\n webhooks::PayoutIdType::ConnectorPayoutId(id) => db\n .find_payout_attempt_by_merchant_id_connector_payout_id(\n merchant_context.get_merchant_account().get_id(),\n &id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout attempt\")?,\n },\n _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)\n .attach_printable(\"received a non-payout id when processing payout webhooks\")?,\n };\n\n let payouts = db\n .find_payout_by_merchant_id_payout_id(\n merchant_context.get_merchant_account().get_id(),\n &payout_attempt.payout_id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout\")?;\n\n let payout_attempt_update = PayoutAttemptUpdate::StatusUpdate {\n connector_payout_id: payout_attempt.connector_payout_id.clone(),\n status: common_enums::PayoutStatus::foreign_try_from(event_type)\n .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)\n .attach_printable(\"failed payout status mapping from event type\")?,\n error_message: None,\n error_code: None,\n is_eligible: payout_attempt.is_eligible,\n unified_code: None,\n unified_message: None,\n payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),\n };\n\n let action_req =\n payout_models::PayoutRequest::PayoutActionRequest(payout_models::PayoutActionRequest {\n payout_id: payouts.payout_id.clone(),\n });\n\n let mut payout_data = Box::pin(payouts::make_payout_data(\n &state,\n &merchant_context,\n None,\n &action_req,\n common_utils::consts::DEFAULT_LOCALE,\n ))\n .await?;\n\n let updated_payout_attempt = db\n .update_payout_attempt(\n &payout_attempt,\n payout_attempt_update,\n &payout_data.payouts,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable_lazy(|| {\n format!(\n \"Failed while updating payout attempt: payout_attempt_id: {}\",\n payout_attempt.payout_attempt_id\n )\n })?;\n payout_data.payout_attempt = updated_payout_attempt;\n\n let event_type: Option = payout_data.payout_attempt.status.into();\n\n // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook\n if let Some(outgoing_event_type) = event_type {\n let payout_create_response =\n payouts::response_handler(&state, &merchant_context, &payout_data).await?;\n\n Box::pin(super::create_event_and_trigger_outgoing_webhook(\n state,\n merchant_context,\n business_profile,\n outgoing_event_type,\n enums::EventClass::Payouts,\n payout_data\n .payout_attempt\n .payout_id\n .get_string_repr()\n .to_string(),\n enums::EventObjectType::PayoutDetails,\n api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),\n Some(payout_data.payout_attempt.created_at),\n ))\n .await?;\n }\n\n Ok(WebhookResponseTracker::Payout {\n payout_id: payout_data.payout_attempt.payout_id,\n status: payout_data.payout_attempt.status,\n })\n } else {\n metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]);\n Err(report!(\n errors::ApiErrorResponse::WebhookAuthenticationFailed\n ))\n }\n}", + "after_code": "async fn payouts_incoming_webhook_flow(\n state: SessionState,\n merchant_context: domain::MerchantContext,\n business_profile: domain::Profile,\n webhook_details: api::IncomingWebhookDetails,\n event_type: webhooks::IncomingWebhookEvent,\n source_verified: bool,\n request_details: &IncomingWebhookRequestDetails<'_>,\n connector: &ConnectorEnum,\n) -> CustomResult {\n metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(1, &[]);\n if source_verified {\n let db = &*state.store;\n //find payout_attempt by object_reference_id\n let payout_attempt = match webhook_details.object_reference_id {\n webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type {\n webhooks::PayoutIdType::PayoutAttemptId(id) => db\n .find_payout_attempt_by_merchant_id_payout_attempt_id(\n merchant_context.get_merchant_account().get_id(),\n &id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout attempt\")?,\n webhooks::PayoutIdType::ConnectorPayoutId(id) => db\n .find_payout_attempt_by_merchant_id_connector_payout_id(\n merchant_context.get_merchant_account().get_id(),\n &id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout attempt\")?,\n },\n _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)\n .attach_printable(\"received a non-payout id when processing payout webhooks\")?,\n };\n\n let payouts = db\n .find_payout_by_merchant_id_payout_id(\n merchant_context.get_merchant_account().get_id(),\n &payout_attempt.payout_id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout\")?;\n\n let status = common_enums::PayoutStatus::foreign_try_from(event_type)\n .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)\n .attach_printable(\"failed payout status mapping from event type\")?;\n\n let payout_webhook_details = connector\n .get_payout_webhook_details(request_details)\n .switch()\n .attach_printable(\"Failed to get error object for payouts\")?;\n\n // if status is failure then update the error_code and error_message as well\n let payout_attempt_update = if status.is_payout_failure() {\n PayoutAttemptUpdate::StatusUpdate {\n connector_payout_id: payout_attempt.connector_payout_id.clone(),\n status,\n error_message: payout_webhook_details.error_message,\n error_code: payout_webhook_details.error_code,\n is_eligible: payout_attempt.is_eligible,\n unified_code: None,\n unified_message: None,\n payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),\n }\n } else {\n PayoutAttemptUpdate::StatusUpdate {\n connector_payout_id: payout_attempt.connector_payout_id.clone(),\n status,\n error_message: None,\n error_code: None,\n is_eligible: payout_attempt.is_eligible,\n unified_code: None,\n unified_message: None,\n payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),\n }\n };\n\n let action_req =\n payout_models::PayoutRequest::PayoutActionRequest(payout_models::PayoutActionRequest {\n payout_id: payouts.payout_id.clone(),\n });\n\n let mut payout_data = Box::pin(payouts::make_payout_data(\n &state,\n &merchant_context,\n None,\n &action_req,\n common_utils::consts::DEFAULT_LOCALE,\n ))\n .await?;\n\n let updated_payout_attempt = db\n .update_payout_attempt(\n &payout_attempt,\n payout_attempt_update,\n &payout_data.payouts,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable_lazy(|| {\n format!(\n \"Failed while updating payout attempt: payout_attempt_id: {}\",\n payout_attempt.payout_attempt_id\n )\n })?;\n payout_data.payout_attempt = updated_payout_attempt;\n\n let event_type: Option = payout_data.payout_attempt.status.into();\n\n // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook\n if let Some(outgoing_event_type) = event_type {\n let payout_create_response =\n payouts::response_handler(&state, &merchant_context, &payout_data).await?;\n\n Box::pin(super::create_event_and_trigger_outgoing_webhook(\n state,\n merchant_context,\n business_profile,\n outgoing_event_type,\n enums::EventClass::Payouts,\n payout_data\n .payout_attempt\n .payout_id\n .get_string_repr()\n .to_string(),\n enums::EventObjectType::PayoutDetails,\n api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),\n Some(payout_data.payout_attempt.created_at),\n ))\n .await?;\n }\n\n Ok(WebhookResponseTracker::Payout {\n payout_id: payout_data.payout_attempt.payout_id,\n status: payout_data.payout_attempt.status,\n })\n } else {\n metrics::INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(1, &[]);\n Err(report!(\n errors::ApiErrorResponse::WebhookAuthenticationFailed\n ))\n }\n}", + "diff_span": { + "before": " .attach_printable(\"Failed to fetch the payout\")?;\n\n let payout_attempt_update = PayoutAttemptUpdate::StatusUpdate {\n connector_payout_id: payout_attempt.connector_payout_id.clone(),\n status: common_enums::PayoutStatus::foreign_try_from(event_type)\n .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)\n .attach_printable(\"failed payout status mapping from event type\")?,\n error_message: None,\n error_code: None,\n is_eligible: payout_attempt.is_eligible,\n unified_code: None,\n unified_message: None,\n payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),\n };\n", + "after": " event_type: webhooks::IncomingWebhookEvent,\n source_verified: bool,\n request_details: &IncomingWebhookRequestDetails<'_>,\n connector: &ConnectorEnum,\n) -> CustomResult {\n metrics::INCOMING_PAYOUT_WEBHOOK_METRIC.add(1, &[]);\n if source_verified {\n let db = &*state.store;\n //find payout_attempt by object_reference_id\n let payout_attempt = match webhook_details.object_reference_id {\n webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type {\n webhooks::PayoutIdType::PayoutAttemptId(id) => db\n .find_payout_attempt_by_merchant_id_payout_attempt_id(\n merchant_context.get_merchant_account().get_id(),\n &id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout attempt\")?,\n webhooks::PayoutIdType::ConnectorPayoutId(id) => db\n .find_payout_attempt_by_merchant_id_connector_payout_id(\n merchant_context.get_merchant_account().get_id(),\n &id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout attempt\")?,\n },\n _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)\n .attach_printable(\"received a non-payout id when processing payout webhooks\")?,\n };\n\n let payouts = db\n .find_payout_by_merchant_id_payout_id(\n merchant_context.get_merchant_account().get_id(),\n &payout_attempt.payout_id,\n merchant_context.get_merchant_account().storage_scheme,\n )\n .await\n .change_context(errors::ApiErrorResponse::WebhookResourceNotFound)\n .attach_printable(\"Failed to fetch the payout\")?;\n\n let status = common_enums::PayoutStatus::foreign_try_from(event_type)\n .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)\n .attach_printable(\"failed payout status mapping from event type\")?;\n\n let payout_webhook_details = connector\n .get_payout_webhook_details(request_details)\n .switch()\n .attach_printable(\"Failed to get error object for payouts\")?;\n\n // if status is failure then update the error_code and error_message as well\n let payout_attempt_update = if status.is_payout_failure() {\n PayoutAttemptUpdate::StatusUpdate {\n connector_payout_id: payout_attempt.connector_payout_id.clone(),\n status,\n error_message: payout_webhook_details.error_message,\n error_code: payout_webhook_details.error_code,\n is_eligible: payout_attempt.is_eligible,\n unified_code: None,\n unified_message: None,\n payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),\n }\n } else {\n PayoutAttemptUpdate::StatusUpdate {\n connector_payout_id: payout_attempt.connector_payout_id.clone(),\n status,\n error_message: None,\n error_code: None,\n is_eligible: payout_attempt.is_eligible,\n unified_code: None,\n unified_message: None,\n payout_connector_metadata: payout_attempt.payout_connector_metadata.clone(),\n }\n };\n" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6", + "before_imports": [ + "use hyperswitch_domain_models::{\n mandates::CommonMandateReference,\n payments::{payment_attempt::PaymentAttempt, HeaderPayload},\n router_request_types::VerifyWebhookSourceRequestData,\n router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},\n};", + "use common_utils::{\n errors::ReportSwitchExt,\n events::ApiEventsType,\n ext_traits::{AsyncExt, ByteSliceExt},\n types::{AmountConvertor, StringMinorUnitForConnector},\n};", + "use error_stack::{report, ResultExt};", + "use super::{types, utils, MERCHANT_ID};", + "use api_models::{\n enums::Connector,\n webhooks::{self, WebhookResponseTracker},\n};" + ], + "after_imports": [ + "use hyperswitch_domain_models::{\n mandates::CommonMandateReference,\n payments::{payment_attempt::PaymentAttempt, HeaderPayload},\n router_request_types::VerifyWebhookSourceRequestData,\n router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},\n};", + "use common_utils::{\n errors::ReportSwitchExt,\n events::ApiEventsType,\n ext_traits::{AsyncExt, ByteSliceExt},\n types::{AmountConvertor, StringMinorUnitForConnector},\n};", + "use error_stack::{report, ResultExt};", + "use hyperswitch_interfaces::webhooks::{IncomingWebhookFlowError, IncomingWebhookRequestDetails};", + "use super::{types, utils, MERCHANT_ID};", + "use api_models::{\n enums::Connector,\n webhooks::{self, WebhookResponseTracker},\n};" + ] + }, + { + "id": "crates/router/src/core/webhooks/recovery_incoming.rs::RevenueRecoveryAttempt::function::store_payment_processor_tokens_in_redis", + "file": "crates/router/src/core/webhooks/recovery_incoming.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "async fn store_payment_processor_tokens_in_redis(\n &self,\n state: &SessionState,\n recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,\n payment_connector_name: Option,\n ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n let error_code = recovery_attempt.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name\n .ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)\n .attach_printable(\"unable to derive payment connector\")?\n .to_string();\n\n let gsm_record = helpers::get_gsm_record(\n state,\n error_code.clone(),\n error_message,\n connector_name,\n REVENUE_RECOVERY.to_string(),\n )\n .await;\n\n let is_hard_decline = gsm_record\n .and_then(|record| record.error_category)\n .map(|category| category == common_enums::ErrorCategory::HardDecline)\n .unwrap_or(false);\n\n // Extract required fields from the revenue recovery attempt data\n let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone();\n\n let attempt_id = recovery_attempt.attempt_id.clone();\n let token_unit = PaymentProcessorTokenStatus {\n error_code,\n inserted_by_attempt_id: attempt_id.clone(),\n daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]),\n scheduled_at: None,\n is_hard_decline: Some(is_hard_decline),\n modified_at: Some(recovery_attempt.created_at),\n payment_processor_token_details: PaymentProcessorTokenDetails {\n payment_processor_token: revenue_recovery_attempt_data\n .processor_payment_method_token\n .clone(),\n expiry_month: revenue_recovery_attempt_data\n .card_info\n .card_exp_month\n .clone(),\n expiry_year: revenue_recovery_attempt_data\n .card_info\n .card_exp_year\n .clone(),\n card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(),\n last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),\n card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),\n card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),\n },\n is_active: Some(true), // Tokens created from recovery attempts are active by default\n account_update_history: None, // No prior account update history exists for freshly ingested tokens\n };\n\n // Make the Redis call to store tokens\n RedisTokenManager::upsert_payment_processor_token(\n state,\n &connector_customer_id,\n token_unit,\n )\n .await\n .change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed)\n .attach_printable(\"Failed to store payment processor tokens in Redis\")?;\n\n Ok(())\n }", + "after_code": "async fn store_payment_processor_tokens_in_redis(\n &self,\n state: &SessionState,\n recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,\n payment_connector_name: Option,\n ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n\n let error_code = revenue_recovery_attempt_data.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name\n .ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)\n .attach_printable(\"unable to derive payment connector\")?\n .to_string();\n\n let gsm_record = helpers::get_gsm_record(\n state,\n error_code.clone(),\n error_message,\n connector_name,\n REVENUE_RECOVERY.to_string(),\n )\n .await;\n\n let is_hard_decline = gsm_record\n .and_then(|record| record.error_category)\n .map(|category| category == common_enums::ErrorCategory::HardDecline)\n .unwrap_or(false);\n\n // Extract required fields from the revenue recovery attempt data\n let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone();\n\n let attempt_id = recovery_attempt.attempt_id.clone();\n let token_unit = PaymentProcessorTokenStatus {\n error_code,\n inserted_by_attempt_id: attempt_id.clone(),\n daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]),\n scheduled_at: None,\n is_hard_decline: Some(is_hard_decline),\n modified_at: Some(recovery_attempt.created_at),\n payment_processor_token_details: PaymentProcessorTokenDetails {\n payment_processor_token: revenue_recovery_attempt_data\n .processor_payment_method_token\n .clone(),\n expiry_month: revenue_recovery_attempt_data\n .card_info\n .card_exp_month\n .clone(),\n expiry_year: revenue_recovery_attempt_data\n .card_info\n .card_exp_year\n .clone(),\n card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(),\n last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),\n card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),\n card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),\n },\n is_active: Some(true), // Tokens created from recovery attempts are active by default\n account_update_history: None, // No prior account update history exists for freshly ingested tokens\n };\n\n // Make the Redis call to store tokens\n RedisTokenManager::upsert_payment_processor_token(\n state,\n &connector_customer_id,\n token_unit,\n )\n .await\n .change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed)\n .attach_printable(\"Failed to store payment processor tokens in Redis\")?;\n\n Ok(())\n }", + "diff_span": { + "before": " ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n let error_code = recovery_attempt.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name", + "after": " ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n\n let error_code = revenue_recovery_attempt_data.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs::impl::AdyenRefundRequest", + "file": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "kind": "impl_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "impl TryFrom<&AdyenRouterData<&RefundsRouterData>> for AdyenRefundRequest {\n type Error = Error;\n fn try_from(item: &AdyenRouterData<&RefundsRouterData>) -> Result {\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let (store, splits) = match item\n .router_data\n .request\n .split_refunds\n .as_ref()\n {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (None, None),\n };\n\n Ok(Self {\n merchant_account: auth_type.merchant_account,\n amount: Amount {\n currency: item.router_data.request.currency,\n value: item.amount,\n },\n merchant_refund_reason: item\n .router_data\n .request\n .reason\n .as_ref()\n .map(|reason| AdyenRefundRequestReason::from_str(reason))\n .transpose()?,\n reference: item.router_data.request.refund_id.clone(),\n store,\n splits,\n })\n }\n}", + "after_code": "impl TryFrom<&AdyenRouterData<&RefundsRouterData>> for AdyenRefundRequest {\n type Error = Error;\n fn try_from(item: &AdyenRouterData<&RefundsRouterData>) -> Result {\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let (store, splits) = match item\n .router_data\n .request\n .split_refunds\n .as_ref()\n {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .refund_connector_metadata\n .clone()\n .and_then(|metadata| get_store_id(metadata.expose())),\n None,\n ),\n };\n\n Ok(Self {\n merchant_account: auth_type.merchant_account,\n amount: Amount {\n currency: item.router_data.request.currency,\n value: item.amount,\n },\n merchant_refund_reason: item\n .router_data\n .request\n .reason\n .as_ref()\n .map(|reason| AdyenRefundRequestReason::from_str(reason))\n .transpose()?,\n reference: item.router_data.request.refund_id.clone(),\n store,\n splits,\n })\n }\n}", + "diff_span": { + "before": " {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (None, None),\n };\n", + "after": " {\n Some(hyperswitch_domain_models::router_request_types::SplitRefundsRequest::AdyenSplitRefund(adyen_split_data)) => get_adyen_split_request(adyen_split_data, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .refund_connector_metadata\n .clone()\n .and_then(|metadata| get_store_id(metadata.expose())),\n None,\n ),\n };\n" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs::struct::AdyenplatformIncomingWebhookData", + "file": "crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs", + "kind": "struct_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub struct AdyenplatformIncomingWebhookData {\n pub status: AdyenplatformWebhookStatus,\n pub reference: String,\n pub tracking: Option,\n pub category: Option,\n}", + "after_code": "pub struct AdyenplatformIncomingWebhookData {\n pub status: AdyenplatformWebhookStatus,\n pub reference: String,\n pub tracking: Option,\n pub reason: Option,\n pub category: Option,\n}", + "diff_span": { + "before": "", + "after": " pub reference: String,\n pub tracking: Option,\n pub reason: Option,\n pub category: Option,\n}" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/router/src/core/webhooks/recovery_incoming.rs::impl::RevenueRecoveryAttempt", + "file": "crates/router/src/core/webhooks/recovery_incoming.rs", + "kind": "impl_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "impl RevenueRecoveryAttempt {\n pub async fn load_recovery_attempt_from_api(\n data: api_models::payments::RecoveryPaymentsCreate,\n state: &SessionState,\n req_state: &ReqState,\n merchant_context: &domain::MerchantContext,\n profile: &domain::Profile,\n payment_intent: revenue_recovery::RecoveryPaymentIntent,\n payment_merchant_connector_account: domain::MerchantConnectorAccount,\n ) -> CustomResult<\n (\n revenue_recovery::RecoveryPaymentAttempt,\n revenue_recovery::RecoveryPaymentIntent,\n ),\n errors::RevenueRecoveryError,\n > {\n let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from(\n &data,\n ));\n recovery_attempt\n .get_payment_attempt(state, req_state, merchant_context, profile, &payment_intent)\n .await\n .transpose()\n .async_unwrap_or_else(|| async {\n recovery_attempt\n .record_payment_attempt(\n state,\n req_state,\n merchant_context,\n profile,\n &payment_intent,\n &data.billing_merchant_connector_id,\n Some(payment_merchant_connector_account),\n )\n .await\n })\n .await\n }\n\n fn get_recovery_invoice_transaction_details(\n connector_enum: &connector_integration_interface::ConnectorEnum,\n request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,\n billing_connector_payment_details: Option<\n &revenue_recovery_response::BillingConnectorPaymentsSyncResponse,\n >,\n billing_connector_invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,\n ) -> CustomResult {\n billing_connector_payment_details.map_or_else(\n || {\n interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details(\n connector_enum,\n request_details,\n )\n .change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)\n .attach_printable(\n \"Failed to get recovery attempt details from the billing connector\",\n )\n .map(RevenueRecoveryAttempt)\n },\n |data| {\n Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from((\n data,\n billing_connector_invoice_details,\n ))))\n },\n )\n }\n pub fn get_revenue_recovery_attempt(\n payment_intent: &domain_payments::PaymentIntent,\n revenue_recovery_metadata: &api_payments::PaymentRevenueRecoveryMetadata,\n billing_connector_account: &domain::MerchantConnectorAccount,\n card_info: api_payments::AdditionalCardInfo,\n payment_processor_token: &str,\n ) -> CustomResult {\n let revenue_recovery_data = payment_intent\n .create_revenue_recovery_attempt_data(\n revenue_recovery_metadata.clone(),\n billing_connector_account,\n card_info,\n payment_processor_token,\n )\n .change_context(errors::RevenueRecoveryError::RevenueRecoveryAttemptDataCreateFailed)\n .attach_printable(\"Failed to build recovery attempt data\")?;\n Ok(Self(revenue_recovery_data))\n }\n async fn get_payment_attempt(\n &self,\n state: &SessionState,\n req_state: &ReqState,\n merchant_context: &domain::MerchantContext,\n profile: &domain::Profile,\n payment_intent: &revenue_recovery::RecoveryPaymentIntent,\n ) -> CustomResult<\n Option<(\n revenue_recovery::RecoveryPaymentAttempt,\n revenue_recovery::RecoveryPaymentIntent,\n )>,\n errors::RevenueRecoveryError,\n > {\n let attempt_response =\n Box::pin(payments::payments_list_attempts_using_payment_intent_id::<\n payments::operations::PaymentGetListAttempts,\n api_payments::PaymentAttemptListResponse,\n _,\n payments::operations::payment_attempt_list::PaymentGetListAttempts,\n hyperswitch_domain_models::payments::PaymentAttemptListData<\n payments::operations::PaymentGetListAttempts,\n >,\n >(\n state.clone(),\n req_state.clone(),\n merchant_context.clone(),\n profile.clone(),\n payments::operations::PaymentGetListAttempts,\n api_payments::PaymentAttemptListRequest {\n payment_intent_id: payment_intent.payment_id.clone(),\n },\n payment_intent.payment_id.clone(),\n hyperswitch_domain_models::payments::HeaderPayload::default(),\n ))\n .await;\n let response = match attempt_response {\n Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {\n let final_attempt = self\n .0\n .charge_id\n .as_ref()\n .map(|charge_id| {\n payments_response\n .find_attempt_in_attempts_list_using_charge_id(charge_id.clone())\n })\n .unwrap_or_else(|| {\n self.0\n .connector_transaction_id\n .as_ref()\n .and_then(|transaction_id| {\n payments_response\n .find_attempt_in_attempts_list_using_connector_transaction_id(\n transaction_id,\n )\n })\n });\n let payment_attempt =\n final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt {\n attempt_id: res.id.to_owned(),\n attempt_status: res.status.to_owned(),\n feature_metadata: res.feature_metadata.to_owned(),\n amount: res.amount.net_amount,\n network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available\n network_decline_code: res\n .error\n .clone()\n .and_then(|e| e.network_decline_code), // Placeholder, to be populated if available\n error_code: res.error.clone().map(|error| error.code),\n created_at: res.created_at,\n });\n // If we have an attempt, combine it with payment_intent in a tuple.\n let res_with_payment_intent_and_attempt =\n payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));\n Ok(res_with_payment_intent_and_attempt)\n }\n Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"Unexpected response from payment intent core\"),\n error @ Err(_) => {\n logger::error!(?error);\n Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"failed to fetch payment attempt in recovery webhook flow\")\n }\n }?;\n Ok(response)\n }\n\n #[allow(clippy::too_many_arguments)]\n async fn record_payment_attempt(\n &self,\n state: &SessionState,\n req_state: &ReqState,\n merchant_context: &domain::MerchantContext,\n profile: &domain::Profile,\n payment_intent: &revenue_recovery::RecoveryPaymentIntent,\n billing_connector_account_id: &id_type::MerchantConnectorAccountId,\n payment_connector_account: Option,\n ) -> CustomResult<\n (\n revenue_recovery::RecoveryPaymentAttempt,\n revenue_recovery::RecoveryPaymentIntent,\n ),\n errors::RevenueRecoveryError,\n > {\n let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone());\n let payment_connector_name = payment_connector_account\n .as_ref()\n .map(|account| account.connector_name);\n let request_payload: api_payments::PaymentsAttemptRecordRequest = self\n .create_payment_record_request(\n state,\n billing_connector_account_id,\n payment_connector_id,\n payment_connector_name,\n common_enums::TriggeredBy::External,\n )\n .await?;\n let attempt_response = Box::pin(payments::record_attempt_core(\n state.clone(),\n req_state.clone(),\n merchant_context.clone(),\n profile.clone(),\n request_payload,\n payment_intent.payment_id.clone(),\n hyperswitch_domain_models::payments::HeaderPayload::default(),\n ))\n .await;\n\n let (recovery_attempt, updated_recovery_intent) = match attempt_response {\n Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {\n Ok((\n revenue_recovery::RecoveryPaymentAttempt {\n attempt_id: attempt_response.id.clone(),\n attempt_status: attempt_response.status,\n feature_metadata: attempt_response.payment_attempt_feature_metadata,\n amount: attempt_response.amount,\n network_advice_code: attempt_response\n .error_details\n .clone()\n .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available\n network_decline_code: attempt_response\n .error_details\n .clone()\n .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available\n error_code: attempt_response\n .error_details\n .clone()\n .map(|error| error.code),\n created_at: attempt_response.created_at,\n },\n revenue_recovery::RecoveryPaymentIntent {\n payment_id: payment_intent.payment_id.clone(),\n status: attempt_response.status.into(), // Using status from attempt_response\n feature_metadata: attempt_response.payment_intent_feature_metadata, // Using feature_metadata from attempt_response\n merchant_id: payment_intent.merchant_id.clone(),\n merchant_reference_id: payment_intent.merchant_reference_id.clone(),\n invoice_amount: payment_intent.invoice_amount,\n invoice_currency: payment_intent.invoice_currency,\n created_at: payment_intent.created_at,\n billing_address: payment_intent.billing_address.clone(),\n },\n ))\n }\n Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"Unexpected response from record attempt core\"),\n error @ Err(_) => {\n logger::error!(?error);\n Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"failed to record attempt in recovery webhook flow\")\n }\n }?;\n\n let response = (recovery_attempt, updated_recovery_intent);\n\n self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name)\n .await\n .map_err(|e| {\n router_env::logger::error!(\n \"Failed to store payment processor tokens in Redis: {:?}\",\n e\n );\n errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed\n })?;\n\n Ok(response)\n }\n\n pub async fn create_payment_record_request(\n &self,\n state: &SessionState,\n billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId,\n payment_merchant_connector_account_id: Option,\n payment_connector: Option,\n triggered_by: common_enums::TriggeredBy,\n ) -> CustomResult\n {\n let revenue_recovery_attempt_data = &self.0;\n let amount_details =\n api_payments::PaymentAttemptAmountDetails::from(revenue_recovery_attempt_data);\n let feature_metadata = api_payments::PaymentAttemptFeatureMetadata {\n revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData {\n // Since we are recording the external paymenmt attempt, this is hardcoded to External\n attempt_triggered_by: triggered_by,\n charge_id: self.0.charge_id.clone(),\n }),\n };\n\n let card_info = revenue_recovery_attempt_data\n .card_info\n .card_isin\n .clone()\n .async_and_then(|isin| async move {\n let issuer_identifier_number = isin.clone();\n state\n .store\n .get_card_info(issuer_identifier_number.as_str())\n .await\n .map_err(|error| services::logger::warn!(card_info_error=?error))\n .ok()\n })\n .await\n .flatten();\n let payment_method_data = api_models::payments::RecordAttemptPaymentMethodDataRequest {\n payment_method_data: api_models::payments::AdditionalPaymentData::Card(Box::new(\n revenue_recovery_attempt_data.card_info.clone(),\n )),\n billing: None,\n };\n\n let card_issuer = revenue_recovery_attempt_data.card_info.card_issuer.clone();\n\n let error =\n Option::::from(revenue_recovery_attempt_data);\n Ok(api_payments::PaymentsAttemptRecordRequest {\n amount_details,\n status: revenue_recovery_attempt_data.status,\n billing: None,\n shipping: None,\n connector: payment_connector,\n payment_merchant_connector_id: payment_merchant_connector_account_id,\n error,\n description: None,\n connector_transaction_id: revenue_recovery_attempt_data\n .connector_transaction_id\n .clone(),\n payment_method_type: revenue_recovery_attempt_data.payment_method_type,\n billing_connector_id: billing_merchant_connector_account_id.clone(),\n payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type,\n payment_method_data: Some(payment_method_data),\n metadata: None,\n feature_metadata: Some(feature_metadata),\n transaction_created_at: revenue_recovery_attempt_data.transaction_created_at,\n processor_payment_method_token: revenue_recovery_attempt_data\n .processor_payment_method_token\n .clone(),\n connector_customer_id: revenue_recovery_attempt_data.connector_customer_id.clone(),\n retry_count: revenue_recovery_attempt_data.retry_count,\n invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time,\n invoice_billing_started_at_time: revenue_recovery_attempt_data\n .invoice_billing_started_at_time,\n triggered_by,\n card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),\n card_issuer,\n })\n }\n\n pub async fn find_payment_merchant_connector_account(\n &self,\n state: &SessionState,\n key_store: &domain::MerchantKeyStore,\n billing_connector_account: &domain::MerchantConnectorAccount,\n ) -> CustomResult, errors::RevenueRecoveryError> {\n let payment_merchant_connector_account_id = billing_connector_account\n .get_payment_merchant_connector_account_id_using_account_reference_id(\n self.0.connector_account_reference_id.clone(),\n );\n let db = &*state.store;\n let key_manager_state = &(state).into();\n let payment_merchant_connector_account = payment_merchant_connector_account_id\n .as_ref()\n .async_map(|mca_id| async move {\n db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store)\n .await\n })\n .await\n .transpose()\n .change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)\n .attach_printable(\n \"failed to fetch payment merchant connector id using account reference id\",\n )?;\n Ok(payment_merchant_connector_account)\n }\n\n #[allow(clippy::too_many_arguments)]\n async fn get_recovery_payment_attempt(\n is_recovery_transaction_event: bool,\n billing_connector_account: &domain::MerchantConnectorAccount,\n state: &SessionState,\n connector_enum: &connector_integration_interface::ConnectorEnum,\n req_state: &ReqState,\n billing_connector_payment_details: Option<\n &revenue_recovery_response::BillingConnectorPaymentsSyncResponse,\n >,\n request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,\n merchant_context: &domain::MerchantContext,\n business_profile: &domain::Profile,\n payment_intent: &revenue_recovery::RecoveryPaymentIntent,\n invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,\n ) -> CustomResult<\n (\n Option,\n revenue_recovery::RecoveryPaymentIntent,\n ),\n errors::RevenueRecoveryError,\n > {\n let payment_attempt_with_recovery_intent = match is_recovery_transaction_event {\n true => {\n let invoice_transaction_details = Self::get_recovery_invoice_transaction_details(\n connector_enum,\n request_details,\n billing_connector_payment_details,\n invoice_details,\n )?;\n\n // Find the payment merchant connector ID at the top level to avoid multiple DB calls.\n let payment_merchant_connector_account = invoice_transaction_details\n .find_payment_merchant_connector_account(\n state,\n merchant_context.get_merchant_key_store(),\n billing_connector_account,\n )\n .await?;\n\n let (payment_attempt, updated_payment_intent) = invoice_transaction_details\n .get_payment_attempt(\n state,\n req_state,\n merchant_context,\n business_profile,\n payment_intent,\n )\n .await\n .transpose()\n .async_unwrap_or_else(|| async {\n invoice_transaction_details\n .record_payment_attempt(\n state,\n req_state,\n merchant_context,\n business_profile,\n payment_intent,\n &billing_connector_account.get_id(),\n payment_merchant_connector_account,\n )\n .await\n })\n .await?;\n (Some(payment_attempt), updated_payment_intent)\n }\n\n false => (None, payment_intent.clone()),\n };\n\n Ok(payment_attempt_with_recovery_intent)\n }\n\n /// Store payment processor tokens in Redis for retry management\n async fn store_payment_processor_tokens_in_redis(\n &self,\n state: &SessionState,\n recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,\n payment_connector_name: Option,\n ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n let error_code = recovery_attempt.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name\n .ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)\n .attach_printable(\"unable to derive payment connector\")?\n .to_string();\n\n let gsm_record = helpers::get_gsm_record(\n state,\n error_code.clone(),\n error_message,\n connector_name,\n REVENUE_RECOVERY.to_string(),\n )\n .await;\n\n let is_hard_decline = gsm_record\n .and_then(|record| record.error_category)\n .map(|category| category == common_enums::ErrorCategory::HardDecline)\n .unwrap_or(false);\n\n // Extract required fields from the revenue recovery attempt data\n let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone();\n\n let attempt_id = recovery_attempt.attempt_id.clone();\n let token_unit = PaymentProcessorTokenStatus {\n error_code,\n inserted_by_attempt_id: attempt_id.clone(),\n daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]),\n scheduled_at: None,\n is_hard_decline: Some(is_hard_decline),\n modified_at: Some(recovery_attempt.created_at),\n payment_processor_token_details: PaymentProcessorTokenDetails {\n payment_processor_token: revenue_recovery_attempt_data\n .processor_payment_method_token\n .clone(),\n expiry_month: revenue_recovery_attempt_data\n .card_info\n .card_exp_month\n .clone(),\n expiry_year: revenue_recovery_attempt_data\n .card_info\n .card_exp_year\n .clone(),\n card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(),\n last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),\n card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),\n card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),\n },\n is_active: Some(true), // Tokens created from recovery attempts are active by default\n account_update_history: None, // No prior account update history exists for freshly ingested tokens\n };\n\n // Make the Redis call to store tokens\n RedisTokenManager::upsert_payment_processor_token(\n state,\n &connector_customer_id,\n token_unit,\n )\n .await\n .change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed)\n .attach_printable(\"Failed to store payment processor tokens in Redis\")?;\n\n Ok(())\n }\n}", + "after_code": "impl RevenueRecoveryAttempt {\n pub async fn load_recovery_attempt_from_api(\n data: api_models::payments::RecoveryPaymentsCreate,\n state: &SessionState,\n req_state: &ReqState,\n merchant_context: &domain::MerchantContext,\n profile: &domain::Profile,\n payment_intent: revenue_recovery::RecoveryPaymentIntent,\n payment_merchant_connector_account: domain::MerchantConnectorAccount,\n ) -> CustomResult<\n (\n revenue_recovery::RecoveryPaymentAttempt,\n revenue_recovery::RecoveryPaymentIntent,\n ),\n errors::RevenueRecoveryError,\n > {\n let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from(\n &data,\n ));\n recovery_attempt\n .get_payment_attempt(state, req_state, merchant_context, profile, &payment_intent)\n .await\n .transpose()\n .async_unwrap_or_else(|| async {\n recovery_attempt\n .record_payment_attempt(\n state,\n req_state,\n merchant_context,\n profile,\n &payment_intent,\n &data.billing_merchant_connector_id,\n Some(payment_merchant_connector_account),\n )\n .await\n })\n .await\n }\n\n fn get_recovery_invoice_transaction_details(\n connector_enum: &connector_integration_interface::ConnectorEnum,\n request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,\n billing_connector_payment_details: Option<\n &revenue_recovery_response::BillingConnectorPaymentsSyncResponse,\n >,\n billing_connector_invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,\n ) -> CustomResult {\n billing_connector_payment_details.map_or_else(\n || {\n interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details(\n connector_enum,\n request_details,\n )\n .change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)\n .attach_printable(\n \"Failed to get recovery attempt details from the billing connector\",\n )\n .map(RevenueRecoveryAttempt)\n },\n |data| {\n Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from((\n data,\n billing_connector_invoice_details,\n ))))\n },\n )\n }\n pub fn get_revenue_recovery_attempt(\n payment_intent: &domain_payments::PaymentIntent,\n revenue_recovery_metadata: &api_payments::PaymentRevenueRecoveryMetadata,\n billing_connector_account: &domain::MerchantConnectorAccount,\n card_info: api_payments::AdditionalCardInfo,\n payment_processor_token: &str,\n ) -> CustomResult {\n let revenue_recovery_data = payment_intent\n .create_revenue_recovery_attempt_data(\n revenue_recovery_metadata.clone(),\n billing_connector_account,\n card_info,\n payment_processor_token,\n )\n .change_context(errors::RevenueRecoveryError::RevenueRecoveryAttemptDataCreateFailed)\n .attach_printable(\"Failed to build recovery attempt data\")?;\n Ok(Self(revenue_recovery_data))\n }\n async fn get_payment_attempt(\n &self,\n state: &SessionState,\n req_state: &ReqState,\n merchant_context: &domain::MerchantContext,\n profile: &domain::Profile,\n payment_intent: &revenue_recovery::RecoveryPaymentIntent,\n ) -> CustomResult<\n Option<(\n revenue_recovery::RecoveryPaymentAttempt,\n revenue_recovery::RecoveryPaymentIntent,\n )>,\n errors::RevenueRecoveryError,\n > {\n let attempt_response =\n Box::pin(payments::payments_list_attempts_using_payment_intent_id::<\n payments::operations::PaymentGetListAttempts,\n api_payments::PaymentAttemptListResponse,\n _,\n payments::operations::payment_attempt_list::PaymentGetListAttempts,\n hyperswitch_domain_models::payments::PaymentAttemptListData<\n payments::operations::PaymentGetListAttempts,\n >,\n >(\n state.clone(),\n req_state.clone(),\n merchant_context.clone(),\n profile.clone(),\n payments::operations::PaymentGetListAttempts,\n api_payments::PaymentAttemptListRequest {\n payment_intent_id: payment_intent.payment_id.clone(),\n },\n payment_intent.payment_id.clone(),\n hyperswitch_domain_models::payments::HeaderPayload::default(),\n ))\n .await;\n let response = match attempt_response {\n Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {\n let final_attempt = self\n .0\n .charge_id\n .as_ref()\n .map(|charge_id| {\n payments_response\n .find_attempt_in_attempts_list_using_charge_id(charge_id.clone())\n })\n .unwrap_or_else(|| {\n self.0\n .connector_transaction_id\n .as_ref()\n .and_then(|transaction_id| {\n payments_response\n .find_attempt_in_attempts_list_using_connector_transaction_id(\n transaction_id,\n )\n })\n });\n let payment_attempt =\n final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt {\n attempt_id: res.id.to_owned(),\n attempt_status: res.status.to_owned(),\n feature_metadata: res.feature_metadata.to_owned(),\n amount: res.amount.net_amount,\n network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available\n network_decline_code: res\n .error\n .clone()\n .and_then(|e| e.network_decline_code), // Placeholder, to be populated if available\n error_code: res.error.clone().map(|error| error.code),\n created_at: res.created_at,\n });\n // If we have an attempt, combine it with payment_intent in a tuple.\n let res_with_payment_intent_and_attempt =\n payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));\n Ok(res_with_payment_intent_and_attempt)\n }\n Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"Unexpected response from payment intent core\"),\n error @ Err(_) => {\n logger::error!(?error);\n Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"failed to fetch payment attempt in recovery webhook flow\")\n }\n }?;\n Ok(response)\n }\n\n #[allow(clippy::too_many_arguments)]\n async fn record_payment_attempt(\n &self,\n state: &SessionState,\n req_state: &ReqState,\n merchant_context: &domain::MerchantContext,\n profile: &domain::Profile,\n payment_intent: &revenue_recovery::RecoveryPaymentIntent,\n billing_connector_account_id: &id_type::MerchantConnectorAccountId,\n payment_connector_account: Option,\n ) -> CustomResult<\n (\n revenue_recovery::RecoveryPaymentAttempt,\n revenue_recovery::RecoveryPaymentIntent,\n ),\n errors::RevenueRecoveryError,\n > {\n let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone());\n let payment_connector_name = payment_connector_account\n .as_ref()\n .map(|account| account.connector_name);\n let request_payload: api_payments::PaymentsAttemptRecordRequest = self\n .create_payment_record_request(\n state,\n billing_connector_account_id,\n payment_connector_id,\n payment_connector_name,\n common_enums::TriggeredBy::External,\n )\n .await?;\n let attempt_response = Box::pin(payments::record_attempt_core(\n state.clone(),\n req_state.clone(),\n merchant_context.clone(),\n profile.clone(),\n request_payload,\n payment_intent.payment_id.clone(),\n hyperswitch_domain_models::payments::HeaderPayload::default(),\n ))\n .await;\n\n let (recovery_attempt, updated_recovery_intent) = match attempt_response {\n Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {\n Ok((\n revenue_recovery::RecoveryPaymentAttempt {\n attempt_id: attempt_response.id.clone(),\n attempt_status: attempt_response.status,\n feature_metadata: attempt_response.payment_attempt_feature_metadata,\n amount: attempt_response.amount,\n network_advice_code: attempt_response\n .error_details\n .clone()\n .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available\n network_decline_code: attempt_response\n .error_details\n .clone()\n .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available\n error_code: attempt_response\n .error_details\n .clone()\n .map(|error| error.code),\n created_at: attempt_response.created_at,\n },\n revenue_recovery::RecoveryPaymentIntent {\n payment_id: payment_intent.payment_id.clone(),\n status: attempt_response.status.into(), // Using status from attempt_response\n feature_metadata: attempt_response.payment_intent_feature_metadata, // Using feature_metadata from attempt_response\n merchant_id: payment_intent.merchant_id.clone(),\n merchant_reference_id: payment_intent.merchant_reference_id.clone(),\n invoice_amount: payment_intent.invoice_amount,\n invoice_currency: payment_intent.invoice_currency,\n created_at: payment_intent.created_at,\n billing_address: payment_intent.billing_address.clone(),\n },\n ))\n }\n Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"Unexpected response from record attempt core\"),\n error @ Err(_) => {\n logger::error!(?error);\n Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)\n .attach_printable(\"failed to record attempt in recovery webhook flow\")\n }\n }?;\n\n let response = (recovery_attempt, updated_recovery_intent);\n\n self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name)\n .await\n .map_err(|e| {\n router_env::logger::error!(\n \"Failed to store payment processor tokens in Redis: {:?}\",\n e\n );\n errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed\n })?;\n\n Ok(response)\n }\n\n pub async fn create_payment_record_request(\n &self,\n state: &SessionState,\n billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId,\n payment_merchant_connector_account_id: Option,\n payment_connector: Option,\n triggered_by: common_enums::TriggeredBy,\n ) -> CustomResult\n {\n let revenue_recovery_attempt_data = &self.0;\n let amount_details =\n api_payments::PaymentAttemptAmountDetails::from(revenue_recovery_attempt_data);\n let feature_metadata = api_payments::PaymentAttemptFeatureMetadata {\n revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData {\n // Since we are recording the external paymenmt attempt, this is hardcoded to External\n attempt_triggered_by: triggered_by,\n charge_id: self.0.charge_id.clone(),\n }),\n };\n\n let card_info = revenue_recovery_attempt_data\n .card_info\n .card_isin\n .clone()\n .async_and_then(|isin| async move {\n let issuer_identifier_number = isin.clone();\n state\n .store\n .get_card_info(issuer_identifier_number.as_str())\n .await\n .map_err(|error| services::logger::warn!(card_info_error=?error))\n .ok()\n })\n .await\n .flatten();\n let payment_method_data = api_models::payments::RecordAttemptPaymentMethodDataRequest {\n payment_method_data: api_models::payments::AdditionalPaymentData::Card(Box::new(\n revenue_recovery_attempt_data.card_info.clone(),\n )),\n billing: None,\n };\n\n let card_issuer = revenue_recovery_attempt_data.card_info.card_issuer.clone();\n\n let error =\n Option::::from(revenue_recovery_attempt_data);\n Ok(api_payments::PaymentsAttemptRecordRequest {\n amount_details,\n status: revenue_recovery_attempt_data.status,\n billing: None,\n shipping: None,\n connector: payment_connector,\n payment_merchant_connector_id: payment_merchant_connector_account_id,\n error,\n description: None,\n connector_transaction_id: revenue_recovery_attempt_data\n .connector_transaction_id\n .clone(),\n payment_method_type: revenue_recovery_attempt_data.payment_method_type,\n billing_connector_id: billing_merchant_connector_account_id.clone(),\n payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type,\n payment_method_data: Some(payment_method_data),\n metadata: None,\n feature_metadata: Some(feature_metadata),\n transaction_created_at: revenue_recovery_attempt_data.transaction_created_at,\n processor_payment_method_token: revenue_recovery_attempt_data\n .processor_payment_method_token\n .clone(),\n connector_customer_id: revenue_recovery_attempt_data.connector_customer_id.clone(),\n retry_count: revenue_recovery_attempt_data.retry_count,\n invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time,\n invoice_billing_started_at_time: revenue_recovery_attempt_data\n .invoice_billing_started_at_time,\n triggered_by,\n card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),\n card_issuer,\n })\n }\n\n pub async fn find_payment_merchant_connector_account(\n &self,\n state: &SessionState,\n key_store: &domain::MerchantKeyStore,\n billing_connector_account: &domain::MerchantConnectorAccount,\n ) -> CustomResult, errors::RevenueRecoveryError> {\n let payment_merchant_connector_account_id = billing_connector_account\n .get_payment_merchant_connector_account_id_using_account_reference_id(\n self.0.connector_account_reference_id.clone(),\n );\n let db = &*state.store;\n let key_manager_state = &(state).into();\n let payment_merchant_connector_account = payment_merchant_connector_account_id\n .as_ref()\n .async_map(|mca_id| async move {\n db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store)\n .await\n })\n .await\n .transpose()\n .change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)\n .attach_printable(\n \"failed to fetch payment merchant connector id using account reference id\",\n )?;\n Ok(payment_merchant_connector_account)\n }\n\n #[allow(clippy::too_many_arguments)]\n async fn get_recovery_payment_attempt(\n is_recovery_transaction_event: bool,\n billing_connector_account: &domain::MerchantConnectorAccount,\n state: &SessionState,\n connector_enum: &connector_integration_interface::ConnectorEnum,\n req_state: &ReqState,\n billing_connector_payment_details: Option<\n &revenue_recovery_response::BillingConnectorPaymentsSyncResponse,\n >,\n request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,\n merchant_context: &domain::MerchantContext,\n business_profile: &domain::Profile,\n payment_intent: &revenue_recovery::RecoveryPaymentIntent,\n invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData,\n ) -> CustomResult<\n (\n Option,\n revenue_recovery::RecoveryPaymentIntent,\n ),\n errors::RevenueRecoveryError,\n > {\n let payment_attempt_with_recovery_intent = match is_recovery_transaction_event {\n true => {\n let invoice_transaction_details = Self::get_recovery_invoice_transaction_details(\n connector_enum,\n request_details,\n billing_connector_payment_details,\n invoice_details,\n )?;\n\n // Find the payment merchant connector ID at the top level to avoid multiple DB calls.\n let payment_merchant_connector_account = invoice_transaction_details\n .find_payment_merchant_connector_account(\n state,\n merchant_context.get_merchant_key_store(),\n billing_connector_account,\n )\n .await?;\n\n let (payment_attempt, updated_payment_intent) = invoice_transaction_details\n .get_payment_attempt(\n state,\n req_state,\n merchant_context,\n business_profile,\n payment_intent,\n )\n .await\n .transpose()\n .async_unwrap_or_else(|| async {\n invoice_transaction_details\n .record_payment_attempt(\n state,\n req_state,\n merchant_context,\n business_profile,\n payment_intent,\n &billing_connector_account.get_id(),\n payment_merchant_connector_account,\n )\n .await\n })\n .await?;\n (Some(payment_attempt), updated_payment_intent)\n }\n\n false => (None, payment_intent.clone()),\n };\n\n Ok(payment_attempt_with_recovery_intent)\n }\n\n /// Store payment processor tokens in Redis for retry management\n async fn store_payment_processor_tokens_in_redis(\n &self,\n state: &SessionState,\n recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,\n payment_connector_name: Option,\n ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n\n let error_code = revenue_recovery_attempt_data.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name\n .ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)\n .attach_printable(\"unable to derive payment connector\")?\n .to_string();\n\n let gsm_record = helpers::get_gsm_record(\n state,\n error_code.clone(),\n error_message,\n connector_name,\n REVENUE_RECOVERY.to_string(),\n )\n .await;\n\n let is_hard_decline = gsm_record\n .and_then(|record| record.error_category)\n .map(|category| category == common_enums::ErrorCategory::HardDecline)\n .unwrap_or(false);\n\n // Extract required fields from the revenue recovery attempt data\n let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone();\n\n let attempt_id = recovery_attempt.attempt_id.clone();\n let token_unit = PaymentProcessorTokenStatus {\n error_code,\n inserted_by_attempt_id: attempt_id.clone(),\n daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]),\n scheduled_at: None,\n is_hard_decline: Some(is_hard_decline),\n modified_at: Some(recovery_attempt.created_at),\n payment_processor_token_details: PaymentProcessorTokenDetails {\n payment_processor_token: revenue_recovery_attempt_data\n .processor_payment_method_token\n .clone(),\n expiry_month: revenue_recovery_attempt_data\n .card_info\n .card_exp_month\n .clone(),\n expiry_year: revenue_recovery_attempt_data\n .card_info\n .card_exp_year\n .clone(),\n card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(),\n last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),\n card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),\n card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),\n },\n is_active: Some(true), // Tokens created from recovery attempts are active by default\n account_update_history: None, // No prior account update history exists for freshly ingested tokens\n };\n\n // Make the Redis call to store tokens\n RedisTokenManager::upsert_payment_processor_token(\n state,\n &connector_customer_id,\n token_unit,\n )\n .await\n .change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed)\n .attach_printable(\"Failed to store payment processor tokens in Redis\")?;\n\n Ok(())\n }\n}", + "diff_span": { + "before": " ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n let error_code = recovery_attempt.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name", + "after": " ) -> CustomResult<(), errors::RevenueRecoveryError> {\n let revenue_recovery_attempt_data = &self.0;\n\n let error_code = revenue_recovery_attempt_data.error_code.clone();\n let error_message = revenue_recovery_attempt_data.error_message.clone();\n let connector_name = payment_connector_name" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::RedisTokenManager::function::upsert_payment_processor_token", + "file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let modified_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n (existing_token.modified_at < modified_at).then(|| {\n existing_token.modified_at = modified_at;\n error_code.map(|err| existing_token.error_code = Some(err));\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }", + "after_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }", + "diff_span": { + "before": " let error_code = token_data.error_code.clone();\n\n let modified_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n (existing_token.modified_at < modified_at).then(|| {\n existing_token.modified_at = modified_at;\n error_code.map(|err| existing_token.error_code = Some(err));\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {", + "after": " let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs::struct::AdyenPaymentRequest", + "file": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "kind": "struct_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub struct AdyenPaymentRequest<'a> {\n amount: Amount,\n merchant_account: Secret,\n payment_method: PaymentMethod<'a>,\n mpi_data: Option,\n reference: String,\n return_url: String,\n browser_info: Option,\n shopper_interaction: AdyenShopperInteraction,\n recurring_processing_model: Option,\n additional_data: Option,\n shopper_reference: Option,\n store_payment_method: Option,\n shopper_name: Option,\n #[serde(rename = \"shopperIP\")]\n shopper_ip: Option>,\n shopper_locale: Option,\n shopper_email: Option,\n shopper_statement: Option,\n social_security_number: Option>,\n telephone_number: Option>,\n billing_address: Option
,\n delivery_address: Option
,\n country_code: Option,\n line_items: Option>,\n channel: Option,\n merchant_order_reference: Option,\n splits: Option>,\n store: Option,\n device_fingerprint: Option>,\n #[serde(with = \"common_utils::custom_serde::iso8601::option\")]\n session_validity: Option,\n metadata: Option,\n}", + "after_code": "pub struct AdyenPaymentRequest<'a> {\n amount: Amount,\n merchant_account: Secret,\n payment_method: PaymentMethod<'a>,\n mpi_data: Option,\n reference: String,\n return_url: String,\n browser_info: Option,\n shopper_interaction: AdyenShopperInteraction,\n recurring_processing_model: Option,\n additional_data: Option,\n shopper_reference: Option,\n store_payment_method: Option,\n shopper_name: Option,\n #[serde(rename = \"shopperIP\")]\n shopper_ip: Option>,\n shopper_locale: Option,\n shopper_email: Option,\n shopper_statement: Option,\n social_security_number: Option>,\n telephone_number: Option>,\n billing_address: Option
,\n delivery_address: Option
,\n country_code: Option,\n line_items: Option>,\n channel: Option,\n merchant_order_reference: Option,\n splits: Option>,\n /// metadata.store\n store: Option,\n device_fingerprint: Option>,\n #[serde(with = \"common_utils::custom_serde::iso8601::option\")]\n session_validity: Option,\n metadata: Option,\n}", + "diff_span": { + "before": "", + "after": " merchant_order_reference: Option,\n splits: Option>,\n /// metadata.store\n store: Option,\n device_fingerprint: Option>," + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs::AdyenPaymentRequest<'_>::function::try_from", + "file": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "fn try_from(\n value: (\n &AdyenRouterData<&PaymentsAuthorizeRouterData>,\n &NetworkTokenData,\n ),\n ) -> Result {\n let (item, token_data) = value;\n let amount = get_amount_data(item);\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let shopper_interaction = AdyenShopperInteraction::from(item.router_data);\n let shopper_reference = build_shopper_reference(item.router_data);\n let (recurring_processing_model, store_payment_method, _) =\n get_recurring_processing_model(item.router_data)?;\n let browser_info = get_browser_info(item.router_data)?;\n let billing_address =\n get_address_info(item.router_data.get_optional_billing()).transpose()?;\n let country_code = get_country_code(item.router_data.get_optional_billing());\n let additional_data = get_additional_data(item.router_data);\n let return_url = item.router_data.request.get_router_return_url()?;\n let testing_data = item\n .router_data\n .request\n .get_connector_testing_data()\n .map(AdyenTestingData::try_from)\n .transpose()?;\n let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name);\n let card_holder_name =\n test_holder_name.or(item.router_data.get_optional_billing_full_name());\n let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new(\n AdyenPaymentMethod::try_from((token_data, card_holder_name))?,\n ));\n\n let shopper_email = item.router_data.request.email.clone();\n let shopper_name = get_shopper_name(item.router_data.get_optional_billing());\n let mpi_data = AdyenMpiData {\n directory_response: \"Y\".to_string(),\n authentication_response: \"Y\".to_string(),\n cavv: None,\n token_authentication_verification_value: Some(\n token_data.get_cryptogram().clone().unwrap_or_default(),\n ),\n eci: Some(\"02\".to_string()),\n };\n let (store, splits) = match item.router_data.request.split_payments.as_ref() {\n Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(\n adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (None, None),\n };\n let device_fingerprint = item\n .router_data\n .request\n .metadata\n .clone()\n .and_then(get_device_fingerprint);\n\n let delivery_address =\n get_address_info(item.router_data.get_optional_shipping()).and_then(Result::ok);\n let telephone_number = item.router_data.get_optional_billing_phone_number();\n\n Ok(AdyenPaymentRequest {\n amount,\n merchant_account: auth_type.merchant_account,\n payment_method,\n reference: item.router_data.connector_request_reference_id.clone(),\n return_url,\n shopper_interaction,\n recurring_processing_model,\n browser_info,\n additional_data,\n telephone_number,\n shopper_name,\n shopper_email,\n shopper_locale: item.router_data.request.locale.clone(),\n social_security_number: None,\n billing_address,\n delivery_address,\n country_code,\n line_items: None,\n shopper_reference,\n store_payment_method,\n channel: None,\n shopper_statement: item.router_data.request.statement_descriptor.clone(),\n shopper_ip: item.router_data.request.get_ip_address_as_optional(),\n merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(),\n mpi_data: Some(mpi_data),\n store,\n splits,\n device_fingerprint,\n session_validity: None,\n metadata: item.router_data.request.metadata.clone(),\n })\n }", + "after_code": "fn try_from(\n value: (\n &AdyenRouterData<&PaymentsAuthorizeRouterData>,\n &NetworkTokenData,\n ),\n ) -> Result {\n let (item, token_data) = value;\n let amount = get_amount_data(item);\n let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;\n let shopper_interaction = AdyenShopperInteraction::from(item.router_data);\n let shopper_reference = build_shopper_reference(item.router_data);\n let (recurring_processing_model, store_payment_method, _) =\n get_recurring_processing_model(item.router_data)?;\n let browser_info = get_browser_info(item.router_data)?;\n let billing_address =\n get_address_info(item.router_data.get_optional_billing()).transpose()?;\n let country_code = get_country_code(item.router_data.get_optional_billing());\n let additional_data = get_additional_data(item.router_data);\n let return_url = item.router_data.request.get_router_return_url()?;\n let testing_data = item\n .router_data\n .request\n .get_connector_testing_data()\n .map(AdyenTestingData::try_from)\n .transpose()?;\n let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name);\n let card_holder_name =\n test_holder_name.or(item.router_data.get_optional_billing_full_name());\n let payment_method = PaymentMethod::AdyenPaymentMethod(Box::new(\n AdyenPaymentMethod::try_from((token_data, card_holder_name))?,\n ));\n\n let shopper_email = item.router_data.request.email.clone();\n let shopper_name = get_shopper_name(item.router_data.get_optional_billing());\n let mpi_data = AdyenMpiData {\n directory_response: \"Y\".to_string(),\n authentication_response: \"Y\".to_string(),\n cavv: None,\n token_authentication_verification_value: Some(\n token_data.get_cryptogram().clone().unwrap_or_default(),\n ),\n eci: Some(\"02\".to_string()),\n };\n let (store, splits) = match item.router_data.request.split_payments.as_ref() {\n Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(\n adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .metadata\n .clone()\n .and_then(get_store_id),\n None,\n ),\n };\n let device_fingerprint = item\n .router_data\n .request\n .metadata\n .clone()\n .and_then(get_device_fingerprint);\n\n let delivery_address =\n get_address_info(item.router_data.get_optional_shipping()).and_then(Result::ok);\n let telephone_number = item.router_data.get_optional_billing_phone_number();\n\n Ok(AdyenPaymentRequest {\n amount,\n merchant_account: auth_type.merchant_account,\n payment_method,\n reference: item.router_data.connector_request_reference_id.clone(),\n return_url,\n shopper_interaction,\n recurring_processing_model,\n browser_info,\n additional_data,\n telephone_number,\n shopper_name,\n shopper_email,\n shopper_locale: item.router_data.request.locale.clone(),\n social_security_number: None,\n billing_address,\n delivery_address,\n country_code,\n line_items: None,\n shopper_reference,\n store_payment_method,\n channel: None,\n shopper_statement: item.router_data.request.statement_descriptor.clone(),\n shopper_ip: item.router_data.request.get_ip_address_as_optional(),\n merchant_order_reference: item.router_data.request.merchant_order_reference_id.clone(),\n mpi_data: Some(mpi_data),\n store,\n splits,\n device_fingerprint,\n session_validity: None,\n metadata: item.router_data.request.metadata.clone(),\n })\n }", + "diff_span": { + "before": " adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (None, None),\n };\n let device_fingerprint = item", + "after": " adyen_split_payment,\n )) => get_adyen_split_request(adyen_split_payment, item.router_data.request.currency),\n _ => (\n item.router_data\n .request\n .metadata\n .clone()\n .and_then(get_store_id),\n None,\n ),\n };\n let device_fingerprint = item" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/router/src/core/revenue_recovery.rs::function::perform_execute_payment", + "file": "crates/router/src/core/revenue_recovery.rs", + "kind": "function_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub async fn perform_execute_payment(\n state: &SessionState,\n execute_task_process: &storage::ProcessTracker,\n profile: &domain::Profile,\n merchant_context: domain::MerchantContext,\n tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,\n revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,\n payment_intent: &PaymentIntent,\n) -> Result<(), sch_errors::ProcessTrackerError> {\n let db = &*state.store;\n\n let mut revenue_recovery_metadata = payment_intent\n .feature_metadata\n .as_ref()\n .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())\n .get_required_value(\"Payment Revenue Recovery Metadata\")?\n .convert_back();\n\n let decision = types::Decision::get_decision_based_on_params(\n state,\n payment_intent.status,\n revenue_recovery_metadata\n .payment_connector_transmission\n .unwrap_or_default(),\n payment_intent.active_attempt_id.clone(),\n revenue_recovery_payment_data,\n &tracking_data.global_payment_id,\n )\n .await?;\n\n // TODO decide if its a global failure or is it requeueable error\n match decision {\n types::Decision::Execute => {\n let connector_customer_id = revenue_recovery_metadata.get_connector_customer_id();\n\n let last_token_used = payment_intent\n .feature_metadata\n .as_ref()\n .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())\n .map(|rr| {\n rr.billing_connector_payment_details\n .payment_processor_token\n .clone()\n });\n\n let processor_token = storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(\n state,\n &connector_customer_id,\n tracking_data.revenue_recovery_retry,\n last_token_used.as_deref(),\n )\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"Failed to fetch token details from redis\".to_string(),\n })?;\n\n match processor_token {\n None => {\n logger::info!(\"No Token fetched from redis\");\n\n // Close the job if there is no token available\n db.as_scheduler()\n .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE,\n )\n .await?;\n\n Box::pin(reopen_calculate_workflow_on_payment_failure(\n state,\n execute_task_process,\n profile,\n merchant_context,\n payment_intent,\n revenue_recovery_payment_data,\n &tracking_data.payment_attempt_id,\n ))\n .await?;\n\n storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(state, &connector_customer_id).await?;\n }\n\n Some(payment_processor_token) => {\n logger::info!(\"Token fetched from redis success\");\n\n record_internal_attempt_and_execute_payment(\n state,\n execute_task_process,\n profile,\n merchant_context,\n tracking_data,\n revenue_recovery_payment_data,\n payment_intent,\n &payment_processor_token,\n &mut revenue_recovery_metadata,\n )\n .await?;\n }\n };\n }\n\n types::Decision::Psync(attempt_status, attempt_id) => {\n // find if a psync task is already present\n let task = PSYNC_WORKFLOW;\n let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;\n let process_tracker_id = attempt_id.get_psync_revenue_recovery_id(task, runner);\n let psync_process = db.find_process_by_id(&process_tracker_id).await?;\n\n match psync_process {\n Some(_) => {\n let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus =\n attempt_status.foreign_into();\n\n pcr_status\n .update_pt_status_based_on_attempt_status_for_execute_payment(\n db,\n execute_task_process,\n )\n .await?;\n }\n\n None => {\n // insert new psync task\n insert_psync_pcr_task_to_pt(\n revenue_recovery_payment_data.billing_mca.get_id().clone(),\n db,\n revenue_recovery_payment_data\n .merchant_account\n .get_id()\n .clone(),\n payment_intent.get_id().clone(),\n revenue_recovery_payment_data.profile.get_id().clone(),\n attempt_id.clone(),\n storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,\n tracking_data.revenue_recovery_retry,\n )\n .await?;\n\n // finish the current task\n db.as_scheduler()\n .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,\n )\n .await?;\n }\n };\n }\n types::Decision::ReviewForSuccessfulPayment => {\n // Finish the current task since the payment was a success\n // And mark it as review as it might have happened through the external system\n db.finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,\n )\n .await?;\n }\n types::Decision::ReviewForFailedPayment(triggered_by) => {\n match triggered_by {\n enums::TriggeredBy::Internal => {\n // requeue the current tasks to update the fields for rescheduling a payment\n let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {\n status: enums::ProcessTrackerStatus::Pending,\n business_status: Some(String::from(\n business_status::EXECUTE_WORKFLOW_REQUEUE,\n )),\n };\n db.as_scheduler()\n .update_process(execute_task_process.clone(), pt_update)\n .await?;\n }\n enums::TriggeredBy::External => {\n logger::debug!(\"Failed Payment Attempt Triggered By External\");\n // Finish the current task since the payment was a failure by an external source\n db.as_scheduler()\n .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,\n )\n .await?;\n }\n };\n }\n types::Decision::InvalidDecision => {\n db.finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE,\n )\n .await?;\n logger::warn!(\"Abnormal State Identified\")\n }\n }\n\n Ok(())\n}", + "after_code": "pub async fn perform_execute_payment(\n state: &SessionState,\n execute_task_process: &storage::ProcessTracker,\n profile: &domain::Profile,\n merchant_context: domain::MerchantContext,\n tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,\n revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,\n payment_intent: &PaymentIntent,\n) -> Result<(), sch_errors::ProcessTrackerError> {\n let db = &*state.store;\n\n let mut revenue_recovery_metadata = payment_intent\n .feature_metadata\n .as_ref()\n .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())\n .get_required_value(\"Payment Revenue Recovery Metadata\")?\n .convert_back();\n\n let decision = types::Decision::get_decision_based_on_params(\n state,\n payment_intent.status,\n revenue_recovery_metadata\n .payment_connector_transmission\n .unwrap_or_default(),\n payment_intent.active_attempt_id.clone(),\n revenue_recovery_payment_data,\n &tracking_data.global_payment_id,\n )\n .await?;\n\n // TODO decide if its a global failure or is it requeueable error\n match decision {\n types::Decision::Execute => {\n let connector_customer_id = revenue_recovery_metadata.get_connector_customer_id();\n\n let last_token_used = payment_intent\n .feature_metadata\n .as_ref()\n .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())\n .map(|rr| {\n rr.billing_connector_payment_details\n .payment_processor_token\n .clone()\n });\n\n let processor_token = storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(\n state,\n &connector_customer_id,\n tracking_data.revenue_recovery_retry,\n last_token_used.as_deref(),\n )\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"Failed to fetch token details from redis\".to_string(),\n })?;\n\n match processor_token {\n None => {\n logger::info!(\"No Token fetched from redis\");\n\n // Close the job if there is no token available\n db.as_scheduler()\n .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_FAILURE,\n )\n .await?;\n\n Box::pin(reopen_calculate_workflow_on_payment_failure(\n state,\n execute_task_process,\n profile,\n merchant_context,\n payment_intent,\n revenue_recovery_payment_data,\n &tracking_data.payment_attempt_id,\n ))\n .await?;\n\n storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(state, &connector_customer_id).await?;\n }\n\n Some(payment_processor_token) => {\n logger::info!(\"Token fetched from redis success\");\n\n record_internal_attempt_and_execute_payment(\n state,\n execute_task_process,\n profile,\n merchant_context,\n tracking_data,\n revenue_recovery_payment_data,\n payment_intent,\n &payment_processor_token,\n &mut revenue_recovery_metadata,\n )\n .await?;\n }\n };\n }\n\n types::Decision::Psync(attempt_status, attempt_id) => {\n // find if a psync task is already present\n let task = PSYNC_WORKFLOW;\n let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;\n let process_tracker_id = attempt_id.get_psync_revenue_recovery_id(task, runner);\n let psync_process = db.find_process_by_id(&process_tracker_id).await?;\n\n match psync_process {\n Some(_) => {\n let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus =\n attempt_status.foreign_into();\n\n pcr_status\n .update_pt_status_based_on_attempt_status_for_execute_payment(\n db,\n execute_task_process,\n )\n .await?;\n }\n\n None => {\n // insert new psync task\n insert_psync_pcr_task_to_pt(\n revenue_recovery_payment_data.billing_mca.get_id().clone(),\n db,\n revenue_recovery_payment_data\n .merchant_account\n .get_id()\n .clone(),\n payment_intent.get_id().clone(),\n revenue_recovery_payment_data.profile.get_id().clone(),\n attempt_id.clone(),\n storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,\n tracking_data.revenue_recovery_retry,\n )\n .await?;\n\n // finish the current task\n db.as_scheduler()\n .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,\n )\n .await?;\n }\n };\n }\n types::Decision::ReviewForSuccessfulPayment => {\n // Finish the current task since the payment was a success\n // And mark it as review as it might have happened through the external system\n db.finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,\n )\n .await?;\n }\n types::Decision::ReviewForFailedPayment(triggered_by) => {\n match triggered_by {\n enums::TriggeredBy::Internal => {\n // requeue the current tasks to update the fields for rescheduling a payment\n let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {\n status: enums::ProcessTrackerStatus::Pending,\n business_status: Some(String::from(\n business_status::EXECUTE_WORKFLOW_REQUEUE,\n )),\n };\n db.as_scheduler()\n .update_process(execute_task_process.clone(), pt_update)\n .await?;\n }\n enums::TriggeredBy::External => {\n logger::debug!(\"Failed Payment Attempt Triggered By External\");\n // Finish the current task since the payment was a failure by an external source\n db.as_scheduler()\n .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,\n )\n .await?;\n }\n };\n }\n types::Decision::InvalidDecision => {\n db.finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE,\n )\n .await?;\n logger::warn!(\"Abnormal State Identified\")\n }\n }\n\n Ok(())\n}", + "diff_span": { + "before": " .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_COMPLETE,\n )\n .await?;", + "after": " .finish_process_with_business_status(\n execute_task_process.clone(),\n business_status::EXECUTE_WORKFLOW_FAILURE,\n )\n .await?;" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs::struct::AdyenRefundRequest", + "file": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "kind": "struct_item", + "status": "modified", + "code_changed": true, + "imports_changed": false, + "before_code": "pub struct AdyenRefundRequest {\n merchant_account: Secret,\n amount: Amount,\n merchant_refund_reason: Option,\n reference: String,\n splits: Option>,\n store: Option,\n}", + "after_code": "pub struct AdyenRefundRequest {\n merchant_account: Secret,\n amount: Amount,\n merchant_refund_reason: Option,\n reference: String,\n splits: Option>,\n /// refund_connector_metadata.store\n store: Option,\n}", + "diff_span": { + "before": "", + "after": " reference: String,\n splits: Option>,\n /// refund_connector_metadata.store\n store: Option,\n}" + }, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/common_enums/src/enums.rs::PayoutStatus::function::is_payout_failure", + "file": "crates/common_enums/src/enums.rs", + "kind": "function_item", + "status": "added", + "before_code": null, + "after_code": "pub fn is_payout_failure(&self) -> bool {\n matches!(\n self,\n Self::Failed | Self::Cancelled | Self::Expired | Self::Ineligible\n )\n }", + "diff_span": null, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs::function::get_store_id", + "file": "crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs", + "kind": "function_item", + "status": "added", + "before_code": null, + "after_code": "fn get_store_id(metadata: serde_json::Value) -> Option {\n metadata\n .get(\"store\")\n .and_then(|store| store.as_str())\n .map(|store| store.to_string())\n}", + "diff_span": null, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_interfaces/src/webhooks.rs::IncomingWebhook::function::get_payout_webhook_details", + "file": "crates/hyperswitch_interfaces/src/webhooks.rs", + "kind": "function_item", + "status": "added", + "before_code": null, + "after_code": "fn get_payout_webhook_details(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Ok(api_models::webhooks::PayoutWebhookUpdate {\n error_code: None,\n error_message: None,\n })\n }", + "diff_span": null, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/common_enums/src/enums.rs::impl::PayoutStatus", + "file": "crates/common_enums/src/enums.rs", + "kind": "impl_item", + "status": "added", + "before_code": null, + "after_code": "impl PayoutStatus {\n pub fn is_payout_failure(&self) -> bool {\n matches!(\n self,\n Self::Failed | Self::Cancelled | Self::Expired | Self::Ineligible\n )\n }\n}", + "diff_span": null, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_connectors/src/connectors/adyenplatform.rs::Adyenplatform::function::get_payout_webhook_details", + "file": "crates/hyperswitch_connectors/src/connectors/adyenplatform.rs", + "kind": "function_item", + "status": "added", + "before_code": null, + "after_code": "fn get_payout_webhook_details(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request\n .body\n .parse_struct(\"AdyenplatformIncomingWebhook\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n\n let error_reason = webhook_body.data.reason.or(webhook_body\n .data\n .tracking\n .and_then(|tracking_data| tracking_data.reason));\n\n Ok(api_models::webhooks::PayoutWebhookUpdate {\n error_message: error_reason.clone(),\n error_code: error_reason,\n })\n }", + "diff_span": null, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/api_models/src/webhooks.rs::struct::PayoutWebhookUpdate", + "file": "crates/api_models/src/webhooks.rs", + "kind": "struct_item", + "status": "added", + "before_code": null, + "after_code": "pub struct PayoutWebhookUpdate {\n pub error_message: Option,\n pub error_code: Option,\n}", + "diff_span": null, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + }, + { + "id": "crates/hyperswitch_interfaces/src/connector_integration_interface.rs::ConnectorEnum::function::get_payout_webhook_details", + "file": "crates/hyperswitch_interfaces/src/connector_integration_interface.rs", + "kind": "function_item", + "status": "added", + "before_code": null, + "after_code": "fn get_payout_webhook_details(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n match self {\n Self::Old(connector) => connector.get_payout_webhook_details(request),\n Self::New(connector) => connector.get_payout_webhook_details(request),\n }\n }", + "diff_span": null, + "commit_sha": "6dbfc73f14f3d968ceaa38cb789fe042d2eae3f6" + } + ] +} \ No newline at end of file