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

fix(core): Merchant Category Code Enum to strict Struct (#10423)

Nithin N2c9e6307ff13
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index fd853c8c24..f65a4f9f25 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -21465,15 +21465,8 @@
},
"MerchantCategoryCode": {
"type": "string",
- "enum": [
- "5411",
- "7011",
- "0763",
- "8111",
- "5021",
- "4816",
- "5661"
- ]
+ "title": "4 digit Merchant category code (MCC)",
+ "example": "5411"
},
"MerchantConnectorAccountId": {
"type": "string",
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 81f4c52adf..9b4fca56c0 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -14743,15 +14743,8 @@
},
"MerchantCategoryCode": {
"type": "string",
- "enum": [
- "5411",
- "7011",
- "0763",
- "8111",
- "5021",
- "4816",
- "5661"
- ]
+ "title": "4 digit Merchant category code (MCC)",
+ "example": "5411"
},
"MerchantConnectorAccountFeatureMetadata": {
"type": "object",
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 5d560e754b..9a53266c3c 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3,14 +3,23 @@ mod payments;
mod ui;
use std::{
collections::HashSet,
+ fmt,
num::{ParseFloatError, TryFromIntError},
+ str::FromStr,
};
pub use accounts::{
MerchantAccountRequestType, MerchantAccountType, MerchantProductType, OrganizationType,
};
+use diesel::{
+ backend::Backend,
+ deserialize::FromSql,
+ expression::AsExpression,
+ serialize::{Output, ToSql},
+ sql_types::Text,
+};
pub use payments::ProductType;
-use serde::{Deserialize, Serialize};
+use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use smithy::SmithyModel;
pub use ui::*;
use utoipa::ToSchema;
@@ -3081,96 +3090,147 @@ pub enum DisputeStatus {
DisputeLost,
}
-#[derive(
- Clone,
- Copy,
- Debug,
- Eq,
- Hash,
- PartialEq,
- serde::Deserialize,
- serde::Serialize,
- strum::Display,
- strum::EnumString,
- strum::EnumIter,
- strum::VariantNames,
- ToSchema,
+#[derive(Debug, Clone, AsExpression, PartialEq, ToSchema)]
+#[schema(
+ value_type = String,
+ title = "4 digit Merchant category code (MCC)",
+ example = "5411"
)]
-pub enum MerchantCategory {
- #[serde(rename = "Grocery Stores, Supermarkets (5411)")]
- GroceryStoresSupermarkets,
- #[serde(rename = "Lodging-Hotels, Motels, Resorts-not elsewhere classified (7011)")]
- LodgingHotelsMotelsResorts,
- #[serde(rename = "Agricultural Cooperatives (0763)")]
- AgriculturalCooperatives,
- #[serde(rename = "Attorneys, Legal Services (8111)")]
- AttorneysLegalServices,
- #[serde(rename = "Office and Commercial Furniture (5021)")]
- OfficeAndCommercialFurniture,
- #[serde(rename = "Computer Network/Information Services (4816)")]
- ComputerNetworkInformationServices,
- #[serde(rename = "Shoe Stores (5661)")]
- ShoeStores,
+#[diesel(sql_type = Text)]
+pub struct MerchantCategoryCode(String);
+
+impl MerchantCategoryCode {
+ pub fn get_code(&self) -> Result<u16, InvalidMccError> {
+ // since self.0 is private field we can safely ensure self.0 is string "0001"-"9999"
+ self.0.parse::<u16>().map_err(|_| InvalidMccError {
+ message: "Invalid MCC code found".to_string(),
+ })
+ }
+
+ pub fn new(code: u16) -> Result<Self, InvalidMccError> {
+ if code >= 10000 {
+ return Err(InvalidMccError {
+ message: "MCC should be in range 0001 to 9999".to_string(),
+ });
+ }
+ let formatted = format!("{code:04}");
+
+ Ok(Self(formatted))
+ }
+
+ pub fn get_category_name(&self) -> Result<&str, InvalidMccError> {
+ let code = self.get_code()?;
+ match code {
+ // specific mapping needs to be depricated
+ 5411 => Ok("Grocery Stores, Supermarkets (5411)"),
+ 7011 => Ok("Lodging-Hotels, Motels, Resorts-not elsewhere classified (7011)"),
+ 763 => Ok("Agricultural Cooperatives (0763)"),
+ 8111 => Ok("Attorneys, Legal Services (8111)"),
+ 5021 => Ok("Office and Commercial Furniture (5021)"),
+ 4816 => Ok("Computer Network/Information Services (4816)"),
+ 5661 => Ok("Shoe Stores (5661)"),
+
+ _ => Err(InvalidMccError {
+ message: format!("Category name not found for {}", code),
+ }),
+ }
+ }
+
+ /// Returns a reference to the 4-digit zero-padded code string.
+ pub fn get_string_code(&self) -> &str {
+ &self.0
+ }
}
-#[derive(
- Clone,
- Copy,
- Debug,
- Eq,
- Hash,
- PartialEq,
- serde::Deserialize,
- serde::Serialize,
- strum::Display,
- strum::EnumString,
- strum::EnumIter,
- strum::VariantNames,
- ToSchema,
-)]
-#[router_derive::diesel_enum(storage_type = "text")]
-pub enum MerchantCategoryCode {
- #[serde(rename = "5411")]
- #[strum(serialize = "5411")]
- Mcc5411,
- #[serde(rename = "7011")]
- #[strum(serialize = "7011")]
- Mcc7011,
- #[serde(rename = "0763")]
- #[strum(serialize = "0763")]
- Mcc0763,
- #[serde(rename = "8111")]
- #[strum(serialize = "8111")]
- Mcc8111,
- #[serde(rename = "5021")]
- #[strum(serialize = "5021")]
- Mcc5021,
- #[serde(rename = "4816")]
- #[strum(serialize = "4816")]
- Mcc4816,
- #[serde(rename = "5661")]
- #[strum(serialize = "5661")]
- Mcc5661,
+impl<DB> ToSql<Text, DB> for MerchantCategoryCode
+where
+ DB: Backend,
+ String: ToSql<Text, DB>,
+{
+ fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
+ self.0.to_sql(out)
+ }
}
+impl<DB: Backend> FromSql<Text, DB> for MerchantCategoryCode
+where
+ String: FromSql<Text, DB>,
+{
+ fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
+ let code = <String as FromSql<Text, DB>>::from_sql(bytes)?;
-impl MerchantCategoryCode {
- pub fn to_merchant_category_name(&self) -> MerchantCategory {
- match self {
- Self::Mcc5411 => MerchantCategory::GroceryStoresSupermarkets,
- Self::Mcc7011 => MerchantCategory::LodgingHotelsMotelsResorts,
- Self::Mcc0763 => MerchantCategory::AgriculturalCooperatives,
- Self::Mcc8111 => MerchantCategory::AttorneysLegalServices,
- Self::Mcc5021 => MerchantCategory::OfficeAndCommercialFurniture,
- Self::Mcc4816 => MerchantCategory::ComputerNetworkInformationServices,
- Self::Mcc5661 => MerchantCategory::ShoeStores,
+ Self::from_str(&code).map_err(Into::into)
+ }
+}
+
+impl Serialize for MerchantCategoryCode {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_str(&self.0)
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct InvalidMccError {
+ pub message: String,
+}
+
+impl fmt::Display for InvalidMccError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "Invalid MCC: {}", self.message)
+ }
+}
+
+impl std::error::Error for InvalidMccError {}
+
+impl From<std::num::ParseIntError> for InvalidMccError {
+ fn from(err: std::num::ParseIntError) -> Self {
+ Self {
+ message: format!("MCC must be a number: {}", err),
}
}
}
+impl FromStr for MerchantCategoryCode {
+ type Err = InvalidMccError;
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let _code: u16 = s.parse()?;
+
+ if s.len() != 4 {
+ return Err(InvalidMccError {
+ message: format!(
+ "MCC must be exactly 4 characters long (e.g., '0001'), but got '{}'",
+ s
+ ),
+ });
+ }
+ Ok(Self(s.to_string()))
+ }
+}
+
+impl<'de> Deserialize<'de> for MerchantCategoryCode {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let code = String::deserialize(deserializer)?;
+
+ Self::from_str(&code).map_err(de::Error::custom)
+ }
+}
+
+impl fmt::Display for MerchantCategoryCode {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ // Format as a zero-padded 4-digit string, which matches the expected enum serialization.
+ write!(f, "{:04}", self.0)
+ }
+}
+
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct MerchantCategoryCodeWithName {
pub code: MerchantCategoryCode,
- pub name: MerchantCategory,
+ pub name: String,
}
#[derive(
diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs
index 8050f3693f..b8ab8478b0 100644
--- a/crates/euclid_wasm/src/lib.rs
+++ b/crates/euclid_wasm/src/lib.rs
@@ -50,6 +50,15 @@ struct SeedData {
static SEED_DATA: OnceLock<SeedData> = OnceLock::new();
static SEED_FOREX: OnceLock<currency_conversion_types::ExchangeRates> = OnceLock::new();
+#[wasm_bindgen]
+extern "C" {
+ #[wasm_bindgen(js_namespace = console, js_name = log)]
+ fn console_log(s: &str);
+
+ #[wasm_bindgen(js_namespace = console, js_name = error)]
+ fn console_error(s: &str);
+}
+
/// This function can be used by the frontend to educate wasm about the forex rates data.
/// The input argument is a struct fields base_currency and conversion where later is all the conversions associated with the base_currency
/// to all different currencies present.
@@ -100,10 +109,29 @@ pub fn get_two_letter_country_code() -> JsResult {
/// along with their names.
#[wasm_bindgen(js_name=getMerchantCategoryCodeWithName)]
pub fn get_merchant_category_code_with_name() -> JsResult {
- let merchant_category_codes_with_name = MerchantCategoryCode::iter()
- .map(|mcc_value| MerchantCategoryCodeWithName {
- code: mcc_value,
- name: mcc_value.to_merchant_category_name(),
+ let merchant_category_codes_with_name = vec![5411, 7011, 763, 8111, 5021, 4816, 5661]
+ .into_iter()
+ .filter_map(|mcc_value| match MerchantCategoryCode::new(mcc_value) {
+ Ok(mcc) => match mcc.get_category_name() {
+ Ok(mcc_name) => Some(MerchantCategoryCodeWithName {
+ code: mcc.clone(),
+ name: mcc_name.to_string(),
+ }),
+ Err(err) => {
+ console_error(&format!(
+ "Failed to get category name for MCC {}: {:?}",
+ mcc_value, err
+ ));
+ None
+ }
+ },
+ Err(err) => {
+ console_error(&format!(
+ "Failed to create MCC for value {}: {:?}",
+ mcc_value, err
+ ));
+ None
+ }
})
.collect::<Vec<_>>();
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 78849ba5bb..4da89b20a4 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1463,7 +1463,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
let merchant_details = Some(unified_authentication_service::MerchantDetails {
merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),
merchant_name: acquirer_configs.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),
- merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),
+ merchant_category_code: business_profile.merchant_category_code.clone().or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),
endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix),
three_ds_requestor_url: business_profile.authentication_connector_details.clone().map(|details| details.three_ds_requestor_url),
three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),