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(dashboard): implement saved views to store frequently used payment filters (#11447)
Venu Madhav Bandarupalli766281e3c1c3
diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rsindex 0f728fcaf3..b6c7f5532d 100644--- a/crates/api_models/src/user/dashboard_metadata.rs+++ b/crates/api_models/src/user/dashboard_metadata.rs@@ -4,6 +4,9 @@ use common_utils::{id_type, pii};use hyperswitch_masking::Secret;use strum::EnumString;+#[cfg(feature = "v1")]+use crate::{enums, payments};+#[derive(Debug, serde::Deserialize, serde::Serialize)]pub enum SetMetaDataRequest {ProductionAgreement(ProductionAgreementRequest),@@ -29,6 +32,17 @@ pub enum SetMetaDataRequest {IsChangePasswordRequired,OnboardingSurvey(OnboardingSurvey),ReconStatus(ReconStatus),+ #[cfg(feature = "v1")]+ PaymentViews(SavedViewOperation),+}++#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+#[serde(tag = "type", content = "data")]+pub enum SavedViewOperation {+ Create(CreateSavedViewRequest),+ Update(UpdateSavedViewRequest),+ Delete(DeleteSavedViewRequest),}#[derive(Debug, serde::Deserialize, serde::Serialize)]@@ -141,6 +155,8 @@ pub enum GetMetaDataRequest {IsChangePasswordRequired,OnboardingSurvey,ReconStatus,+ #[cfg(feature = "v1")]+ PaymentViews,}#[derive(Debug, serde::Deserialize, serde::Serialize)]@@ -180,4 +196,84 @@ pub enum GetMetaDataResponse {IsChangePasswordRequired(bool),OnboardingSurvey(Option<OnboardingSurvey>),ReconStatus(Option<ReconStatus>),+ #[cfg(feature = "v1")]+ PaymentViews(Option<Vec<SavedViewResponse>>),+}++// === Saved Views API Types ===++#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]+#[serde(tag = "entity", content = "filters")]+#[serde(rename_all = "snake_case")]+pub enum SavedViewFiltersV1 {+ PaymentViews(PaymentListFilterConstraintsV1),+}++#[cfg(feature = "v1")]+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]+pub struct PaymentListFilterConstraintsV1 {+ pub payment_id: Option<id_type::PaymentId>,+ pub profile_id: Option<id_type::ProfileId>,+ pub customer_id: Option<id_type::CustomerId>,+ #[serde(default = "common_utils::consts::default_payments_list_limit")]+ pub limit: u32,+ pub offset: Option<u32>,+ pub amount_filter: Option<payments::AmountFilter>,+ #[serde(flatten)]+ pub time_range: Option<common_utils::types::TimeRange>,+ pub connector: Option<Vec<enums::Connector>>,+ pub currency: Option<Vec<enums::Currency>>,+ pub status: Option<Vec<enums::IntentStatus>>,+ pub payment_method: Option<Vec<enums::PaymentMethod>>,+ pub payment_method_type: Option<Vec<enums::PaymentMethodType>>,+ pub authentication_type: Option<Vec<enums::AuthenticationType>>,+ pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,+ #[serde(default)]+ pub order: payments::Order,+ pub card_network: Option<Vec<enums::CardNetwork>>,+ pub merchant_order_reference_id: Option<String>,+ pub card_discovery: Option<Vec<enums::CardDiscovery>>,+ pub customer_email: Option<pii::Email>,+}++#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+#[serde(tag = "version", rename_all = "snake_case")]+pub enum SavedViewFilters {+ V1(SavedViewFiltersV1),+}++#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct SavedViewResponse {+ pub view_id: String,+ pub view_name: String,+ pub data: SavedViewFilters,+ pub created_at: String,+ pub updated_at: String,+}+/// POST /user/views+#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct CreateSavedViewRequest {+ pub view_name: String,+ #[serde(flatten)]+ pub data: SavedViewFilters,+}++/// PUT /user/views+#[cfg(feature = "v1")]+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct UpdateSavedViewRequest {+ pub view_id: String,+ pub view_name: Option<String>,+ #[serde(flatten)]+ pub data: SavedViewFilters,+}++/// DELETE /user/views+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct DeleteSavedViewRequest {+ pub view_id: String,}diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rsindex 79e7a05695..d1dfdabbbe 100644--- a/crates/diesel_models/src/enums.rs+++ b/crates/diesel_models/src/enums.rs@@ -237,6 +237,8 @@ pub enum DashboardMetadata {IsChangePasswordRequired,OnboardingSurvey,ReconStatus,+ #[cfg(feature = "v1")]+ PaymentViews,}#[derive(diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rsindex 122bd5582a..8d39618134 100644--- a/crates/diesel_models/src/query/dashboard_metadata.rs+++ b/crates/diesel_models/src/query/dashboard_metadata.rs@@ -1,5 +1,6 @@use common_utils::id_type;use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+use error_stack::{report, ResultExt};use crate::{enums, errors,@@ -12,6 +13,49 @@ use crate::{PgPooledConn, StorageResult,};+macro_rules! dashboard_metadata_filter {+ ($user_id:expr, $profile_id:expr, $merchant_id:expr, $org_id:expr, $data_key:expr, $predicate:ident, $action:block) => {+ match ($user_id, $profile_id) {+ (Some(uid), Some(pid)) => {+ let $predicate = dsl::user_id+ .eq(uid.to_owned())+ .and(dsl::profile_id.eq(pid.to_owned()))+ .and(dsl::merchant_id.eq($merchant_id.to_owned()))+ .and(dsl::org_id.eq($org_id.to_owned()))+ .and(dsl::data_key.eq($data_key));+ $action+ }+ (Some(uid), None) => {+ let $predicate = dsl::user_id+ .eq(uid.to_owned())+ .and(dsl::profile_id.is_null())+ .and(dsl::merchant_id.eq($merchant_id.to_owned()))+ .and(dsl::org_id.eq($org_id.to_owned()))+ .and(dsl::data_key.eq($data_key));+ $action+ }+ (None, Some(pid)) => {+ let $predicate = dsl::user_id+ .is_null()+ .and(dsl::profile_id.eq(pid.to_owned()))+ .and(dsl::merchant_id.eq($merchant_id.to_owned()))+ .and(dsl::org_id.eq($org_id.to_owned()))+ .and(dsl::data_key.eq($data_key));+ $action+ }+ (None, None) => {+ let $predicate = dsl::user_id+ .is_null()+ .and(dsl::profile_id.is_null())+ .and(dsl::merchant_id.eq($merchant_id.to_owned()))+ .and(dsl::org_id.eq($org_id.to_owned()))+ .and(dsl::data_key.eq($data_key));+ $action+ }+ }+ };+}+impl DashboardMetadataNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DashboardMetadata> {generics::generic_insert(conn, self).await@@ -24,39 +68,34 @@ impl DashboardMetadata {user_id: Option<String>,merchant_id: id_type::MerchantId,org_id: id_type::OrganizationId,+ profile_id: Option<String>,data_key: enums::DashboardMetadata,dashboard_metadata_update: DashboardMetadataUpdate,) -> StorageResult<Self> {- let predicate = dsl::merchant_id- .eq(merchant_id.to_owned())- .and(dsl::org_id.eq(org_id.to_owned()))- .and(dsl::data_key.eq(data_key.to_owned()));+ let changeset = DashboardMetadataUpdateInternal::from(dashboard_metadata_update);- if let Some(uid) = user_id {- generics::generic_update_with_unique_predicate_get_result::<- <Self as HasTable>::Table,- _,- _,- _,- >(- conn,- predicate.and(dsl::user_id.eq(uid)),- DashboardMetadataUpdateInternal::from(dashboard_metadata_update),- )- .await- } else {- generics::generic_update_with_unique_predicate_get_result::<- <Self as HasTable>::Table,- _,- _,- _,- >(- conn,- predicate.and(dsl::user_id.is_null()),- DashboardMetadataUpdateInternal::from(dashboard_metadata_update),- )- .await- }+ dashboard_metadata_filter!(+ user_id.as_ref(),+ profile_id.as_ref(),+ merchant_id,+ org_id,+ data_key,+ predicate,+ {+ generics::generic_update_with_unique_predicate_get_result::<+ <Self as HasTable>::Table,+ _,+ _,+ _,+ >(conn, predicate, changeset)+ .await+ .map_err(|e| match e.current_context() {+ errors::DatabaseError::NotFound => report!(errors::DatabaseError::NotFound),+ _ => e,+ })+ .attach_printable("Error while updating dashboard metadata")+ }+ )}pub async fn find_user_scoped_dashboard_metadata(@@ -103,6 +142,30 @@ impl DashboardMetadata {.await}+ pub async fn find_dashboard_metadata_by_user_merchant_org_profile_key(+ conn: &PgPooledConn,+ user_id: String,+ merchant_id: id_type::MerchantId,+ org_id: id_type::OrganizationId,+ profile_id: Option<String>,+ data_key: enums::DashboardMetadata,+ ) -> StorageResult<Option<Self>> {+ dashboard_metadata_filter!(+ Some(&user_id),+ profile_id.as_ref(),+ merchant_id,+ org_id,+ data_key,+ predicate,+ {+ generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(+ conn, predicate,+ )+ .await+ }+ )+ }+pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(conn: &PgPooledConn,user_id: String,diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 4e5bece420..9607eb64f3 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -465,6 +465,8 @@ diesel::table! {#[max_length = 64]last_modified_by -> Varchar,last_modified_at -> Timestamp,+ #[max_length = 64]+ profile_id -> Nullable<Varchar>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex c8f51990f9..b215e50fae 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -476,6 +476,8 @@ diesel::table! {#[max_length = 64]last_modified_by -> Varchar,last_modified_at -> Timestamp,+ #[max_length = 64]+ profile_id -> Nullable<Varchar>,}}diff --git a/crates/diesel_models/src/user/dashboard_metadata.rs b/crates/diesel_models/src/user/dashboard_metadata.rsindex 4bd01dab0e..913f8af595 100644--- a/crates/diesel_models/src/user/dashboard_metadata.rs+++ b/crates/diesel_models/src/user/dashboard_metadata.rs@@ -18,6 +18,7 @@ pub struct DashboardMetadata {pub created_at: PrimitiveDateTime,pub last_modified_by: String,pub last_modified_at: PrimitiveDateTime,+ pub profile_id: Option<String>,}#[derive(@@ -34,6 +35,7 @@ pub struct DashboardMetadataNew {pub created_at: PrimitiveDateTime,pub last_modified_by: String,pub last_modified_at: PrimitiveDateTime,+ pub profile_id: Option<String>,}#[derive(diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rsindex 33c0a2ab9c..ed60343cfb 100644--- a/crates/router/src/core/errors/user.rs+++ b/crates/router/src/core/errors/user.rs@@ -118,6 +118,14 @@ pub enum UserErrors {InvalidEmbeddedOperation(String),#[error("Invalid Platform Operation")]InvalidPlatformOperation,+ #[error("MaxSavedViewsReached")]+ MaxSavedViewsReached,+ #[error("SavedViewNameAlreadyExists")]+ SavedViewNameAlreadyExists,+ #[error("SavedViewNotFound")]+ SavedViewNotFound,+ #[error("InvalidSavedViewName")]+ InvalidSavedViewName,}impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {@@ -308,6 +316,18 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponSelf::InvalidPlatformOperation => {AER::BadRequest(ApiError::new(sub_code, 61, self.get_error_message(), None))}+ Self::MaxSavedViewsReached => {+ AER::BadRequest(ApiError::new(sub_code, 62, self.get_error_message(), None))+ }+ Self::SavedViewNameAlreadyExists => {+ AER::BadRequest(ApiError::new(sub_code, 63, self.get_error_message(), None))+ }+ Self::SavedViewNotFound => {+ AER::NotFound(ApiError::new(sub_code, 64, self.get_error_message(), None))+ }+ Self::InvalidSavedViewName => {+ AER::BadRequest(ApiError::new(sub_code, 65, self.get_error_message(), None))+ }}}}@@ -388,6 +408,16 @@ impl UserErrors {format!("Invalid Embedded Operation: {error_message}")}Self::InvalidPlatformOperation => "Invalid Platform Operation".to_string(),+ Self::MaxSavedViewsReached => {+ "Maximum number of saved views reached (limit: 5)".to_string()+ }+ Self::SavedViewNameAlreadyExists => {+ "A saved view with this name already exists".to_string()+ }+ Self::SavedViewNotFound => "Saved view not found".to_string(),+ Self::InvalidSavedViewName => {+ "The saved view name cannot be empty or contain only whitespace".to_string()+ }}}}diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rsindex cee4f0b180..9b3ff2a55e 100644--- a/crates/router/src/core/user/dashboard_metadata.rs+++ b/crates/router/src/core/user/dashboard_metadata.rs@@ -119,6 +119,10 @@ fn parse_set_request(data_enum: api::SetMetaDataRequest) -> UserResult<types::MeOk(types::MetaData::OnboardingSurvey(req))}api::SetMetaDataRequest::ReconStatus(req) => Ok(types::MetaData::ReconStatus(req)),+ #[cfg(feature = "v1")]+ api::SetMetaDataRequest::PaymentViews(operation) => {+ Ok(types::MetaData::PaymentViews(operation))+ }}}@@ -148,6 +152,8 @@ fn parse_get_request(data_enum: api::GetMetaDataRequest) -> DBEnum {api::GetMetaDataRequest::IsChangePasswordRequired => DBEnum::IsChangePasswordRequired,api::GetMetaDataRequest::OnboardingSurvey => DBEnum::OnboardingSurvey,api::GetMetaDataRequest::ReconStatus => DBEnum::ReconStatus,+ #[cfg(feature = "v1")]+ api::GetMetaDataRequest::PaymentViews => DBEnum::PaymentViews,}}@@ -235,6 +241,24 @@ fn into_response(let resp = utils::deserialize_to_response(data)?;Ok(api::GetMetaDataResponse::ReconStatus(resp))}+ #[cfg(feature = "v1")]+ DBEnum::PaymentViews => {+ let resp: Option<types::PaymentViewsValue> = utils::deserialize_to_response(data)?;+ Ok(api::GetMetaDataResponse::PaymentViews(resp.map(|d| {+ d.views+ .into_iter()+ .map(|v| api::SavedViewResponse {+ view_id: v.view_id,+ view_name: v.view_name,+ data: api::SavedViewFilters::V1(api::SavedViewFiltersV1::PaymentViews(+ v.filters,+ )),+ created_at: v.created_at.to_string(),+ updated_at: v.updated_at.to_string(),+ })+ .collect()+ })))+ }}}@@ -655,6 +679,10 @@ async fn insert_metadata(}metadata}+ #[cfg(feature = "v1")]+ types::MetaData::PaymentViews(operation) => {+ utils::handle_saved_view_operations(state, user, metadata_key, operation).await+ }}}@@ -664,7 +692,7 @@ async fn fetch_metadata(metadata_keys: Vec<DBEnum>,) -> UserResult<Vec<DashboardMetadata>> {let mut dashboard_metadata = Vec::with_capacity(metadata_keys.len());- let (merchant_scoped_enums, user_scoped_enums) =+ let (merchant_scoped_enums, user_scoped_enums, profile_user_scoped_enums) =utils::separate_metadata_type_based_on_scope(metadata_keys);if !merchant_scoped_enums.is_empty() {@@ -690,6 +718,20 @@ async fn fetch_metadata(dashboard_metadata.append(&mut res);}+ if !profile_user_scoped_enums.is_empty() {+ let profile_id = utils::get_profile_id_from_role(state, user).await?;+ let mut res = utils::get_profile_user_scoped_metadata_from_db(+ state,+ user.user_id.to_owned(),+ user.merchant_id.to_owned(),+ user.org_id.to_owned(),+ profile_id,+ profile_user_scoped_enums,+ )+ .await?;+ dashboard_metadata.append(&mut res);+ }+Ok(dashboard_metadata)}diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rsindex dbd8f21471..af0e9d14fb 100644--- a/crates/router/src/db/dashboard_metadata.rs+++ b/crates/router/src/db/dashboard_metadata.rs@@ -22,6 +22,7 @@ pub trait DashboardMetadataInterface {user_id: Option<String>,merchant_id: id_type::MerchantId,org_id: id_type::OrganizationId,+ profile_id: Option<String>,data_key: enums::DashboardMetadata,dashboard_metadata_update: storage::DashboardMetadataUpdate,) -> CustomResult<storage::DashboardMetadata, errors::StorageError>;@@ -41,6 +42,15 @@ pub trait DashboardMetadataInterface {data_keys: Vec<enums::DashboardMetadata>,) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>;+ async fn find_profile_scoped_dashboard_metadata(+ &self,+ user_id: &str,+ merchant_id: &id_type::MerchantId,+ org_id: &id_type::OrganizationId,+ profile_id: Option<String>,+ data_key: enums::DashboardMetadata,+ ) -> CustomResult<Option<storage::DashboardMetadata>, errors::StorageError>;+async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(&self,user_id: &str,@@ -80,6 +90,7 @@ impl DashboardMetadataInterface for Store {user_id: Option<String>,merchant_id: id_type::MerchantId,org_id: id_type::OrganizationId,+ profile_id: Option<String>,data_key: enums::DashboardMetadata,dashboard_metadata_update: storage::DashboardMetadataUpdate,) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {@@ -89,6 +100,7 @@ impl DashboardMetadataInterface for Store {user_id,merchant_id,org_id,+ profile_id,data_key,dashboard_metadata_update,)@@ -134,6 +146,28 @@ impl DashboardMetadataInterface for Store {.map_err(|error| report!(errors::StorageError::from(error)))}+ #[instrument(skip_all)]+ async fn find_profile_scoped_dashboard_metadata(+ &self,+ user_id: &str,+ merchant_id: &id_type::MerchantId,+ org_id: &id_type::OrganizationId,+ profile_id: Option<String>,+ data_key: enums::DashboardMetadata,+ ) -> CustomResult<Option<storage::DashboardMetadata>, errors::StorageError> {+ let conn = connection::pg_accounts_connection_read(self).await?;+ storage::DashboardMetadata::find_dashboard_metadata_by_user_merchant_org_profile_key(+ &conn,+ user_id.to_owned(),+ merchant_id.to_owned(),+ org_id.to_owned(),+ profile_id,+ data_key,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[instrument(skip_all)]async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(&self,@@ -192,9 +226,10 @@ impl DashboardMetadataInterface for MockDb {&& metadata_inner.merchant_id == metadata.merchant_id&& metadata_inner.org_id == metadata.org_id&& metadata_inner.data_key == metadata.data_key+ && metadata_inner.profile_id == metadata.profile_id}) {Err(errors::StorageError::DuplicateValue {- entity: "user_id, merchant_id, org_id and data_key",+ entity: "user_id, merchant_id, org_id, profile_id and data_key",key: None,})?}@@ -210,6 +245,7 @@ impl DashboardMetadataInterface for MockDb {created_at: metadata.created_at,last_modified_by: metadata.last_modified_by,last_modified_at: metadata.last_modified_at,+ profile_id: metadata.profile_id,};dashboard_metadata.push(metadata_new.clone());Ok(metadata_new)@@ -220,6 +256,7 @@ impl DashboardMetadataInterface for MockDb {user_id: Option<String>,merchant_id: id_type::MerchantId,org_id: id_type::OrganizationId,+ profile_id: Option<String>,data_key: enums::DashboardMetadata,dashboard_metadata_update: storage::DashboardMetadataUpdate,) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {@@ -232,6 +269,7 @@ impl DashboardMetadataInterface for MockDb {&& metadata.merchant_id == merchant_id&& metadata.org_id == org_id&& metadata.data_key == data_key+ && metadata.profile_id == profile_id}).ok_or(errors::StorageError::MockDbError)?;@@ -309,6 +347,33 @@ impl DashboardMetadataInterface for MockDb {}Ok(query_result)}++ async fn find_profile_scoped_dashboard_metadata(+ &self,+ user_id: &str,+ merchant_id: &id_type::MerchantId,+ org_id: &id_type::OrganizationId,+ profile_id: Option<String>,+ data_key: enums::DashboardMetadata,+ ) -> CustomResult<Option<storage::DashboardMetadata>, errors::StorageError> {+ let dashboard_metadata = self.dashboard_metadata.lock().await;+ let result = dashboard_metadata+ .iter()+ .find(|metadata_inner| {+ metadata_inner+ .user_id+ .as_deref()+ .map(|uid| uid == user_id)+ .unwrap_or(false)+ && metadata_inner.merchant_id == *merchant_id+ && metadata_inner.org_id == *org_id+ && metadata_inner.profile_id == profile_id+ && metadata_inner.data_key == data_key+ })+ .cloned();+ Ok(result)+ }+async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(&self,user_id: &str,diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 84edea9482..5f8d616a94 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -3614,6 +3614,7 @@ impl DashboardMetadataInterface for KafkaStore {user_id: Option<String>,merchant_id: id_type::MerchantId,org_id: id_type::OrganizationId,+ profile_id: Option<String>,data_key: enums::DashboardMetadata,dashboard_metadata_update: storage::DashboardMetadataUpdate,) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {@@ -3622,6 +3623,7 @@ impl DashboardMetadataInterface for KafkaStore {user_id,merchant_id,org_id,+ profile_id,data_key,dashboard_metadata_update,)@@ -3651,6 +3653,25 @@ impl DashboardMetadataInterface for KafkaStore {.await}+ async fn find_profile_scoped_dashboard_metadata(+ &self,+ user_id: &str,+ merchant_id: &id_type::MerchantId,+ org_id: &id_type::OrganizationId,+ profile_id: Option<String>,+ data_key: enums::DashboardMetadata,+ ) -> CustomResult<Option<storage::DashboardMetadata>, errors::StorageError> {+ self.diesel_store+ .find_profile_scoped_dashboard_metadata(+ user_id,+ merchant_id,+ org_id,+ profile_id,+ data_key,+ )+ .await+ }+async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(&self,user_id: &str,diff --git a/crates/router/src/types/domain/user/dashboard_metadata.rs b/crates/router/src/types/domain/user/dashboard_metadata.rsindex 6e2e74310d..05d7327832 100644--- a/crates/router/src/types/domain/user/dashboard_metadata.rs+++ b/crates/router/src/types/domain/user/dashboard_metadata.rs@@ -3,6 +3,7 @@ use diesel_models::enums::DashboardMetadata as DBEnum;use hyperswitch_masking::Secret;use time::PrimitiveDateTime;+#[derive(Debug, serde::Serialize, serde::Deserialize)]pub enum MetaData {ProductionAgreement(ProductionAgreementValue),SetupProcessor(api::SetupProcessor),@@ -28,6 +29,8 @@ pub enum MetaData {IsChangePasswordRequired(bool),OnboardingSurvey(api::OnboardingSurvey),ReconStatus(api::ReconStatus),+ #[cfg(feature = "v1")]+ PaymentViews(api::SavedViewOperation),}impl From<&MetaData> for DBEnum {@@ -57,12 +60,31 @@ impl From<&MetaData> for DBEnum {MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired,MetaData::OnboardingSurvey(_) => Self::OnboardingSurvey,MetaData::ReconStatus(_) => Self::ReconStatus,+ #[cfg(feature = "v1")]+ MetaData::PaymentViews(_) => Self::PaymentViews,}}}-#[derive(Debug, serde::Serialize)]++#[derive(Debug, serde::Serialize, serde::Deserialize)]pub struct ProductionAgreementValue {pub version: String,pub ip_address: Secret<String, common_utils::pii::IpAddress>,pub timestamp: PrimitiveDateTime,}++#[cfg(feature = "v1")]+#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub struct SavedViewV1 {+ pub view_id: String,+ pub view_name: String,+ pub filters: api::PaymentListFilterConstraintsV1,+ pub created_at: String,+ pub updated_at: String,+}++#[cfg(feature = "v1")]+#[derive(Debug, serde::Serialize, serde::Deserialize)]+pub struct PaymentViewsValue {+ pub views: Vec<SavedViewV1>,+}diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rsindex 40286ee6ca..bd0c471575 100644--- a/crates/router/src/utils/user/dashboard_metadata.rs+++ b/crates/router/src/utils/user/dashboard_metadata.rs@@ -2,8 +2,18 @@ use std::{net::IpAddr, ops::Not, str::FromStr};use actix_web::http::header::HeaderMap;use api_models::user::dashboard_metadata::{- GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest,+ DeleteSavedViewRequest, GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent,+ SetMetaDataRequest,};+#[cfg(feature = "v1")]+use api_models::{+ payments,+ user::dashboard_metadata::{+ CreateSavedViewRequest, PaymentListFilterConstraintsV1, SavedViewFilters,+ SavedViewFiltersV1, SavedViewOperation, UpdateSavedViewRequest,+ },+};+use common_enums::EntityType;use common_utils::id_type;use diesel_models::{enums::DashboardMetadata as DBEnum,@@ -15,9 +25,14 @@ use router_env::logger;use crate::{core::errors::{UserErrors, UserResult},- headers, SessionState,+ headers,+ services::{authentication::UserFromToken, authorization::roles::RoleInfo},+ types::{domain::user::dashboard_metadata as types, transformers::ForeignFrom},+ SessionState,};+pub const MAX_SAVED_VIEWS: usize = 5;+pub async fn insert_merchant_scoped_metadata_to_db(state: &SessionState,user_id: String,@@ -42,6 +57,7 @@ pub async fn insert_merchant_scoped_metadata_to_db(created_at: now,last_modified_by: user_id,last_modified_at: now,+ profile_id: None,}).await.map_err(|e| {@@ -75,6 +91,7 @@ pub async fn insert_user_scoped_metadata_to_db(created_at: now,last_modified_by: user_id,last_modified_at: now,+ profile_id: None,}).await.map_err(|e| {@@ -122,6 +139,35 @@ pub async fn get_user_scoped_metadata_from_db(}}+pub async fn get_profile_user_scoped_metadata_from_db(+ state: &SessionState,+ user_id: String,+ merchant_id: id_type::MerchantId,+ org_id: id_type::OrganizationId,+ profile_id: Option<String>,+ metadata_keys: Vec<DBEnum>,+) -> UserResult<Vec<DashboardMetadata>> {+ let mut results = Vec::with_capacity(metadata_keys.len());+ for key in metadata_keys {+ if let Some(metadata) = state+ .store+ .find_profile_scoped_dashboard_metadata(+ &user_id,+ &merchant_id,+ &org_id,+ profile_id.clone(),+ key,+ )+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("DB Error Fetching DashboardMetaData")?+ {+ results.push(metadata);+ }+ }+ Ok(results)+}+pub async fn update_merchant_scoped_metadata(state: &SessionState,user_id: String,@@ -140,6 +186,7 @@ pub async fn update_merchant_scoped_metadata(None,merchant_id,org_id,+ None,metadata_key,DashboardMetadataUpdate::UpdateData {data_key: metadata_key,@@ -168,6 +215,7 @@ pub async fn update_user_scoped_metadata(Some(user_id.clone()),merchant_id,org_id,+ None,metadata_key,DashboardMetadataUpdate::UpdateData {data_key: metadata_key,@@ -191,8 +239,9 @@ wherepub fn separate_metadata_type_based_on_scope(metadata_keys: Vec<DBEnum>,-) -> (Vec<DBEnum>, Vec<DBEnum>) {- let (mut merchant_scoped, mut user_scoped) = (+) -> (Vec<DBEnum>, Vec<DBEnum>, Vec<DBEnum>) {+ let (mut merchant_scoped, mut user_scoped, mut profile_user_scoped) = (+ Vec::with_capacity(metadata_keys.len()),Vec::with_capacity(metadata_keys.len()),Vec::with_capacity(metadata_keys.len()),);@@ -220,10 +269,12 @@ pub fn separate_metadata_type_based_on_scope(| DBEnum::IsMultipleConfiguration| DBEnum::ReconStatus| DBEnum::ProdIntent => merchant_scoped.push(key),+ #[cfg(feature = "v1")]+ DBEnum::PaymentViews => profile_user_scoped.push(key),DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key),}}- (merchant_scoped, user_scoped)+ (merchant_scoped, user_scoped, profile_user_scoped)}pub fn is_update_required(metadata: &UserResult<DashboardMetadata>) -> bool {@@ -303,3 +354,381 @@ pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool {poc_email_check && business_website_check && user_email_check}++pub async fn get_profile_id_from_role(+ state: &SessionState,+ user: &UserFromToken,+) -> UserResult<Option<String>> {+ let tenant_id = user+ .tenant_id+ .clone()+ .unwrap_or(state.tenant.tenant_id.clone());++ let role_info = RoleInfo::from_role_id_in_lineage(+ state,+ &user.role_id,+ &user.merchant_id,+ &user.org_id,+ &user.profile_id,+ &tenant_id,+ )+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Failed to fetch role info")?;++ match role_info.get_entity_type() {+ EntityType::Profile => Ok(Some(user.profile_id.get_string_repr().to_owned())),+ EntityType::Merchant | EntityType::Organization | EntityType::Tenant => Ok(None),+ }+}++#[cfg(feature = "v1")]+#[allow(clippy::too_many_arguments)]+pub async fn modify_dashboard_metadata<T, F>(+ state: &SessionState,+ user: UserFromToken,+ metadata_key: DBEnum,+ profile_id: Option<String>,+ transform: F,+) -> UserResult<DashboardMetadata>+where+ T: serde::Serialize + serde::de::DeserializeOwned,+ F: FnOnce(Option<T>) -> UserResult<T>,+{+ let existing = {+ state+ .store+ .find_profile_scoped_dashboard_metadata(+ &user.user_id,+ &user.merchant_id,+ &user.org_id,+ profile_id.clone(),+ metadata_key,+ )+ .await+ }+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Error fetching dashboard metadata")?;++ let existing_value: Option<T> = existing+ .as_ref()+ .map(|m| serde_json::from_value(m.data_value.clone().peek().clone()))+ .transpose()+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Error deserializing dashboard metadata")?;++ let updated_value = transform(existing_value)?;+ let data_value = serde_json::to_value(&updated_value)+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Error serializing dashboard metadata")?;++ match existing {+ Some(metadata) => state+ .store+ .update_metadata(+ metadata.user_id,+ metadata.merchant_id,+ metadata.org_id,+ metadata.profile_id,+ metadata_key,+ DashboardMetadataUpdate::UpdateData {+ data_key: metadata_key,+ data_value: Secret::new(data_value),+ last_modified_by: user.user_id.clone(),+ },+ )+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Error updating dashboard metadata"),+ None => {+ let now = common_utils::date_time::now();+ state+ .store+ .insert_metadata(DashboardMetadataNew {+ user_id: Some(user.user_id.clone()),+ merchant_id: user.merchant_id,+ org_id: user.org_id,+ data_key: metadata_key,+ data_value: Secret::new(data_value),+ created_by: user.user_id.clone(),+ created_at: now,+ last_modified_by: user.user_id.clone(),+ last_modified_at: now,+ profile_id,+ })+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Error inserting dashboard metadata")+ }+ }+}++#[cfg(feature = "v1")]+impl ForeignFrom<payments::PaymentListFilterConstraints> for PaymentListFilterConstraintsV1 {+ fn foreign_from(item: payments::PaymentListFilterConstraints) -> Self {+ let payments::PaymentListFilterConstraints {+ payment_id,+ profile_id,+ customer_id,+ limit,+ offset,+ amount_filter,+ time_range,+ connector,+ currency,+ status,+ payment_method,+ payment_method_type,+ authentication_type,+ merchant_connector_id,+ order,+ card_network,+ merchant_order_reference_id,+ card_discovery,+ customer_email,+ } = item;+ Self {+ payment_id,+ profile_id,+ customer_id,+ limit,+ offset,+ amount_filter,+ time_range,+ connector,+ currency,+ status,+ payment_method,+ payment_method_type,+ authentication_type,+ merchant_connector_id,+ order,+ card_network,+ merchant_order_reference_id,+ card_discovery,+ customer_email,+ }+ }+}++#[cfg(feature = "v1")]+impl ForeignFrom<PaymentListFilterConstraintsV1> for payments::PaymentListFilterConstraints {+ fn foreign_from(item: PaymentListFilterConstraintsV1) -> Self {+ let PaymentListFilterConstraintsV1 {+ payment_id,+ profile_id,+ customer_id,+ limit,+ offset,+ amount_filter,+ time_range,+ connector,+ currency,+ status,+ payment_method,+ payment_method_type,+ authentication_type,+ merchant_connector_id,+ order,+ card_network,+ merchant_order_reference_id,+ card_discovery,+ customer_email,+ } = item;+ Self {+ payment_id,+ profile_id,+ customer_id,+ limit,+ offset,+ amount_filter,+ time_range,+ connector,+ currency,+ status,+ payment_method,+ payment_method_type,+ authentication_type,+ merchant_connector_id,+ order,+ card_network,+ merchant_order_reference_id,+ card_discovery,+ customer_email,+ }+ }+}++#[cfg(feature = "v1")]+fn get_payment_views_filters_v1(data: SavedViewFilters) -> PaymentListFilterConstraintsV1 {+ match data {+ SavedViewFilters::V1(f) => match f {+ SavedViewFiltersV1::PaymentViews(p) => p,+ },+ }+}++#[cfg(feature = "v1")]+pub async fn handle_saved_view_operations(+ state: &SessionState,+ user: UserFromToken,+ metadata_key: DBEnum,+ operation: SavedViewOperation,+) -> UserResult<DashboardMetadata> {+ let profile_id = get_profile_id_from_role(state, &user).await?;+ match operation {+ SavedViewOperation::Create(request) => {+ create_saved_view(state, user, metadata_key, profile_id, request).await+ }+ SavedViewOperation::Update(request) => {+ update_saved_view(state, user, metadata_key, profile_id, request).await+ }+ SavedViewOperation::Delete(request) => {+ delete_saved_view(state, user, metadata_key, profile_id, request).await+ }+ }+}++#[cfg(feature = "v1")]+async fn create_saved_view(+ state: &SessionState,+ user: UserFromToken,+ metadata_key: DBEnum,+ profile_id: Option<String>,+ request: CreateSavedViewRequest,+) -> UserResult<DashboardMetadata> {+ if request.view_name.trim().is_empty() {+ return Err(report!(UserErrors::InvalidSavedViewName))+ .attach_printable("Saved view name cannot be empty");+ }++ let now = common_utils::date_time::now();+ let view_id = common_utils::generate_id(common_utils::consts::ID_LENGTH, "view");+ let new_view_domain = types::SavedViewV1 {+ view_id,+ view_name: request.view_name.clone(),+ filters: get_payment_views_filters_v1(request.data),+ created_at: now.to_string(),+ updated_at: now.to_string(),+ };++ modify_dashboard_metadata(+ state,+ user,+ metadata_key,+ profile_id,+ |existing: Option<types::PaymentViewsValue>| {+ let mut views_data = existing.unwrap_or(types::PaymentViewsValue { views: vec![] });++ if views_data.views.len() >= MAX_SAVED_VIEWS {+ return Err(report!(UserErrors::MaxSavedViewsReached))+ .attach_printable("Maximum of 5 saved views reached");+ }++ if views_data+ .views+ .iter()+ .any(|v| v.view_name == request.view_name)+ {+ return Err(report!(UserErrors::SavedViewNameAlreadyExists))+ .attach_printable("A saved view with this name already exists");+ }++ views_data.views.push(new_view_domain);+ Ok(views_data)+ },+ )+ .await+}++#[cfg(feature = "v1")]+async fn update_saved_view(+ state: &SessionState,+ user: UserFromToken,+ metadata_key: DBEnum,+ profile_id: Option<String>,+ request: UpdateSavedViewRequest,+) -> UserResult<DashboardMetadata> {+ modify_dashboard_metadata(+ state,+ user,+ metadata_key,+ profile_id,+ |existing: Option<types::PaymentViewsValue>| {+ let mut views_data = existing.ok_or(report!(UserErrors::SavedViewNotFound))?;++ if !views_data+ .views+ .iter()+ .any(|v| v.view_id == request.view_id)+ {+ return Err(report!(UserErrors::SavedViewNotFound))+ .attach_printable("Saved view with this ID not found");+ }++ if let Some(ref new_name) = request.view_name {+ if new_name.trim().is_empty() {+ return Err(report!(UserErrors::InvalidSavedViewName))+ .attach_printable("Saved view name cannot be empty");+ }++ if views_data+ .views+ .iter()+ .any(|v| v.view_id != request.view_id && v.view_name == *new_name)+ {+ return Err(report!(UserErrors::SavedViewNameAlreadyExists))+ .attach_printable("A saved view with this name already exists");+ }+ }++ let view = views_data+ .views+ .iter_mut()+ .find(|v| v.view_id == request.view_id)+ .ok_or(report!(UserErrors::SavedViewNotFound))?;++ if let Some(new_name) = request.view_name {+ view.view_name = new_name;+ }+ view.filters = get_payment_views_filters_v1(request.data);+ view.updated_at = common_utils::date_time::now().to_string();++ Ok(views_data)+ },+ )+ .await+}++#[cfg(feature = "v1")]+async fn delete_saved_view(+ state: &SessionState,+ user: UserFromToken,+ metadata_key: DBEnum,+ profile_id: Option<String>,+ request: DeleteSavedViewRequest,+) -> UserResult<DashboardMetadata> {+ modify_dashboard_metadata(+ state,+ user,+ metadata_key,+ profile_id,+ |existing: Option<types::PaymentViewsValue>| {+ let mut views_data = existing.ok_or(report!(UserErrors::SavedViewNotFound))?;++ let position = views_data+ .views+ .iter()+ .position(|v| v.view_id == request.view_id)+ .ok_or_else(|| {+ report!(UserErrors::SavedViewNotFound)+ .attach_printable("Saved view with this ID not found")+ })?;++ views_data.views.remove(position);++ Ok(views_data)+ },+ )+ .await+}diff --git a/migrations/2026-02-28-111500_add_saved_views_to_dashboard_metadata/down.sql b/migrations/2026-02-28-111500_add_saved_views_to_dashboard_metadata/down.sqlnew file mode 100644index 0000000000..07db01a9e9--- /dev/null+++ b/migrations/2026-02-28-111500_add_saved_views_to_dashboard_metadata/down.sql@@ -0,0 +1,6 @@+DROP INDEX IF EXISTS dashboard_metadata_index;++CREATE UNIQUE INDEX dashboard_metadata_index+ON dashboard_metadata (COALESCE(user_id, '0'), merchant_id, org_id, data_key);++ALTER TABLE dashboard_metadata DROP COLUMN IF EXISTS profile_id;diff --git a/migrations/2026-02-28-111500_add_saved_views_to_dashboard_metadata/up.sql b/migrations/2026-02-28-111500_add_saved_views_to_dashboard_metadata/up.sqlnew file mode 100644index 0000000000..c066a010db--- /dev/null+++ b/migrations/2026-02-28-111500_add_saved_views_to_dashboard_metadata/up.sql@@ -0,0 +1,20 @@+ALTER TABLE dashboard_metadata+ ADD COLUMN profile_id VARCHAR(64);++ALTER TYPE "DashboardMetadata" ADD VALUE IF NOT EXISTS 'payment_views';+ALTER TYPE "DashboardMetadata" ADD VALUE IF NOT EXISTS 'refund_views';+ALTER TYPE "DashboardMetadata" ADD VALUE IF NOT EXISTS 'customer_views';+ALTER TYPE "DashboardMetadata" ADD VALUE IF NOT EXISTS 'dispute_views';+ALTER TYPE "DashboardMetadata" ADD VALUE IF NOT EXISTS 'payout_views';++DROP INDEX IF EXISTS dashboard_metadata_index;++CREATE UNIQUE INDEX dashboard_metadata_index+ON dashboard_metadata (+ COALESCE(user_id, '0'),+ merchant_id,+ org_id,+ COALESCE(profile_id, '0'),+ data_key+);+