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(platform): convert organization to platform organization (#10910)

Ankit Kumar Gupta256e7fee0233
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 6eebdbff7f..4999d7ec10 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -21177,7 +21177,7 @@
"merchant_account_type": {
"allOf": [
{
- "$ref": "#/components/schemas/MerchantAccountRequestType"
+ "$ref": "#/components/schemas/MerchantAccountType"
}
],
"nullable": true
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index baa0e69dcf..7c00327abb 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -115,8 +115,8 @@ pub struct MerchantAccountCreate {
pub product_type: Option<api_enums::MerchantProductType>,
/// Merchant Account Type of this merchant account
- #[schema(value_type = Option<MerchantAccountRequestType>, example = "standard")]
- pub merchant_account_type: Option<api_enums::MerchantAccountRequestType>,
+ #[schema(value_type = Option<MerchantAccountType>, example = "standard")]
+ pub merchant_account_type: Option<api_enums::MerchantAccountType>,
}
#[cfg(feature = "v1")]
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index b97d77a4a8..8b8e78c686 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -39,6 +39,7 @@ use crate::{
files::*,
mandates::*,
organization::{
+ ConvertOrganizationToPlatformRequest, ConvertOrganizationToPlatformResponse,
OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest,
},
payment_methods::*,
@@ -74,6 +75,8 @@ impl_api_event_type!(
RetrievePaymentLinkResponse,
MandateListConstraints,
CreateFileResponse,
+ ConvertOrganizationToPlatformRequest,
+ ConvertOrganizationToPlatformResponse,
MerchantConnectorResponse,
MerchantConnectorId,
MandateResponse,
diff --git a/crates/api_models/src/organization.rs b/crates/api_models/src/organization.rs
index e12b21c143..fa6dc01c98 100644
--- a/crates/api_models/src/organization.rs
+++ b/crates/api_models/src/organization.rs
@@ -1,5 +1,6 @@
use common_enums::OrganizationType;
use common_utils::{id_type, pii};
+use masking::Secret;
use utoipa::ToSchema;
pub struct OrganizationNew {
pub org_id: id_type::OrganizationId,
@@ -104,3 +105,25 @@ pub struct OrganizationResponse {
#[schema(value_type = Option<OrganizationType>, example = "standard")]
pub organization_type: Option<OrganizationType>,
}
+
+#[derive(serde::Deserialize, Debug, Clone, serde::Serialize, ToSchema)]
+pub struct ConvertOrganizationToPlatformRequest {
+ /// Name for the platform merchant to be created
+ #[schema(value_type = Option<String>)]
+ pub platform_merchant_name: Option<Secret<String>>,
+}
+
+#[derive(serde::Serialize, Debug, Clone, ToSchema)]
+pub struct ConvertOrganizationToPlatformResponse {
+ /// The unique identifier for the Organization
+ #[schema(value_type = String)]
+ pub organization_id: id_type::OrganizationId,
+
+ /// Organization Type after conversion
+ #[schema(value_type = OrganizationType)]
+ pub organization_type: OrganizationType,
+
+ /// The unique identifier for the platform merchant created
+ #[schema(value_type = String)]
+ pub platform_merchant_id: id_type::MerchantId,
+}
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index b0fe921940..0aa40fa16a 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -18,6 +18,7 @@ pub struct SignUpWithMerchantIdRequest {
pub email: pii::Email,
pub password: Secret<String>,
pub company_name: String,
+ pub organization_type: Option<common_enums::OrganizationType>,
}
pub type SignUpWithMerchantIdResponse = AuthorizeResponse;
diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs
index bb0c5845c4..4fe8c8666d 100644
--- a/crates/common_enums/src/enums/accounts.rs
+++ b/crates/common_enums/src/enums/accounts.rs
@@ -92,3 +92,12 @@ pub enum MerchantAccountRequestType {
Standard,
Connected,
}
+
+impl From<MerchantAccountRequestType> for MerchantAccountType {
+ fn from(value: MerchantAccountRequestType) -> Self {
+ match value {
+ MerchantAccountRequestType::Standard => Self::Standard,
+ MerchantAccountRequestType::Connected => Self::Connected,
+ }
+ }
+}
diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs
index ffa1e94fcf..6004335ce7 100644
--- a/crates/diesel_models/src/organization.rs
+++ b/crates/diesel_models/src/organization.rs
@@ -206,6 +206,7 @@ pub struct OrganizationUpdateInternal {
metadata: Option<pii::SecretSerdeValue>,
modified_at: time::PrimitiveDateTime,
platform_merchant_id: Option<id_type::MerchantId>,
+ organization_type: Option<common_enums::OrganizationType>,
}
#[cfg(feature = "v2")]
@@ -217,6 +218,7 @@ pub struct OrganizationUpdateInternal {
metadata: Option<pii::SecretSerdeValue>,
modified_at: time::PrimitiveDateTime,
platform_merchant_id: Option<id_type::MerchantId>,
+ organization_type: Option<common_enums::OrganizationType>,
}
pub enum OrganizationUpdate {
@@ -224,7 +226,10 @@ pub enum OrganizationUpdate {
organization_name: Option<String>,
organization_details: Option<pii::SecretSerdeValue>,
metadata: Option<pii::SecretSerdeValue>,
- platform_merchant_id: Option<id_type::MerchantId>,
+ },
+ ConvertToPlatform,
+ UpdatePlatformMerchant {
+ platform_merchant_id: id_type::MerchantId,
},
}
@@ -236,14 +241,34 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal {
organization_name,
organization_details,
metadata,
- platform_merchant_id,
} => Self {
org_name: organization_name.clone(),
organization_name,
organization_details,
metadata,
modified_at: common_utils::date_time::now(),
+ platform_merchant_id: None,
+ organization_type: None,
+ },
+ OrganizationUpdate::ConvertToPlatform => Self {
+ org_name: None,
+ organization_name: None,
+ organization_details: None,
+ metadata: None,
+ modified_at: common_utils::date_time::now(),
+ platform_merchant_id: None,
+ organization_type: Some(common_enums::OrganizationType::Platform),
+ },
+ OrganizationUpdate::UpdatePlatformMerchant {
platform_merchant_id,
+ } => Self {
+ org_name: None,
+ organization_name: None,
+ organization_details: None,
+ metadata: None,
+ modified_at: common_utils::date_time::now(),
+ platform_merchant_id: Some(platform_merchant_id),
+ organization_type: None,
},
}
}
@@ -257,13 +282,31 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal {
organization_name,
organization_details,
metadata,
- platform_merchant_id,
} => Self {
organization_name,
organization_details,
metadata,
modified_at: common_utils::date_time::now(),
+ platform_merchant_id: None,
+ organization_type: None,
+ },
+ OrganizationUpdate::ConvertToPlatform => Self {
+ organization_name: None,
+ organization_details: None,
+ metadata: None,
+ modified_at: common_utils::date_time::now(),
+ platform_merchant_id: None,
+ organization_type: Some(common_enums::OrganizationType::Platform),
+ },
+ OrganizationUpdate::UpdatePlatformMerchant {
platform_merchant_id,
+ } => Self {
+ organization_name: None,
+ organization_details: None,
+ metadata: None,
+ modified_at: common_utils::date_time::now(),
+ platform_merchant_id: Some(platform_merchant_id),
+ organization_type: None,
},
}
}
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index a6ccaec206..52ffd7a264 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -286,7 +286,6 @@ pub enum MerchantAccountUpdate {
},
UnsetDefaultProfile,
ModifiedAtUpdate,
- ToPlatformAccount,
}
#[cfg(feature = "v2")]
@@ -305,7 +304,6 @@ pub enum MerchantAccountUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
ModifiedAtUpdate,
- ToPlatformAccount,
}
#[cfg(feature = "v1")]
@@ -480,35 +478,6 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
is_platform_account: None,
product_type: None,
},
- MerchantAccountUpdate::ToPlatformAccount => Self {
- modified_at: now,
- merchant_name: None,
- merchant_details: None,
- return_url: None,
- webhook_details: None,
- sub_merchants_enabled: None,
- parent_merchant_id: None,
- enable_payment_response_hash: None,
- payment_response_hash_key: None,
- redirect_to_merchant_with_http_post: None,
- publishable_key: None,
- storage_scheme: None,
- locker_id: None,
- metadata: None,
- routing_algorithm: None,
- primary_business_details: None,
- intent_fulfillment_time: None,
- frm_routing_algorithm: None,
- payout_routing_algorithm: None,
- organization_id: None,
- is_recon_enabled: None,
- default_profile: None,
- recon_status: None,
- payment_link_config: None,
- pm_collect_link_config: None,
- is_platform_account: Some(true),
- product_type: None,
- },
}
}
}
@@ -572,18 +541,6 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
is_platform_account: None,
product_type: None,
},
- MerchantAccountUpdate::ToPlatformAccount => Self {
- modified_at: now,
- merchant_name: None,
- merchant_details: None,
- publishable_key: None,
- storage_scheme: None,
- metadata: None,
- organization_id: None,
- recon_status: None,
- is_platform_account: Some(true),
- product_type: None,
- },
}
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index a60f5872e0..b6ccf01421 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -2,9 +2,9 @@ use std::str::FromStr;
use api_models::{
admin::{self as admin_types},
- enums as api_enums, routing as routing_types,
+ enums as api_enums, organization as org_types, routing as routing_types,
};
-use common_enums::{MerchantAccountRequestType, MerchantAccountType, OrganizationType};
+use common_enums::{MerchantAccountType, OrganizationType};
use common_utils::{
date_time,
ext_traits::{AsyncExt, Encode, OptionExt, ValueExt},
@@ -40,7 +40,7 @@ use crate::{
},
db::{AccountsStorageInterface, StorageInterface},
logger,
- routes::{metrics, SessionState},
+ routes::{app::SessionStateInfo, metrics, SessionState},
services::{
self,
api::{self as service_api},
@@ -143,7 +143,6 @@ pub async fn update_organization(
organization_name: req.organization_name,
organization_details: req.organization_details,
metadata: req.metadata,
- platform_merchant_id: req.platform_merchant_id,
};
state
.accounts_store
@@ -183,6 +182,139 @@ pub async fn get_organization(
}
}
+#[cfg(all(feature = "olap", feature = "v1"))]
+fn create_platform_merchant_account_request(
+ merchant_id: id_type::MerchantId,
+ merchant_name: String,
+ organization_id: id_type::OrganizationId,
+) -> admin_types::MerchantAccountCreate {
+ admin_types::MerchantAccountCreate {
+ merchant_id,
+ merchant_name: Some(Secret::new(merchant_name)),
+ organization_id: Some(organization_id),
+ merchant_account_type: Some(MerchantAccountType::Platform),
+ merchant_details: None,
+ return_url: None,
+ webhook_details: None,
+ sub_merchants_enabled: None,
+ parent_merchant_id: None,
+ enable_payment_response_hash: None,
+ payment_response_hash_key: None,
+ redirect_to_merchant_with_http_post: None,
+ publishable_key: None,
+ locker_id: None,
+ metadata: None,
+ routing_algorithm: None,
+ primary_business_details: None,
+ frm_routing_algorithm: None,
+ #[cfg(feature = "payouts")]
+ payout_routing_algorithm: None,
+ pm_collect_link_config: None,
+ product_type: Some(consts::user::DEFAULT_PRODUCT_TYPE),
+ }
+}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn convert_organization_to_platform_organization(
+ state: SessionState,
+ org_id: api::OrganizationId,
+ req: org_types::ConvertOrganizationToPlatformRequest,
+) -> RouterResponse<org_types::ConvertOrganizationToPlatformResponse> {
+ // Validate platform feature is enabled
+ fp_utils::when(!state.conf().platform.enabled, || {
+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Platform feature is not enabled".to_string()
+ }))
+ })?;
+
+ let organization = state
+ .accounts_store
+ .find_organization_by_org_id(&org_id.organization_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Organization with the given id does not exist".to_string(),
+ })?;
+
+ // Validate organization is not already of type Platform
+ fp_utils::when(
+ organization.get_organization_type() == OrganizationType::Platform,
+ || {
+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "Organization is already of type {:?}",
+ OrganizationType::Platform
+ ),
+ }))
+ },
+ )?;
+
+ // Validate organization doesn't already have a platform_merchant_id
+ fp_utils::when(organization.platform_merchant_id.is_some(), || {
+ Err(report!(errors::ApiErrorResponse::InternalServerError))
+ })?;
+
+ state
+ .accounts_store
+ .update_organization_by_org_id(
+ &org_id.organization_id,
+ diesel_models::organization::OrganizationUpdate::ConvertToPlatform,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update organization type to Platform")?;
+
+ let platform_merchant_name = req
+ .platform_merchant_name
+ .map(|merchant_name| merchant_name.peek().to_string())
+ .unwrap_or_else(|| {
+ format!(
+ "{} Platform",
+ organization.get_organization_name().unwrap_or_default()
+ )
+ });
+
+ let platform_merchant_id =
+ utils::user::generate_env_specific_merchant_id(platform_merchant_name.clone())
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid platform merchant name".to_string(),
+ })?;
+
+ let merchant_create_request = create_platform_merchant_account_request(
+ platform_merchant_id.clone(),
+ platform_merchant_name.clone(),
+ org_id.organization_id.clone(),
+ );
+
+ Box::pin(create_merchant_account(
+ state.clone(),
+ merchant_create_request,
+ Some(authentication::AuthenticationDataWithOrg {
+ organization_id: org_id.organization_id.clone(),
+ }),
+ ))
+ .await?;
+
+ let updated_organization = state
+ .accounts_store
+ .update_organization_by_org_id(
+ &org_id.organization_id,
+ diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {
+ platform_merchant_id: platform_merchant_id.clone(),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update organization type to Platform")?;
+
+ Ok(service_api::ApplicationResponse::Json(
+ org_types::ConvertOrganizationToPlatformResponse {
+ organization_id: updated_organization.get_organization_id(),
+ organization_type: updated_organization.get_organization_type(),
+ platform_merchant_id,
+ },
+ ))
+}
+
#[cfg(feature = "olap")]
pub async fn create_merchant_account(
state: SessionState,
@@ -364,20 +496,25 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
.await?;
let merchant_account_type = match organization.get_organization_type() {
- OrganizationType::Standard => {
- match self.merchant_account_type.unwrap_or_default() {
- // Allow only if explicitly Standard or not provided
- MerchantAccountRequestType::Standard => MerchantAccountType::Standard,
- MerchantAccountRequestType::Connected => {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message:
- "Merchant account type must be Standard for a Standard Organization"
- .to_string(),
- }
- .into());
+ OrganizationType::Standard => match self.merchant_account_type.unwrap_or_default() {
+ MerchantAccountType::Standard => MerchantAccountType::Standard,
+ MerchantAccountType::Connected => {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message:
+ "Merchant account type must be Standard for a Standard Organization"
+ .to_string(),
}
+ .into());
}
- }
+ MerchantAccountType::Platform => {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message:
+ "Merchant account type cannot be Platform for a Standard Organization"
+ .to_string(),
+ }
+ .into());
+ }
+ },
OrganizationType::Platform => {
let accounts = state
@@ -395,8 +532,8 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
MerchantAccountType::Platform
} else {
match self.merchant_account_type.unwrap_or_default() {
- MerchantAccountRequestType::Standard => MerchantAccountType::Standard,
- MerchantAccountRequestType::Connected => {
+ MerchantAccountType::Standard => MerchantAccountType::Standard,
+ MerchantAccountType::Connected => {
if state.conf.platform.allow_connected_merchants {
MerchantAccountType::Connected
} else {
@@ -407,6 +544,14 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
.into());
}
}
+ MerchantAccountType::Platform => {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message:
+ "Only one Platform merchant account is allowed per Organization"
+ .to_string(),
+ }
+ .into());
+ }
}
}
}
@@ -4560,32 +4705,6 @@ async fn locker_recipient_create_call(
Ok(store_resp.card_reference)
}
-pub async fn enable_platform_account(
- state: SessionState,
- merchant_id: id_type::MerchantId,
-) -> RouterResponse<()> {
- let db = state.store.as_ref();
- let key_store = db
- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())
- .await
- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
-
- let merchant_account = db
- .find_merchant_account_by_merchant_id(&merchant_id, &key_store)
- .await
- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
-
- db.update_merchant(
- merchant_account,
- storage::MerchantAccountUpdate::ToPlatformAccount,
- &key_store,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while enabling platform merchant account")
- .map(|_| services::ApplicationResponse::StatusOk)
-}
-
impl From<&types::MerchantAccountData> for pm_auth_types::RecipientCreateRequest {
fn from(data: &types::MerchantAccountData) -> Self {
let (name, account_data) = match data {
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 12ebddccc5..33c0a2ab9c 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -116,6 +116,8 @@ pub enum UserErrors {
ErrorCloningConnector(String),
#[error("Invalid Embedded Operation : {0}")]
InvalidEmbeddedOperation(String),
+ #[error("Invalid Platform Operation")]
+ InvalidPlatformOperation,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -303,6 +305,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::InvalidEmbeddedOperation(_) => {
AER::BadRequest(ApiError::new(sub_code, 60, self.get_error_message(), None))
}
+ Self::InvalidPlatformOperation => {
+ AER::BadRequest(ApiError::new(sub_code, 61, self.get_error_message(), None))
+ }
}
}
}
@@ -382,6 +387,7 @@ impl UserErrors {
Self::InvalidEmbeddedOperation(error_message) => {
format!("Invalid Embedded Operation: {error_message}")
}
+ Self::InvalidPlatformOperation => "Invalid Platform Operation".to_string(),
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 6b9dea4000..c163cce25e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -22,9 +22,7 @@ use diesel_models::{
};
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
-#[cfg(feature = "email")]
-use router_env::env;
-use router_env::logger;
+use router_env::{env, logger};
use storage_impl::errors::StorageError;
#[cfg(not(feature = "email"))]
use user_api::dashboard_metadata::SetMetaDataRequest;
@@ -64,6 +62,16 @@ pub async fn signup_with_merchant_id(
auth_id: Option<String>,
theme_id: Option<String>,
) -> UserResponse<user_api::SignUpWithMerchantIdResponse> {
+ // Validate platform feature is enabled if Platform org requested
+ fp_utils::when(
+ request.organization_type == Some(common_enums::OrganizationType::Platform)
+ && !state.conf.platform.enabled,
+ || {
+ Err(report!(UserErrors::InvalidPlatformOperation)
+ .attach_printable("Platform feature is not enabled"))
+ },
+ )?;
+
let new_user = domain::NewUser::try_from(request.clone())?;
new_user
.get_new_merchant()
@@ -1688,6 +1696,10 @@ pub async fn create_platform_account(
user_from_token: auth::UserFromToken,
req: user_api::PlatformAccountCreateRequest,
) -> UserResponse<user_api::PlatformAccountCreateResponse> {
+ fp_utils::when(matches!(env::which(), env::Env::Production), || {
+ Err(report!(UserErrors::InvalidPlatformOperation))
+ })?;
+
let user_from_db = user_from_token.get_user_from_db(&state).await?;
let new_merchant = domain::NewUserMerchant::try_from(req)?;
@@ -1702,11 +1714,8 @@ pub async fn create_platform_account(
.accounts_store
.update_organization_by_org_id(
&organization.get_organization_id(),
- diesel_models::organization::OrganizationUpdate::Update {
- organization_name: None,
- organization_details: None,
- metadata: None,
- platform_merchant_id: Some(merchant_account.get_id().to_owned()),
+ diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {
+ platform_merchant_id: merchant_account.get_id().clone(),
},
)
.await
diff --git a/crates/router/src/db/organization.rs b/crates/router/src/db/organization.rs
index f809e6bb88..06e4ee834d 100644
--- a/crates/router/src/db/organization.rs
+++ b/crates/router/src/db/organization.rs
@@ -118,14 +118,22 @@ impl OrganizationInterface for super::MockDb {
organization_name,
organization_details,
metadata,
- platform_merchant_id,
} => {
organization_name
.as_ref()
.map(|org_name| org.set_organization_name(org_name.to_owned()));
organization_details.clone_into(&mut org.organization_details);
metadata.clone_into(&mut org.metadata);
- platform_merchant_id.clone_into(&mut org.platform_merchant_id);
+ org
+ }
+ storage::OrganizationUpdate::ConvertToPlatform => {
+ org.organization_type = Some(common_enums::OrganizationType::Platform);
+ org
+ }
+ storage::OrganizationUpdate::UpdatePlatformMerchant {
+ platform_merchant_id,
+ } => {
+ org.platform_merchant_id = Some(platform_merchant_id.clone());
org
}
})
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index f24635a2d0..c08f4bb528 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -178,6 +178,33 @@ pub async fn organization_retrieve(
.await
}
+#[cfg(all(feature = "olap", feature = "v1"))]
+#[instrument(skip_all, fields(flow = ?Flow::ConvertOrganizationToPlatform))]
+pub async fn convert_organization_to_platform(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ org_id: web::Path<common_utils::id_type::OrganizationId>,
+ json_payload: web::Json<admin::ConvertOrganizationToPlatformRequest>,
+) -> HttpResponse {
+ let flow = Flow::ConvertOrganizationToPlatform;
+ let organization_id = org_id.into_inner();
+ let org_id = admin::OrganizationId {
+ organization_id: organization_id.clone(),
+ };
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, _, req, _| {
+ convert_organization_to_platform_organization(state, org_id.clone(), req)
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))]
pub async fn merchant_account_create(
@@ -1052,26 +1079,3 @@ pub async fn merchant_account_transfer_keys(
))
.await
}
-
-/// Merchant Account - Platform Account
-///
-/// Enable platform account
-#[instrument(skip_all)]
-pub async fn merchant_account_enable_platform_account(
- state: web::Data<AppState>,
- req: HttpRequest,
- path: web::Path<common_utils::id_type::MerchantId>,
-) -> HttpResponse {
- let flow = Flow::EnablePlatformAccount;
- let merchant_id = path.into_inner();
- Box::pin(api::server_wrap(
- flow,
- state,
- &req,
- merchant_id,
- |state, _, req, _| enable_platform_account(state, req),
- &auth::AdminApiAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index a52fa6e1c3..1378855b83 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1860,9 +1860,16 @@ impl Organization {
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(admin::organization_create)))
.service(
- web::resource("/{id}")
- .route(web::get().to(admin::organization_retrieve))
- .route(web::put().to(admin::organization_update)),
+ web::scope("/{id}")
+ .service(
+ web::resource("")
+ .route(web::get().to(admin::organization_retrieve))
+ .route(web::put().to(admin::organization_update)),
+ )
+ .service(
+ web::resource("/convert_to_platform")
+ .route(web::post().to(admin::convert_organization_to_platform)),
+ ),
)
}
}
@@ -1918,7 +1925,7 @@ impl MerchantAccount {
#[cfg(all(feature = "olap", feature = "v1"))]
impl MerchantAccount {
pub fn server(state: AppState) -> Scope {
- let mut routes = web::scope("/accounts")
+ let routes = web::scope("/accounts")
.service(web::resource("").route(web::post().to(admin::merchant_account_create)))
.service(web::resource("/list").route(web::get().to(admin::merchant_account_list)))
.service(
@@ -1939,12 +1946,6 @@ impl MerchantAccount {
.route(web::post().to(admin::update_merchant_account))
.route(web::delete().to(admin::delete_merchant_account)),
);
- if state.conf.platform.enabled {
- routes = routes.service(
- web::resource("/{id}/platform")
- .route(web::post().to(admin::merchant_account_enable_platform_account)),
- )
- }
routes.app_data(web::Data::new(state))
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 4456e3a264..3242443311 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -63,9 +63,10 @@ impl From<Flow> for ApiIdentifier {
| Flow::MerchantTransferKey
| Flow::MerchantAccountList
| Flow::EnablePlatformAccount => Self::MerchantAccount,
- Flow::OrganizationCreate | Flow::OrganizationRetrieve | Flow::OrganizationUpdate => {
- Self::Organization
- }
+ Flow::OrganizationCreate
+ | Flow::OrganizationRetrieve
+ | Flow::OrganizationUpdate
+ | Flow::ConvertOrganizationToPlatform => Self::Organization,
Flow::RoutingCreateConfig
| Flow::RoutingLinkConfig
| Flow::RoutingUnlinkConfig
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 004b04f0c3..1016b464be 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -12,6 +12,7 @@ pub use api_models::{
ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails,
},
organization::{
+ ConvertOrganizationToPlatformRequest, ConvertOrganizationToPlatformResponse,
OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest,
},
};
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 6a1f4efdca..829a095a26 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -270,8 +270,9 @@ impl NewUserOrganization {
impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
+ let org_type = value.organization_type.unwrap_or_default();
let new_organization = api_org::OrganizationNew::new(
- common_enums::OrganizationType::Standard,
+ org_type,
Some(UserCompanyName::new(value.company_name)?.get_secret()),
);
let db_organization = ForeignFrom::foreign_from(new_organization);
@@ -417,7 +418,7 @@ pub struct NewUserMerchant {
company_name: Option<UserCompanyName>,
new_organization: NewUserOrganization,
product_type: Option<common_enums::MerchantProductType>,
- merchant_account_type: Option<common_enums::MerchantAccountRequestType>,
+ merchant_account_type: Option<common_enums::MerchantAccountType>,
}
impl TryFrom<UserCompanyName> for MerchantName {
@@ -671,12 +672,20 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant {
let merchant_id = MerchantId::new(value.company_name.clone())?;
let new_organization = NewUserOrganization::try_from(value)?;
let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);
+ let merchant_account_type = match new_organization.0.organization_type {
+ common_enums::OrganizationType::Platform => {
+ Some(common_enums::MerchantAccountType::Platform)
+ }
+ common_enums::OrganizationType::Standard => {
+ Some(common_enums::MerchantAccountType::Standard)
+ }
+ };
Ok(Self {
company_name,
merchant_id: id_type::MerchantId::try_from(merchant_id)?,
new_organization,
product_type,
- merchant_account_type: None,
+ merchant_account_type,
})
}
}
@@ -747,7 +756,7 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant {
user_merchant_create.company_name.clone(),
)?),
product_type: user_merchant_create.product_type,
- merchant_account_type: user_merchant_create.merchant_account_type,
+ merchant_account_type: user_merchant_create.merchant_account_type.map(Into::into),
new_organization: NewUserOrganization::from((
user_from_storage,
user_merchant_create,
@@ -867,6 +876,42 @@ impl NewUser {
self.new_merchant
.create_new_merchant_and_insert_in_db(state.clone())
.await?;
+
+ // If Platform org, update organization with platform_merchant_id
+ match self.new_merchant.new_organization.0.organization_type {
+ common_enums::OrganizationType::Platform => {
+ common_utils::fp_utils::when(
+ !matches!(
+ self.new_merchant.merchant_account_type,
+ Some(common_enums::MerchantAccountType::Platform)
+ ),
+ || {
+ Err(
+ report!(UserErrors::InvalidPlatformOperation).attach_printable(
+ "Merchant account type must be Platform for Platform organization",
+ ),
+ )
+ },
+ )?;
+
+ let org_update =
+ diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {
+ platform_merchant_id: merchant_id.clone(),
+ };
+
+ state
+ .accounts_store
+ .update_organization_by_org_id(
+ &self.new_merchant.new_organization.get_organization_id(),
+ org_update,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to update organization with platform_merchant_id")?;
+ }
+ common_enums::OrganizationType::Standard => {}
+ }
+
let created_user = self.insert_user_in_db(db).await;
if created_user.is_err() {
let _ = admin::merchant_account_delete(state, merchant_id).await;
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b28c16df7d..1927cdd0f4 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -401,6 +401,8 @@ pub enum Flow {
UserSignUp,
/// User Sign Up
UserSignUpWithMerchantId,
+ /// Convert Organization to Platform
+ ConvertOrganizationToPlatform,
/// User Sign In
UserSignIn,
/// User transfer key