Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(routing): Decision Engine cut-over routing entry and per-card SSO handoff (#13452)

Prajjwal Kumar4dd76de472c9
diff --git a/config/config.example.toml b/config/config.example.toml
index 0bac2f0b20..b9e6c8c417 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1421,6 +1421,7 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" # List
dynamic_routing_enabled = true # Enable or disable Open Router for dynamic routing
static_routing_enabled = true # Enable or disable Open Router for static routing
url = "http://localhost:8080" # Open Router URL
+dashboard_url = "http://localhost:5173" # Decision Engine dashboard (browser) URL for merchant SSO redirect
[grpc_client.unified_connector_service]
base_url = "http://localhost:8000" # Unified Connector Service Base URL
diff --git a/config/development.toml b/config/development.toml
index 480ac49500..01ed424d03 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -1557,6 +1557,7 @@ connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"
dynamic_routing_enabled = false
static_routing_enabled = false
url = "http://localhost:8080"
+dashboard_url = "http://localhost:5173"
[l2_l3_data_config]
enabled = "true"
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index b1129f96af..9b014a773a 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -4,8 +4,8 @@ use crate::routing::{
ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper,
CreateDynamicRoutingWrapper, DynamicRoutingUpdateConfigQuery, EliminationRoutingPayloadWrapper,
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
- RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
- RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
+ RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingEntryResponse,
+ RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit,
RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, RuleMigrationError, RuleMigrationQuery,
RuleMigrationResponse, RuleMigrationResult, SuccessBasedRoutingConfig,
@@ -19,6 +19,12 @@ impl ApiEventMetric for RoutingKind {
}
}
+impl ApiEventMetric for RoutingEntryResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
impl ApiEventMetric for MerchantRoutingAlgorithm {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 7b353dd76a..2fbcc18b3a 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -2153,3 +2153,42 @@ pub enum ComparisonType {
GreaterThan,
GreaterThanEqual,
}
+
+/// Which Decision Engine routing page a cut-over profile's dashboard card should deep-link to.
+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum DecisionEngineRoutingTarget {
+ Volume,
+ Rule,
+ MultiObjective,
+ Debit,
+}
+
+impl DecisionEngineRoutingTarget {
+ const VOLUME_PATH: &'static str = "routing/volume";
+ const RULE_PATH: &'static str = "routing/rules";
+ const MULTI_OBJECTIVE_PATH: &'static str = "routing/sr";
+ const DEBIT_PATH: &'static str = "routing/debit";
+
+ pub fn dashboard_path(self) -> &'static str {
+ match self {
+ Self::Volume => Self::VOLUME_PATH,
+ Self::Rule => Self::RULE_PATH,
+ Self::MultiObjective => Self::MULTI_OBJECTIVE_PATH,
+ Self::Debit => Self::DEBIT_PATH,
+ }
+ }
+}
+
+/// Routing entry query params; `target` selects the DE page to deep-link for a cut-over profile.
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct RoutingEntryRequest {
+ pub target: Option<DecisionEngineRoutingTarget>,
+}
+
+/// Routing entry response: `is_cutover` for the source, `redirect_url` for a per-`target` DE deep-link.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct RoutingEntryResponse {
+ pub is_cutover: bool,
+ pub redirect_url: Option<String>,
+}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 1d2da25a07..1fec74ff9a 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -400,6 +400,9 @@ pub struct OpenRouter {
pub dynamic_routing_enabled: bool,
pub static_routing_enabled: bool,
pub url: String,
+ /// Browser-facing Decision Engine dashboard base URL, used for the merchant SSO redirect.
+ #[serde(default)]
+ pub dashboard_url: String,
}
#[derive(Debug, Deserialize, Clone, Default)]
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 695cb00ee9..7b5f684f32 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -1492,8 +1492,8 @@ impl RoutingStage for HybridRoutingStage {
let (dynamic_routing_request, _dynamic_routing_volume_split) =
self.build_dynamic_routing_request(&input);
- let should_include_static_request = input.state.conf.open_router.static_routing_enabled
- && input.static_approach == common_enums::RoutingApproach::RuleBasedRouting;
+ // Under DE cutover, always evaluate the profile's rule on DE; the caller falls back to HS static/default on empty or error.
+ let should_include_static_request = input.state.conf.open_router.static_routing_enabled;
let payment_id = input
.payment_dsl_input
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 82eb82ffda..4aa331caa4 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -70,6 +70,71 @@ use crate::{
utils::{self, OptionExt},
};
+/// Dashboard routing entry: reports the profile's routing source and, for a cut-over profile with a `target`, returns a one-time DE dashboard deep-link.
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn routing_entry(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ target: Option<routing_types::DecisionEngineRoutingTarget>,
+) -> RouterResponse<routing_types::RoutingEntryResponse> {
+ let profile_id = profile_id.get_required_value("profile_id")?;
+
+ let dimensions = dimension_state::Dimensions::new()
+ .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())
+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())
+ .with_profile_id(profile_id.clone());
+
+ let routing_source = get_routing_result_source(&state, &dimensions).await;
+ let is_cutover = matches!(
+ routing_source,
+ routing_types::RoutingResultSource::DecisionEngine
+ );
+
+ // Mint a fresh one-time code only when a card was clicked (`target`) on a cut-over profile.
+ let redirect_url = match (is_cutover, target) {
+ (true, Some(target)) => {
+ let code = match helpers::mint_decision_engine_sso_code(&state, &profile_id).await {
+ Ok(code) => code,
+ // Provision the DE merchant only when it does not exist yet (DE returns 404), then retry once.
+ Err(err)
+ if matches!(
+ err.current_context(),
+ errors::RoutingError::RoutingEventsError {
+ status_code: 404,
+ ..
+ }
+ ) =>
+ {
+ let _ = helpers::create_decision_engine_merchant(&state, &profile_id).await;
+ helpers::mint_decision_engine_sso_code(&state, &profile_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ }
+ Err(err) => {
+ return Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to mint Decision Engine SSO code");
+ }
+ };
+ Some(format!(
+ "{}/{}?code={}",
+ state.conf.open_router.dashboard_url,
+ target.dashboard_path(),
+ code
+ ))
+ }
+ _ => None,
+ };
+
+ Ok(service_api::ApplicationResponse::Json(
+ routing_types::RoutingEntryResponse {
+ is_cutover,
+ redirect_url,
+ },
+ ))
+}
+
pub enum TransactionData<'a> {
Payment(PaymentsDslInput<'a>),
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index d27cdfbdea..8942b24dae 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -79,6 +79,7 @@ pub const DECISION_ENGINE_RULE_GET_ENDPOINT: &str = "rule/get";
pub const DECISION_ENGINE_RULE_DELETE_ENDPOINT: &str = "rule/delete";
pub const DECISION_ENGINE_MERCHANT_BASE_ENDPOINT: &str = "merchant-account";
pub const DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT: &str = "merchant-account/create";
+pub const DECISION_ENGINE_MERCHANT_TOKEN_ENDPOINT: &str = "auth/admin/merchant-token";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
@@ -2733,6 +2734,47 @@ pub async fn create_decision_engine_merchant(
Ok(())
}
+#[cfg(feature = "v1")]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct DecisionEngineMerchantTokenResponse {
+ pub code: String,
+}
+
+/// Mint a one-time SSO handoff code from the Decision Engine for the profile (keyed on profile_id).
+#[cfg(feature = "v1")]
+#[instrument(skip_all)]
+pub async fn mint_decision_engine_sso_code(
+ state: &SessionState,
+ profile_id: &id_type::ProfileId,
+) -> error_stack::Result<String, errors::RoutingError> {
+ let merchant_token_req = open_router::MerchantAccount {
+ merchant_id: profile_id.get_string_repr().to_string(),
+ gateway_success_rate_based_decider_input: None,
+ };
+
+ let response: Option<DecisionEngineMerchantTokenResponse> =
+ routing_utils::ConfigApiClient::send_decision_engine_request(
+ state,
+ services::Method::Post,
+ DECISION_ENGINE_MERCHANT_TOKEN_ENDPOINT,
+ Some(merchant_token_req),
+ None,
+ None,
+ )
+ .await
+ .attach_printable("Failed to mint SSO code on decision engine")?
+ .response;
+
+ let code = response
+ .ok_or(errors::RoutingError::OpenRouterError(
+ "Decision engine returned an empty SSO code response".to_string(),
+ ))
+ .attach_printable("Decision engine returned an empty SSO code response")?
+ .code;
+
+ Ok(code)
+}
+
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
#[instrument(skip_all)]
pub async fn delete_decision_engine_merchant(
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index d01ddb6fd4..a97f1b1c93 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1132,6 +1132,7 @@ impl Routing {
#[allow(unused_mut)]
let mut route = web::scope("/routing")
.app_data(web::Data::new(state.clone()))
+ .service(web::resource("/entry").route(web::post().to(routing::routing_entry)))
.service(
web::resource("/active").route(web::get().to(|state, req, query_params| {
routing::routing_retrieve_linked_config(state, req, query_params, None)
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 660b7e0967..38e720e526 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -73,6 +73,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::RoutingLinkConfig
| Flow::RoutingUnlinkConfig
| Flow::RoutingRetrieveConfig
+ | Flow::DecisionEngineSsoRedirect
| Flow::RoutingRetrieveActiveConfig
| Flow::RoutingRetrieveDefaultConfig
| Flow::RoutingRetrieveDictionary
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 66d531b746..bac12a9875 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -31,6 +31,43 @@ use crate::{
services::{api as oss_api, authentication as auth, authorization::permissions::Permission},
types::domain,
};
+
+/// Dashboard routing entry: returns the profile's routing source and, with `?target`, a DE deep-link.
+#[cfg(all(feature = "olap", feature = "v1"))]
+#[instrument(skip_all)]
+pub async fn routing_entry(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<routing_types::RoutingEntryRequest>,
+) -> impl Responder {
+ let flow = Flow::DecisionEngineSsoRedirect;
+ let target = query.into_inner().target;
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ move |state, auth: auth::AuthenticationData, _, _| {
+ let platform = auth.platform;
+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());
+ routing::routing_entry(state, platform, profile_id, target)
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: true,
+ allow_platform_self_operation: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::ProfileRoutingRead,
+ allow_connected: true,
+ allow_platform: false,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all)]
pub async fn routing_create_config(
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 50502966c7..bce3be7eb1 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -275,6 +275,8 @@ pub enum Flow {
RoutingUnlinkConfig,
/// Routing retrieve config
RoutingRetrieveConfig,
+ /// Decision engine merchant SSO redirect
+ DecisionEngineSsoRedirect,
/// Routing retrieve active config
RoutingRetrieveActiveConfig,
/// Routing retrieve default config