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(merchant_account): add merchant account list endpoint (#2560)

Narayan Bhata1472c6b78af
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index acffbfe812..dbac9a4bc4 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -14,6 +14,11 @@ use crate::{
payment_methods,
};
+#[derive(Clone, Debug, Deserialize, ToSchema)]
+pub struct MerchantAccountListRequest {
+ pub organization_id: String,
+}
+
#[derive(Clone, Debug, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct MerchantAccountCreate {
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs
index 598a4889a7..ef9a4165d6 100644
--- a/crates/diesel_models/src/query/merchant_account.rs
+++ b/crates/diesel_models/src/query/merchant_account.rs
@@ -1,4 +1,4 @@
-use diesel::{associations::HasTable, ExpressionMethods};
+use diesel::{associations::HasTable, ExpressionMethods, Table};
use router_env::{instrument, tracing};
use super::generics;
@@ -90,4 +90,24 @@ impl MerchantAccount {
)
.await
}
+
+ #[instrument(skip_all)]
+ pub async fn list_by_organization_id(
+ conn: &PgPooledConn,
+ organization_id: &str,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<
+ <Self as HasTable>::Table,
+ _,
+ <<Self as HasTable>::Table as Table>::PrimaryKey,
+ _,
+ >(
+ conn,
+ dsl::organization_id.eq(organization_id.to_owned()),
+ None,
+ None,
+ None,
+ )
+ .await
+ }
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 1f60f11a97..46aae8faea 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -252,6 +252,31 @@ pub async fn create_merchant_account(
))
}
+#[cfg(feature = "olap")]
+pub async fn list_merchant_account(
+ state: AppState,
+ req: api_models::admin::MerchantAccountListRequest,
+) -> RouterResponse<Vec<api::MerchantAccountResponse>> {
+ let merchant_accounts = state
+ .store
+ .list_merchant_accounts_by_organization_id(&req.organization_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ let merchant_accounts = merchant_accounts
+ .into_iter()
+ .map(|merchant_account| {
+ merchant_account
+ .try_into()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "merchant_account",
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+
+ Ok(services::ApplicationResponse::Json(merchant_accounts))
+}
+
pub async fn get_merchant_account(
state: AppState,
req: api::MerchantId,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 726ae55f91..e0bff7d906 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -55,6 +55,12 @@ where
publishable_key: &str,
) -> CustomResult<authentication::AuthenticationData, errors::StorageError>;
+ #[cfg(feature = "olap")]
+ async fn list_merchant_accounts_by_organization_id(
+ &self,
+ organization_id: &str,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>;
+
async fn delete_merchant_account_by_merchant_id(
&self,
merchant_id: &str,
@@ -212,6 +218,47 @@ impl MerchantAccountInterface for Store {
})
}
+ #[cfg(feature = "olap")]
+ async fn list_merchant_accounts_by_organization_id(
+ &self,
+ organization_id: &str,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
+ use futures::future::try_join_all;
+ let conn = connection::pg_connection_read(self).await?;
+
+ let encrypted_merchant_accounts =
+ storage::MerchantAccount::list_by_organization_id(&conn, organization_id)
+ .await
+ .map_err(Into::into)
+ .into_report()?;
+
+ let db_master_key = self.get_master_key().to_vec().into();
+
+ let merchant_key_stores =
+ try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| {
+ self.get_merchant_key_store_by_merchant_id(
+ &merchant_account.merchant_id,
+ &db_master_key,
+ )
+ }))
+ .await?;
+
+ let merchant_accounts = try_join_all(
+ encrypted_merchant_accounts
+ .into_iter()
+ .zip(merchant_key_stores.iter())
+ .map(|(merchant_account, key_store)| async {
+ merchant_account
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }),
+ )
+ .await?;
+
+ Ok(merchant_accounts)
+ }
+
async fn delete_merchant_account_by_merchant_id(
&self,
merchant_id: &str,
@@ -337,6 +384,14 @@ impl MerchantAccountInterface for MockDb {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
+
+ #[cfg(feature = "olap")]
+ async fn list_merchant_accounts_by_organization_id(
+ &self,
+ _organization_id: &str,
+ ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
}
#[cfg(feature = "accounts_cache")]
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index f0a0dc4031..a93556202a 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -77,6 +77,28 @@ pub async fn retrieve_merchant_account(
)
.await
}
+
+#[cfg(feature = "olap")]
+#[instrument(skip_all, fields(flow = ?Flow::MerchantAccountList))]
+pub async fn merchant_account_list(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_params: web::Query<api_models::admin::MerchantAccountListRequest>,
+) -> HttpResponse {
+ let flow = Flow::MerchantAccountList;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_params.into_inner(),
+ |state, _, request| list_merchant_account(state, request),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
/// Merchant Account - Update
///
/// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
@@ -113,6 +135,7 @@ pub async fn update_merchant_account(
)
.await
}
+
/// Merchant Account - Delete
///
/// To delete a merchant account
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 5ebafe9a66..42f44749ac 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -394,6 +394,7 @@ impl MerchantAccount {
web::scope("/accounts")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(merchant_account_create)))
+ .service(web::resource("/list").route(web::get().to(merchant_account_list)))
.service(
web::resource("/{id}/kv")
.route(web::post().to(merchant_account_toggle_kv))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 6a69db6257..5be361098b 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -30,7 +30,8 @@ impl From<Flow> for ApiIdentifier {
Flow::MerchantsAccountCreate
| Flow::MerchantsAccountRetrieve
| Flow::MerchantsAccountUpdate
- | Flow::MerchantsAccountDelete => Self::MerchantAccount,
+ | Flow::MerchantsAccountDelete
+ | Flow::MerchantAccountList => Self::MerchantAccount,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 1c56c4c7c2..d63ddce58f 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -66,6 +66,8 @@ pub enum Flow {
MerchantConnectorsCreate,
/// Merchant Connectors retrieve flow.
MerchantConnectorsRetrieve,
+ /// Merchant account list
+ MerchantAccountList,
/// Merchant Connectors update flow.
MerchantConnectorsUpdate,
/// Merchant Connectors delete flow.
diff --git a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/event.test.js b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/event.test.js
index 7de0d5beb3..9c5a8900dc 100644
--- a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/event.test.js
+++ b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - Create/event.test.js
@@ -14,7 +14,7 @@ pm.test("[POST]::/accounts - Content-Type is application/json", function () {
let jsonData = {};
try {
jsonData = pm.response.json();
-} catch (e) {}
+} catch (e) { }
// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id
if (jsonData?.merchant_id) {
@@ -54,3 +54,16 @@ if (jsonData?.publishable_key) {
"INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.",
);
}
+
+// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id
+if (jsonData?.merchant_id) {
+ pm.collectionVariables.set("organization_id", jsonData.organization_id);
+ console.log(
+ "- use {{organization_id}} as collection variable for value",
+ jsonData.organization_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{organization_id}}, as jsonData.organization_id is undefined.",
+ );
+}
diff --git a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/.event.meta.json b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/.event.meta.json
new file mode 100644
index 0000000000..0731450e6b
--- /dev/null
+++ b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/.event.meta.json
@@ -0,0 +1,3 @@
+{
+ "eventOrder": ["event.test.js"]
+}
diff --git a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/event.test.js b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/event.test.js
new file mode 100644
index 0000000000..0ba15a15ee
--- /dev/null
+++ b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/event.test.js
@@ -0,0 +1,43 @@
+// Validate status 2xx
+pm.test("[GET]::/accounts/list - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[GET]::/accounts/list - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) { }
+
+// pm.collectionVariables - Set api_key as variable for jsonData.api_key
+if (jsonData?.api_key) {
+ pm.collectionVariables.set("api_key", jsonData.api_key);
+ console.log(
+ "- use {{api_key}} as collection variable for value",
+ jsonData.api_key,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key
+if (jsonData?.publishable_key) {
+ pm.collectionVariables.set("publishable_key", jsonData.publishable_key);
+ console.log(
+ "- use {{publishable_key}} as collection variable for value",
+ jsonData.publishable_key,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.",
+ );
+}
diff --git a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/request.json b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/request.json
new file mode 100644
index 0000000000..841485a0a0
--- /dev/null
+++ b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/request.json
@@ -0,0 +1,49 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/accounts/list",
+ "host": ["{{baseUrl}}"],
+ "path": ["accounts", "list"],
+ "query": [
+ {
+ "key": "organization_id",
+ "value": "{{organization_id}}",
+ "disabled": false
+ }
+ ],
+ "variable": [
+ {
+ "key": "organization_id",
+ "value": "{{organization_id}}",
+ "description": "(Required) - Organization id"
+ }
+ ]
+ },
+ "description": "List merchant accounts for an organization"
+}
diff --git a/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/response.json b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/response.json
new file mode 100644
index 0000000000..fe51488c70
--- /dev/null
+++ b/postman/collection-dir/stripe/MerchantAccounts/Merchant Account - List/response.json
@@ -0,0 +1 @@
+[]