Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(payouts): add payout sync workflow to process tracker (#11342)
Sakil Mostakcc5d8683d6c3
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 12b157f879..e2d2f7bd59 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -8532,7 +8532,11 @@ impl PayoutStatus {}pub fn is_non_terminal_status(&self) -> bool {- !matches!(+ !self.is_terminal_status()+ }++ pub fn is_terminal_status(&self) -> bool {+ matches!(self,Self::Success | Self::Failed | Self::Cancelled | Self::Expired | Self::Reversed)@@ -10273,6 +10277,7 @@ pub enum ProcessTrackerRunner {ProcessDisputeWorkflow,DisputeListWorkflow,InvoiceSyncflow,+ PayoutSyncWorkFlow,}#[derive(diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rsindex a442a338c6..57332532fd 100644--- a/crates/router/src/bin/scheduler.rs+++ b/crates/router/src/bin/scheduler.rs@@ -333,6 +333,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))}+ storage::ProcessTrackerRunner::PayoutSyncWorkFlow => {+ Ok(Box::new(workflows::payout_sync::PayoutSyncWorkFlow))+ }}};diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 50316bb1fc..f1e4ea0388 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -354,6 +354,8 @@ pub mod superposition {pub const REQUIRES_CVV: &str = "requires_cvv";/// implicit customer update configuration keypub const IMPLICIT_CUSTOMER_UPDATE: &str = "implicit_customer_update";+ /// payout sync tracker configuration key+ pub const PAYOUT_TRACKER_MAPPING: &str = "payout_tracker_mapping";}#[cfg(test)]diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex e2c322da24..df15ad367f 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -1,10 +1,15 @@use external_services::superposition;+use scheduler::consumer::types::process_data::RetryMapping;use super::{dimension_state::{DimensionsWithMerchantId, DimensionsWithMerchantIdAndProfileId},fetch_db_config_for_dimensions, DatabaseBackedConfig,};-use crate::{consts::superposition as superposition_consts, db::StorageInterface, utils::id_type};+use crate::{+ consts::superposition as superposition_consts,+ core::configs::dimension_state::DimensionsWithMerchantIdAndConnector, db::StorageInterface,+ utils::id_type,+};/// Macro to generate config struct and superposition::Config trait implementation./// Note: Manually implement `DatabaseBackedConfig` for the config struct:@@ -151,3 +156,12 @@ impl DatabaseBackedConfig for ImplicitCustomerUpdate {Some(format!("{}_{}", merchant_id, Self::KEY))}}++config! {+ superposition_key = PAYOUT_TRACKER_MAPPING,+ output = RetryMapping,+ default = RetryMapping::default(),+ object = true,+ requires = DimensionsWithMerchantIdAndConnector,+ targeting_key = id_type::PayoutId+}diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex cafdfb3e7d..9adc8ba902 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -47,6 +47,7 @@ use crate::types::domain::behaviour::Conversion;use crate::types::PayoutActionData;use crate::{core::{+ configs::{self as configs, dimension_state::DimensionsWithMerchantId},errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt,},@@ -64,6 +65,7 @@ use crate::{transformers::{ForeignFrom, ForeignTryFrom},},utils::{self, OptionExt},+ workflows::payout_sync,};// ********************************************** TYPES **********************************************@@ -173,6 +175,7 @@ pub async fn make_connector_decision(platform: &domain::Platform,connector_call_type: api::ConnectorCallType,payout_data: &mut PayoutData,+ dimensions: DimensionsWithMerchantId,) -> RouterResult<()> {match connector_call_type {api::ConnectorCallType::PreDetermined(routing_data) => {@@ -181,6 +184,7 @@ pub async fn make_connector_decision(platform,&routing_data.connector_data,payout_data,+ &dimensions,)).await?;@@ -199,6 +203,7 @@ pub async fn make_connector_decision(routing_data.connector_data,payout_data,platform,+ &dimensions,)).await?;}@@ -216,6 +221,7 @@ pub async fn make_connector_decision(platform,&connector_data,payout_data,+ &dimensions,)).await?;@@ -235,6 +241,7 @@ pub async fn make_connector_decision(connector_data.clone(),payout_data,platform,+ &dimensions,)).await?;}@@ -252,6 +259,7 @@ pub async fn make_connector_decision(connector_data,payout_data,platform,+ &dimensions,)).await?;}@@ -273,6 +281,7 @@ pub async fn payouts_core(payout_data: &mut PayoutData,routing_algorithm: Option<serde_json::Value>,eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,+ dimensions: DimensionsWithMerchantId,) -> RouterResult<()> {let payout_attempt = &payout_data.payout_attempt;@@ -293,6 +302,7 @@ pub async fn payouts_core(platform,connector_call_type,payout_data,+ dimensions,)).await}@@ -305,6 +315,7 @@ pub async fn payouts_core(payout_data: &mut PayoutData,routing_algorithm: Option<serde_json::Value>,eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,+ dimensions: DimensionsWithMerchantId,) -> RouterResult<()> {todo!()}@@ -318,6 +329,8 @@ pub async fn payouts_create_core(// Validate create requestlet (payout_id, payout_method_data, profile_id, customer, payment_method) =validator::validate_create_request(&state, &platform, &req).await?;+ let dimensions = configs::dimension_state::Dimensions::new()+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());// Create DB entrieslet mut payout_data = payout_create_db_entries(@@ -364,6 +377,7 @@ pub async fn payouts_create_core(&mut payout_data,req.routing.clone(),req.connector.clone(),+ dimensions,).await?};@@ -377,6 +391,9 @@ pub async fn payouts_confirm_core(platform: domain::Platform,req: payouts::PayoutCreateRequest,) -> RouterResponse<payouts::PayoutCreateResponse> {+ let dimensions = configs::dimension_state::Dimensions::new()+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());+let mut payout_data = Box::pin(make_payout_data(&state,&platform,@@ -427,6 +444,7 @@ pub async fn payouts_confirm_core(&mut payout_data,req.routing.clone(),req.connector.clone(),+ dimensions,).await?;@@ -438,6 +456,9 @@ pub async fn payouts_update_core(platform: domain::Platform,req: payouts::PayoutCreateRequest,) -> RouterResponse<payouts::PayoutCreateResponse> {+ let dimensions = configs::dimension_state::Dimensions::new()+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());+let payout_id = req.payout_id.clone().get_required_value("payout_id")?;let mut payout_data = Box::pin(make_payout_data(&state,@@ -497,6 +518,7 @@ pub async fn payouts_update_core(&mut payout_data,req.routing.clone(),req.connector.clone(),+ dimensions,).await?;}@@ -663,6 +685,8 @@ pub async fn payouts_fulfill_core(let payout_attempt = payout_data.payout_attempt.to_owned();let status = payout_attempt.status;+ let dimensions = configs::dimension_state::Dimensions::new()+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());// Verify if fulfillment can be triggeredif helpers::is_payout_terminal_state(status)@@ -701,6 +725,7 @@ pub async fn payouts_fulfill_core(&platform,&connector_data,&mut payout_data,+ &dimensions,)).await.attach_printable("Payout fulfillment failed for given Payout request")?;@@ -1059,6 +1084,7 @@ pub async fn call_connector_payout(platform: &domain::Platform,connector_data: &api::ConnectorData,payout_data: &mut PayoutData,+ dimensions: &DimensionsWithMerchantId,) -> RouterResult<()> {let payout_attempt = &payout_data.payout_attempt.to_owned();let payouts = &payout_data.payouts.to_owned();@@ -1146,9 +1172,15 @@ pub async fn call_connector_payout(// Auto fulfillment flowlet status = payout_data.payout_attempt.status;if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment {- Box::pin(fulfill_payout(state, platform, connector_data, payout_data))- .await- .attach_printable("Payout fulfillment failed for given Payout request")?;+ Box::pin(fulfill_payout(+ state,+ platform,+ connector_data,+ payout_data,+ dimensions,+ ))+ .await+ .attach_printable("Payout fulfillment failed for given Payout request")?;}Ok(())@@ -2453,6 +2485,7 @@ pub async fn fulfill_payout(platform: &domain::Platform,connector_data: &api::ConnectorData,payout_data: &mut PayoutData,+ dimensions: &DimensionsWithMerchantId,) -> RouterResult<()> {// 1. Form Router datalet mut router_data =@@ -2470,8 +2503,21 @@ pub async fn fulfill_payout(.await?;// 3. Call connector service+ let db = &*state.store;+ let dimension_with_connector = dimensions.with_connector(connector_data.connector_name);let router_data_resp = match helpers::should_continue_payout(&router_data) {true => {+ // add payout sync task to process tracker+ payout_sync::PayoutSyncWorkFlow::add_payout_sync_task_to_process_tracker(+ state,+ payout_data,+ state.conf.application_source,+ &dimension_with_connector,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add payout sync task to process tracker")?;+let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<api::PoFulfill,types::PayoutsData,@@ -2493,7 +2539,6 @@ pub async fn fulfill_payout(};// 4. Process data returned by the connector- let db = &*state.store;match router_data_resp.response {Ok(payout_response_data) => {let status = payout_response_data@@ -2537,24 +2582,19 @@ pub async fn fulfill_payout(.payout_method_data.clone().get_required_value("payout_method_data")?;- payout_data- .payouts- .customer_id- .clone()- .async_map(|customer_id| async move {- helpers::save_payout_data_to_locker(- state,- payout_data,- &customer_id,- &payout_method_data,- None,- platform,- )- .await- })++ if let Some(customer_id) = payout_data.payouts.customer_id.clone() {+ helpers::save_payout_data_to_locker(+ state,+ payout_data,+ &customer_id,+ &payout_method_data,+ None,+ platform,+ ).await- .transpose().attach_printable("Failed to save payout data to locker")?;+ }}}Err(err) => {diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rsindex 5d3a303ab9..61179d9ff3 100644--- a/crates/router/src/core/payouts/retry.rs+++ b/crates/router/src/core/payouts/retry.rs@@ -11,6 +11,7 @@ use super::{call_connector_payout, PayoutData};use crate::{consts,core::{+ configs::dimension_state::DimensionsWithMerchantId,errors::{self, RouterResult, StorageErrorExt},payouts,},@@ -28,6 +29,7 @@ pub async fn do_gsm_multiple_connector_actions(original_connector_data: api::ConnectorData,payout_data: &mut PayoutData,platform: &domain::Platform,+ dimensions: &DimensionsWithMerchantId,) -> RouterResult<()> {let mut retries = None;@@ -67,6 +69,7 @@ pub async fn do_gsm_multiple_connector_actions(connector.to_owned(),platform,payout_data,+ dimensions,)).await?;@@ -85,6 +88,7 @@ pub async fn do_gsm_single_connector_actions(original_connector_data: api::ConnectorData,payout_data: &mut PayoutData,platform: &domain::Platform,+ dimensions: &DimensionsWithMerchantId,) -> RouterResult<()> {let mut retries = None;@@ -122,6 +126,7 @@ pub async fn do_gsm_single_connector_actions(original_connector_data.to_owned(),platform,payout_data,+ dimensions,)).await?;@@ -204,6 +209,7 @@ pub async fn do_retry(connector: api::ConnectorData,platform: &domain::Platform,payout_data: &mut PayoutData,+ dimensions: &DimensionsWithMerchantId,) -> RouterResult<()> {metrics::AUTO_RETRY_PAYOUT_COUNT.add(1, &[]);@@ -214,6 +220,7 @@ pub async fn do_retry(platform,&connector,payout_data,+ dimensions,)).await}diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rsindex 3c205377af..e8e2e15ecc 100644--- a/crates/router/src/workflows.rs+++ b/crates/router/src/workflows.rs@@ -17,3 +17,6 @@ pub mod process_dispute;pub mod dispute_list;pub mod invoice_sync;++#[cfg(feature = "payouts")]+pub mod payout_sync;diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rsindex 55898ee670..0aecdef6c4 100644--- a/crates/router/src/workflows/attach_payout_account_workflow.rs+++ b/crates/router/src/workflows/attach_payout_account_workflow.rs@@ -8,7 +8,7 @@ use scheduler::{};use crate::{- core::payouts,+ core::{configs, payouts},errors as core_errors,routes::SessionState,types::{api, domain, storage},@@ -34,6 +34,9 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow {.merchant_id.clone().get_required_value("merchant_id")?;+ let dimensions =+ configs::dimension_state::Dimensions::new().with_merchant_id(merchant_id.clone());+let key_store = db.get_merchant_key_store_by_merchant_id(&merchant_id,@@ -63,7 +66,7 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow {)).await?;- payouts::payouts_core(state, &platform, &mut payout_data, None, None).await?;+ payouts::payouts_core(state, &platform, &mut payout_data, None, None, dimensions).await?;Ok(())}diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rsindex eb59813a6a..c17ac4b8f7 100644--- a/crates/router/src/workflows/payment_sync.rs+++ b/crates/router/src/workflows/payment_sync.rs@@ -259,7 +259,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {////// `start_after`: The first psync should happen after 60 seconds///-/// `frequency` and `count`: The next 5 retries should have an interval of 300 seconds between them+/// `frequencies`: Do 5 retries with an interval of 300 seconds between them.+/// After than do 2 retries with an interval of 1800 seconds.pub async fn get_sync_process_schedule_time(db: &dyn StorageInterface,connector: &str,diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rsnew file mode 100644index 0000000000..f9ea08a6ca--- /dev/null+++ b/crates/router/src/workflows/payout_sync.rs@@ -0,0 +1,316 @@+use common_enums::enums;+use common_utils::{+ consts::DEFAULT_LOCALE,+ ext_traits::{OptionExt, ValueExt},+};+use diesel_models::process_tracker::business_status;+use error_stack::ResultExt;+use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;+use scheduler::{+ consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow},+ errors, utils as scheduler_utils,+};++use crate::{+ core::{+ configs::{self, dimension_state::DimensionsWithMerchantIdAndConnector},+ payouts, webhooks,+ },+ errors as core_errors,+ routes::SessionState,+ types::{api, domain, storage},+};++pub struct PayoutSyncWorkFlow;++#[async_trait::async_trait]+impl ProcessTrackerWorkflow<SessionState> for PayoutSyncWorkFlow {+ #[cfg(feature = "v2")]+ async fn execute_workflow<'a>(+ &'a self,+ _state: &'a SessionState,+ _process: storage::ProcessTracker,+ ) -> Result<(), errors::ProcessTrackerError> {+ todo!()+ }++ #[cfg(feature = "v1")]+ async fn execute_workflow<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ ) -> Result<(), errors::ProcessTrackerError> {+ // Gather context+ let db = &*state.store;+ let tracking_data: api::PayoutRetrieveRequest = process+ .tracking_data+ .clone()+ .parse_value("PayoutRetrieveRequest")?;++ let merchant_id = tracking_data+ .merchant_id+ .clone()+ .get_required_value("merchant_id")?;+ let key_store = db+ .get_merchant_key_store_by_merchant_id(+ &merchant_id,+ &db.get_master_key().to_vec().into(),+ )+ .await?;++ let merchant_account = db+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)+ .await?;++ let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data);++ let platform = domain::Platform::new(+ merchant_account.clone(),+ key_store.clone(),+ merchant_account,+ key_store.clone(),+ None,+ );++ let mut payout_data = Box::pin(payouts::make_payout_data(+ state,+ &platform,+ None,+ &request,+ DEFAULT_LOCALE,+ ))+ .await?;++ let connector_name = payout_data+ .payout_attempt+ .connector+ .clone()+ .ok_or(errors::ProcessTrackerError::MissingRequiredField)?;++ let connector_data = api::ConnectorData::get_payout_connector_by_name(+ &state.conf.connectors,+ connector_name.as_str(),+ api::GetToken::Connector,+ payout_data.payout_attempt.merchant_connector_id.clone(),+ )+ .change_context(core_errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get the connector data")?;++ payouts::create_payout_retrieve(state, &platform, &connector_data, &mut payout_data)+ .await?;++ let dimensions = configs::dimension_state::Dimensions::new()+ .with_merchant_id(merchant_id.clone())+ .with_connector(connector_data.connector_name);++ if payout_data.payout_attempt.status.is_terminal_status() {+ Self::process_terminal_task(+ state,+ &mut payout_data,+ &key_store,+ &platform,+ process.clone(),+ )+ .await?;+ } else {+ Self::retry_payout_sync_task(+ state,+ payout_data.payouts.payout_id,+ process,+ &dimensions,+ )+ .await?;+ }++ Ok(())+ }++ async fn error_handler<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ error: errors::ProcessTrackerError,+ ) -> core_errors::CustomResult<(), errors::ProcessTrackerError> {+ consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await+ }+}++impl PayoutSyncWorkFlow {+ pub async fn add_payout_sync_task_to_process_tracker(+ state: &SessionState,+ payout_data: &payouts::PayoutData,+ application_source: common_enums::ApplicationSource,+ dimensions: &DimensionsWithMerchantIdAndConnector,+ ) -> common_utils::errors::CustomResult<(), core_errors::ApiErrorResponse> {+ let db = &*state.store;+ let scheduled_time = Self::get_payout_sync_process_schedule_time(+ state,+ payout_data.payouts.payout_id.clone(),+ 0,+ dimensions,+ )+ .await+ .change_context(core_errors::ApiErrorResponse::InternalServerError)?;+ match scheduled_time {+ Some(schedule_time) => {+ let runner = storage::ProcessTrackerRunner::PayoutSyncWorkFlow;+ let task = "PAYOUTS_SYNC";+ let tag = ["PAYOUTS", "SYNC"];+ let process_tracker_id = scheduler_utils::get_process_tracker_id(+ runner,+ task,+ &payout_data.payout_attempt.payout_attempt_id,+ &payout_data.payout_attempt.merchant_id,+ );+ let tracking_data = api::PayoutRetrieveRequest {+ payout_id: payout_data.payouts.payout_id.to_owned(),+ force_sync: Some(true),+ merchant_id: Some(payout_data.payouts.merchant_id.to_owned()),+ };+ let process_tracker_entry = storage::ProcessTrackerNew::new(+ process_tracker_id,+ task,+ runner,+ tag,+ tracking_data,+ None,+ schedule_time,+ common_types::consts::API_VERSION,+ application_source,+ )+ .change_context(core_errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while getting process schedule time")?;++ db.insert_process(process_tracker_entry)+ .await+ .change_context(core_errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert the process tracker entry")?;+ Ok(())+ }+ None => Ok(()),+ }+ }+ /// Get the next schedule time+ ///+ /// The schedule time can be configured in configs by this key `payout_tracker_mapping_trustpay`+ /// ```json+ /// {+ /// "default_mapping": {+ /// "start_after": 60,+ /// "frequencies": [(300, 5), (1800, 2)],+ /// },+ /// "max_retries_count": 5+ /// }+ /// ```+ ///+ /// This config represents+ ///+ /// `start_after`: The first psync should happen after 60 seconds+ ///+ /// `frequencies`: Do 5 retries with an interval of 300 seconds between them.+ /// After than do 2 retries with an interval of 1800 seconds.+ pub async fn get_payout_sync_process_schedule_time(+ state: &SessionState,+ payout_id: common_utils::id_type::PayoutId,+ retry_count: i32,+ dimensions: &DimensionsWithMerchantIdAndConnector,+ ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {+ let value = dimensions+ .get_payout_tracker_mapping(+ state.store.as_ref(),+ state.superposition_service.as_deref(),+ Some(&payout_id),+ )+ .await;++ let time_delta = Self::get_schedule_time(value, retry_count);++ Ok(scheduler_utils::get_time_from_delta(time_delta))+ }++ /// get the schedule time for next process+ pub fn get_schedule_time(mapping: process_data::RetryMapping, retry_count: i32) -> Option<i32> {+ // For first try, get the `start_after` time+ if retry_count == 0 {+ Some(mapping.start_after)+ } else {+ scheduler_utils::get_delay(retry_count, &mapping.frequencies)+ }+ }++ /// process the task if the status is terminal+ #[cfg(feature = "v1")]+ pub async fn process_terminal_task(+ state: &SessionState,+ payout_data: &mut payouts::PayoutData,+ key_store: &MerchantKeyStore,+ platform: &domain::Platform,+ process: storage::ProcessTracker,+ ) -> Result<(), errors::ProcessTrackerError> {+ let db = &*state.store;+ state+ .store+ .as_scheduler()+ .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)+ .await?;++ let event_type: Option<enums::EventType> = payout_data.payout_attempt.status.into();++ let business_profile = db+ .find_business_profile_by_profile_id(key_store, &payout_data.profile_id)+ .await+ .map_err(errors::ProcessTrackerError::EStorageError)?;++ // Trigger webhook to the merchant if it is a terminal status+ // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook+ if let Some(outgoing_event_type) = event_type {+ let payout_response = payouts::response_handler(state, platform, payout_data).await?;++ Box::pin(webhooks::create_event_and_trigger_outgoing_webhook(+ state.clone(),+ platform.get_processor().clone(),+ business_profile,+ outgoing_event_type,+ enums::EventClass::Payouts,+ payout_data.payouts.payout_id.get_string_repr().to_string(),+ enums::EventObjectType::PayoutDetails,+ api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_response)),+ Some(payout_data.payout_attempt.created_at),+ ))+ .await?;+ }++ Ok(())+ }++ /// Schedule the task for retry+ pub async fn retry_payout_sync_task(+ state: &SessionState,+ payout_id: common_utils::id_type::PayoutId,+ pt: storage::ProcessTracker,+ dimensions: &DimensionsWithMerchantIdAndConnector,+ ) -> Result<(), errors::ProcessTrackerError> {+ let db = &*state.store;+ let schedule_time: Option<time::PrimitiveDateTime> =+ Self::get_payout_sync_process_schedule_time(+ state,+ payout_id,+ pt.retry_count + 1,+ dimensions,+ )+ .await?;++ match schedule_time {+ Some(s_time) => {+ db.as_scheduler().retry_process(pt, s_time).await?;+ }+ None => {+ db.as_scheduler()+ .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)+ .await?;+ }+ }++ Ok(())+ }+}diff --git a/crates/scheduler/src/consumer/types/process_data.rs b/crates/scheduler/src/consumer/types/process_data.rsindex 6e236e1827..e74b72e513 100644--- a/crates/scheduler/src/consumer/types/process_data.rs+++ b/crates/scheduler/src/consumer/types/process_data.rs@@ -9,6 +9,24 @@ pub struct RetryMapping {pub frequencies: Vec<(i32, i32)>, // (frequency, count)}+impl Default for RetryMapping {+ fn default() -> Self {+ Self {+ start_after: 60,+ frequencies: vec![(300, 5)],+ }+ }+}++impl TryFrom<serde_json::Value> for RetryMapping {+ type Error = String;++ fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {+ serde_json::from_value(value)+ .map_err(|e| format!("Failed to deserialize RetryMapping: {:?}", e))+ }+}+#[derive(Serialize, Deserialize)]pub struct ConnectorPTMapping {pub default_mapping: RetryMapping,@@ -20,10 +38,7 @@ impl Default for ConnectorPTMapping {fn default() -> Self {Self {custom_merchant_mapping: HashMap::new(),- default_mapping: RetryMapping {- start_after: 60,- frequencies: vec![(300, 5)],- },+ default_mapping: RetryMapping::default(),max_retries_count: 5,}}