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(payouts): add expanded attempts to payout retrieve (#12363)

Sakil Mostak11c6cea6fed9
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 9a4f3b2722..96129c60ad 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -35631,6 +35631,10 @@
"merchant_id": {
"type": "string",
"nullable": true
+ },
+ "expand_attempts": {
+ "type": "boolean",
+ "nullable": true
}
}
},
@@ -35658,6 +35662,13 @@
"type": "string",
"description": "The identifier for the Merchant Account.",
"nullable": true
+ },
+ "expand_attempts": {
+ "type": "boolean",
+ "description": "Set to true to get the list of attempts along with payout details, no further action required",
+ "default": false,
+ "example": true,
+ "nullable": true
}
}
},
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 3875e02af6..472f966f27 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -26033,6 +26033,10 @@
"merchant_id": {
"type": "string",
"nullable": true
+ },
+ "expand_attempts": {
+ "type": "boolean",
+ "nullable": true
}
}
},
@@ -26060,6 +26064,13 @@
"type": "string",
"description": "The identifier for the Merchant Account.",
"nullable": true
+ },
+ "expand_attempts": {
+ "type": "boolean",
+ "description": "Set to true to get the list of attempts along with payout details, no further action required",
+ "default": false,
+ "example": true,
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 7662b0ab2c..3be96c2254 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -933,6 +933,7 @@ pub struct PayoutRetrieveBody {
pub force_sync: Option<bool>,
#[schema(value_type = Option<String>)]
pub merchant_id: Option<id_type::MerchantId>,
+ pub expand_attempts: Option<bool>,
}
#[derive(Debug, Serialize, ToSchema, Clone, Deserialize)]
@@ -955,6 +956,10 @@ pub struct PayoutRetrieveRequest {
/// The identifier for the Merchant Account.
#[schema(value_type = Option<String>)]
pub merchant_id: Option<id_type::MerchantId>,
+
+ /// Set to true to get the list of attempts along with payout details, no further action required
+ #[schema(value_type = Option<bool>, default = false, example = true)]
+ pub expand_attempts: Option<bool>,
}
#[derive(Debug, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema)]
diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs
index 300b6fdb64..45b8eb4fb2 100644
--- a/crates/diesel_models/src/query/payout_attempt.rs
+++ b/crates/diesel_models/src/query/payout_attempt.rs
@@ -4,7 +4,7 @@ use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{
associations::HasTable,
query_dsl::methods::{DistinctDsl, FilterDsl, SelectDsl},
- BoolExpressionMethods, ExpressionMethods,
+ BoolExpressionMethods, ExpressionMethods, Table,
};
use error_stack::{report, ResultExt};
@@ -57,12 +57,20 @@ impl PayoutAttempt {
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
- ) -> StorageResult<Self> {
- generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<
+ <Self as HasTable>::Table,
+ _,
+ <<Self as HasTable>::Table as Table>::PrimaryKey,
+ _,
+ >(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payout_id.eq(payout_id.to_owned())),
+ None,
+ None,
+ None,
)
.await
}
diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs
index 4c26690b33..303f3c36e0 100644
--- a/crates/diesel_models/src/query/utils.rs
+++ b/crates/diesel_models/src/query/utils.rs
@@ -68,6 +68,18 @@ mod composite_key {
self.1
}
}
+ impl CompositeKey for <schema::payout_attempt::table as diesel::Table>::PrimaryKey {
+ type UK = schema::payout_attempt::dsl::payout_attempt_id;
+ fn get_local_unique_key(&self) -> Self::UK {
+ self.1
+ }
+ }
+ impl CompositeKey for <schema::payouts::table as diesel::Table>::PrimaryKey {
+ type UK = schema::payouts::dsl::payout_id;
+ fn get_local_unique_key(&self) -> Self::UK {
+ self.1
+ }
+ }
}
/// This macro will implement the `GetPrimaryKey` trait for all the tables with single primary key.
@@ -149,5 +161,7 @@ impl_get_primary_key_for_composite!(
schema::incremental_authorization::table,
schema::hyperswitch_ai_interaction::table,
schema_v2::incremental_authorization::table,
- schema_v2::blocklist::table
+ schema_v2::blocklist::table,
+ schema::payout_attempt::table,
+ schema::payouts::table
);
diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
index 291b36dc01..abc5096a5f 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
@@ -55,6 +55,13 @@ pub trait PayoutAttemptInterface {
_merchant_id: &id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutListFilters, Self::Error>;
+
+ async fn find_payout_attempts_by_merchant_id_payout_id(
+ &self,
+ _merchant_id: &id_type::MerchantId,
+ _payout_id: &id_type::PayoutId,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<Vec<PayoutAttempt>, Self::Error>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -99,6 +106,29 @@ pub struct PayoutAttempt {
pub additional_source_bank_data: Option<payout_method_utils::BankAdditionalData>,
}
+impl PayoutAttempt {
+ pub fn to_payout_attempt_response(
+ &self,
+ payout: &Payouts,
+ ) -> api_models::payouts::PayoutAttemptResponse {
+ api_models::payouts::PayoutAttemptResponse {
+ attempt_id: self.payout_attempt_id.clone(),
+ status: self.status,
+ amount: payout.amount,
+ currency: Some(payout.destination_currency),
+ connector: self.connector.clone(),
+ error_code: self.error_code.clone(),
+ error_message: self.error_message.clone(),
+ payment_method: payout.payout_type,
+ payout_method_type: None,
+ connector_transaction_id: self.connector_payout_id.clone(),
+ cancellation_reason: None,
+ unified_code: self.unified_code.clone(),
+ unified_message: self.unified_message.clone(),
+ }
+ }
+}
+
#[derive(Clone, Debug, PartialEq)]
pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 3e3860320e..1c50d131e7 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -96,6 +96,7 @@ pub struct PayoutData {
pub connector_transfer_method_id: Option<String>,
pub browser_info: Option<domain_models::router_request_types::BrowserInformation>,
pub source_bank_data: Option<api_models::payouts::BankTransfer>,
+ pub attempts: Option<Vec<storage::PayoutAttempt>>,
}
// ********************************************** CORE FLOWS **********************************************
@@ -2928,7 +2929,7 @@ pub async fn response_handler(
let payout_link = payout_data.payout_link.to_owned();
let billing_address = payout_data.billing_address.to_owned();
let customer_details = payout_data.customer_details.to_owned();
- let customer_id = payouts.customer_id;
+ let customer_id = payouts.customer_id.clone();
let billing = billing_address.map(From::from);
let translated_unified_message = helpers::get_translated_unified_code_and_message(
@@ -2973,7 +2974,7 @@ pub async fn response_handler(
description: payouts.description.to_owned(),
entity_type: payouts.entity_type.to_owned(),
recurring: payouts.recurring,
- metadata: payouts.metadata,
+ metadata: payouts.metadata.clone(),
merchant_connector_id: payout_attempt.merchant_connector_id.to_owned(),
status: payout_attempt.status.to_owned(),
error_message: payout_attempt.error_message.to_owned(),
@@ -2982,7 +2983,12 @@ pub async fn response_handler(
created: Some(payouts.created_at),
connector_transaction_id: payout_attempt.connector_payout_id,
priority: payouts.priority,
- attempts: None,
+ attempts: payout_data.attempts.as_ref().map(|attempts| {
+ attempts
+ .iter()
+ .map(|attempt| attempt.to_payout_attempt_response(&payouts))
+ .collect()
+ }),
unified_code: payout_attempt.unified_code,
unified_message: translated_unified_message,
payout_link: payout_link
@@ -3278,6 +3284,7 @@ pub async fn payout_create_db_entries(
connector_transfer_method_id: None,
browser_info: req.browser_info.clone().map(Into::into),
source_bank_data: req.source_bank_data.clone(),
+ attempts: None,
})
}
@@ -3319,6 +3326,31 @@ pub async fn make_payout_data(
payouts::PayoutRequest::PayoutRetrieveRequest(_) => None,
};
+ let attempts = match req {
+ payouts::PayoutRequest::PayoutActionRequest(_) => None,
+ payouts::PayoutRequest::PayoutCreateRequest(_) => None,
+ payouts::PayoutRequest::PayoutRetrieveRequest(retrieve_request) => {
+ match retrieve_request.expand_attempts {
+ Some(true) => db
+ .find_payout_attempts_by_merchant_id_payout_id(
+ merchant_id,
+ &retrieve_request.payout_id,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .map_err(|err| {
+ let err_msg = format!(
+ "failed to fetch payout_attempts for payout_id: {:?}",
+ retrieve_request.payout_id
+ );
+ logger::error!(?err, err_msg);
+ })
+ .ok(),
+ Some(false) | None => None,
+ }
+ }
+ };
+
let payouts = db
.find_payout_by_merchant_id_payout_id(
merchant_id,
@@ -3562,6 +3594,7 @@ pub async fn make_payout_data(
connector_transfer_method_id: None,
browser_info,
source_bank_data,
+ attempts,
})
}
@@ -3584,6 +3617,7 @@ pub async fn add_external_account_addition_task(
payout_id: payout_data.payouts.payout_id.to_owned(),
force_sync: None,
merchant_id: Some(payout_data.payouts.merchant_id.to_owned()),
+ expand_attempts: None,
};
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index cae45bef12..14063161ad 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -1191,6 +1191,7 @@ async fn process_payout_incoming_webhook(
payout_id,
force_sync: None,
merchant_id: Some(platform.get_processor().get_account().get_id().clone()),
+ expand_attempts: None,
});
let mut payout_data = Box::pin(payouts::make_payout_data(
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 9dc2e4d892..edf0e8e7f7 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2606,6 +2606,17 @@ impl PayoutAttemptInterface for KafkaStore {
.get_filters_for_payouts(payouts, merchant_id, storage_scheme)
.await
}
+
+ async fn find_payout_attempts_by_merchant_id_payout_id(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ payout_id: &id_type::PayoutId,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<Vec<storage::PayoutAttempt>, errors::StorageError> {
+ self.diesel_store
+ .find_payout_attempts_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme)
+ .await
+ }
}
#[cfg(not(feature = "payouts"))]
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 9c2d6f3b1c..d9ff774ebf 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -77,6 +77,7 @@ pub async fn payouts_retrieve(
payout_id: path.into_inner(),
force_sync: query_params.force_sync.to_owned(),
merchant_id: query_params.merchant_id.to_owned(),
+ expand_attempts: query_params.expand_attempts.to_owned(),
};
let flow = Flow::PayoutsRetrieve;
diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rs
index 76e3669e3f..a9d2e6d3b6 100644
--- a/crates/router/src/workflows/payout_sync.rs
+++ b/crates/router/src/workflows/payout_sync.rs
@@ -172,6 +172,7 @@ impl PayoutSyncWorkFlow {
payout_id: payout_data.payouts.payout_id.to_owned(),
force_sync: Some(true),
merchant_id: Some(payout_data.payouts.merchant_id.to_owned()),
+ expand_attempts: None,
};
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
diff --git a/crates/storage_impl/src/mock_db/payout_attempt.rs b/crates/storage_impl/src/mock_db/payout_attempt.rs
index 008e9f921b..fbd45d6d1f 100644
--- a/crates/storage_impl/src/mock_db/payout_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payout_attempt.rs
@@ -74,4 +74,13 @@ impl PayoutAttemptInterface for MockDb {
) -> CustomResult<PayoutAttempt, StorageError> {
Err(StorageError::MockDbError)?
}
+
+ async fn find_payout_attempts_by_merchant_id_payout_id(
+ &self,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _payout_id: &common_utils::id_type::PayoutId,
+ _storage_scheme: storage_enums::MerchantStorageScheme,
+ ) -> CustomResult<Vec<PayoutAttempt>, StorageError> {
+ Err(StorageError::MockDbError)?
+ }
}
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 086e710250..8ca38c7f08 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -404,6 +404,17 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
)
.await
}
+
+ async fn find_payout_attempts_by_merchant_id_payout_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ payout_id: &common_utils::id_type::PayoutId,
+ storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<Vec<PayoutAttempt>, Self::Error> {
+ self.router_store
+ .find_payout_attempts_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme)
+ .await
+ }
}
#[async_trait::async_trait]
@@ -551,6 +562,27 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
er.change_context(new_err)
})
}
+
+ async fn find_payout_attempts_by_merchant_id_payout_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ payout_id: &common_utils::id_type::PayoutId,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> error_stack::Result<Vec<PayoutAttempt>, errors::StorageError> {
+ let conn = pg_connection_read(self).await?;
+ DieselPayoutAttempt::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
+ .await
+ .map(|attempts| {
+ attempts
+ .into_iter()
+ .map(PayoutAttempt::from_storage_model)
+ .collect()
+ })
+ .map_err(|er| {
+ let new_err = diesel_error_to_data_error(*er.current_context());
+ er.change_context(new_err)
+ })
+ }
}
impl DataModelExt for PayoutAttempt {