{"file_name": "crates__analytics__src__query.rs", "text": "use std::{fmt, marker::PhantomData};\n\nuse api_models::{\n analytics::{\n self as analytics_api,\n api_event::ApiEventDimensions,\n auth_events::{AuthEventDimensions, AuthEventFlows},\n disputes::DisputeDimensions,\n frm::{FrmDimensions, FrmTransactionType},\n payment_intents::PaymentIntentDimensions,\n payments::{PaymentDimensions, PaymentDistributions},\n refunds::{RefundDimensions, RefundDistributions, RefundType},\n sdk_events::{SdkEventDimensions, SdkEventNames},\n Granularity,\n },\n enums::{\n AttemptStatus, AuthenticationType, Connector, Currency, DisputeStage, IntentStatus,\n PaymentMethod, PaymentMethodType, RoutingApproach,\n },\n refunds::RefundStatus,\n};\nuse common_enums::{\n AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus,\n};\nuse common_utils::{\n errors::{CustomResult, ParsingError},\n id_type::{MerchantId, OrganizationId, ProfileId},\n};\nuse diesel_models::{enums as storage_enums, enums::FraudCheckStatus};\nuse error_stack::ResultExt;\nuse router_env::{logger, Flow};\n\nuse super::types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, TableEngine};\nuse crate::{enums::AuthInfo, types::QueryExecutionError};\npub type QueryResult = error_stack::Result;\npub trait QueryFilter\nwhere\n T: AnalyticsDataSource,\n AnalyticsCollection: ToSql,\n{\n fn set_filter_clause(&self, builder: &mut QueryBuilder) -> QueryResult<()>;\n}\n\npub trait GroupByClause\nwhere\n T: AnalyticsDataSource,\n AnalyticsCollection: ToSql,\n{\n fn set_group_by_clause(&self, builder: &mut QueryBuilder) -> QueryResult<()>;\n}\n\npub trait SeriesBucket {\n type SeriesType;\n type GranularityLevel;\n\n fn get_lowest_common_granularity_level(&self) -> Self::GranularityLevel;\n\n fn get_bucket_size(&self) -> u8;\n\n fn clip_to_start(\n &self,\n value: Self::SeriesType,\n ) -> error_stack::Result;\n\n fn clip_to_end(\n &self,\n value: Self::SeriesType,\n ) -> error_stack::Result;\n}\n\nimpl QueryFilter for analytics_api::TimeRange\nwhere\n T: AnalyticsDataSource,\n time::PrimitiveDateTime: ToSql,\n AnalyticsCollection: ToSql,\n Granularity: GroupByClause,\n{\n fn set_filter_clause(&self, builder: &mut QueryBuilder) -> QueryResult<()> {\n builder.add_custom_filter_clause(\"created_at\", self.start_time, FilterTypes::Gte)?;\n if let Some(end) = self.end_time {\n builder.add_custom_filter_clause(\"created_at\", end, FilterTypes::Lte)?;\n }\n Ok(())\n }\n}\n\nimpl GroupByClause for Granularity {\n fn set_group_by_clause(\n &self,\n builder: &mut QueryBuilder,\n ) -> QueryResult<()> {\n let trunc_scale = self.get_lowest_common_granularity_level();\n\n let granularity_bucket_scale = match self {\n Self::OneMin => None,\n Self::FiveMin | Self::FifteenMin | Self::ThirtyMin => Some(\"minute\"),\n Self::OneHour | Self::OneDay => None,\n };\n\n let granularity_divisor = self.get_bucket_size();\n\n builder\n .add_group_by_clause(format!(\"DATE_TRUNC('{trunc_scale}', created_at)\"))\n .attach_printable(\"Error adding time prune group by\")?;\n if let Some(scale) = granularity_bucket_scale {\n builder\n .add_group_by_clause(format!(\n \"FLOOR(DATE_PART('{scale}', created_at)/{granularity_divisor})\"\n ))\n .attach_printable(\"Error adding time binning group by\")?;\n }\n Ok(())\n }\n}\n\nimpl GroupByClause for Granularity {\n fn set_group_by_clause(\n &self,\n builder: &mut QueryBuilder,\n ) -> QueryResult<()> {\n let interval = match self {\n Self::OneMin => \"toStartOfMinute(created_at)\",\n Self::FiveMin => \"toStartOfFiveMinutes(created_at)\",\n Self::FifteenMin => \"toStartOfFifteenMinutes(created_at)\",\n Self::ThirtyMin => \"toStartOfInterval(created_at, INTERVAL 30 minute)\",\n Self::OneHour => \"toStartOfHour(created_at)\",\n Self::OneDay => \"toStartOfDay(created_at)\",\n };\n\n builder\n .add_group_by_clause(interval)\n .attach_printable(\"Error adding interval group by\")\n }\n}\n\n#[derive(strum::Display)]\n#[strum(serialize_all = \"lowercase\")]\npub enum TimeGranularityLevel {\n Minute,\n Hour,\n Day,\n}\n\nimpl SeriesBucket for Granularity {\n type SeriesType = time::PrimitiveDateTime;\n\n type GranularityLevel = TimeGranularityLevel;\n\n fn get_lowest_common_granularity_level(&self) -> Self::GranularityLevel {\n match self {\n Self::OneMin => TimeGranularityLevel::Minute,\n Self::FiveMin | Self::FifteenMin | Self::ThirtyMin | Self::OneHour => {\n TimeGranularityLevel::Hour\n }\n Self::OneDay => TimeGranularityLevel::Day,\n }\n }\n\n fn get_bucket_size(&self) -> u8 {\n match self {\n Self::OneMin => 60,\n Self::FiveMin => 5,\n Self::FifteenMin => 15,\n Self::ThirtyMin => 30,\n Self::OneHour => 60,\n Self::OneDay => 24,\n }\n }\n\n fn clip_to_start(\n &self,\n value: Self::SeriesType,\n ) -> error_stack::Result {\n let clip_start = |value: u8, modulo: u8| -> u8 { value - value % modulo };\n\n let clipped_time = match (\n self.get_lowest_common_granularity_level(),\n self.get_bucket_size(),\n ) {\n (TimeGranularityLevel::Minute, i) => time::Time::MIDNIGHT\n .replace_second(clip_start(value.second(), i))\n .and_then(|t| t.replace_minute(value.minute()))\n .and_then(|t| t.replace_hour(value.hour())),\n (TimeGranularityLevel::Hour, i) => time::Time::MIDNIGHT\n .replace_minute(clip_start(value.minute(), i))\n .and_then(|t| t.replace_hour(value.hour())),\n (TimeGranularityLevel::Day, i) => {\n time::Time::MIDNIGHT.replace_hour(clip_start(value.hour(), i))\n }\n }\n .change_context(PostProcessingError::BucketClipping)?;\n\n Ok(value.replace_time(clipped_time))\n }\n\n fn clip_to_end(\n &self,\n value: Self::SeriesType,\n ) -> error_stack::Result {\n let clip_end = |value: u8, modulo: u8| -> u8 { value + modulo - 1 - value % modulo };\n\n let clipped_time = match (\n self.get_lowest_common_granularity_level(),\n self.get_bucket_size(),\n ) {\n (TimeGranularityLevel::Minute, i) => time::Time::MIDNIGHT\n .replace_second(clip_end(value.second(), i))\n .and_then(|t| t.replace_minute(value.minute()))\n .and_then(|t| t.replace_hour(value.hour())),\n (TimeGranularityLevel::Hour, i) => time::Time::MIDNIGHT\n .replace_minute(clip_end(value.minute(), i))\n .and_then(|t| t.replace_hour(value.hour())),\n (TimeGranularityLevel::Day, i) => {\n time::Time::MIDNIGHT.replace_hour(clip_end(value.hour(), i))\n }\n }\n .change_context(PostProcessingError::BucketClipping)\n .attach_printable_lazy(|| format!(\"Bucket Clip Error: {value}\"))?;\n\n Ok(value.replace_time(clipped_time))\n }\n}\n\n#[derive(thiserror::Error, Debug)]\npub enum QueryBuildingError {\n #[allow(dead_code)]\n #[error(\"Not Implemented: {0}\")]\n NotImplemented(String),\n #[error(\"Failed to Serialize to SQL\")]\n SqlSerializeError,\n #[error(\"Failed to build sql query: {0}\")]\n InvalidQuery(&'static str),\n}\n\n#[derive(thiserror::Error, Debug)]\npub enum PostProcessingError {\n #[error(\"Error Clipping values to bucket sizes\")]\n BucketClipping,\n}\n\n#[derive(Debug)]\npub enum Aggregate {\n Count {\n field: Option,\n alias: Option<&'static str>,\n },\n Sum {\n field: R,\n alias: Option<&'static str>,\n },\n Min {\n field: R,\n alias: Option<&'static str>,\n },\n Max {\n field: R,\n alias: Option<&'static str>,\n },\n Percentile {\n field: R,\n alias: Option<&'static str>,\n percentile: Option<&'static u8>,\n },\n DistinctCount {\n field: R,\n alias: Option<&'static str>,\n },\n}\n\n// Window functions in query\n// ---\n// Description -\n// field: to_sql type value used as expr in aggregation\n// partition_by: partition by fields in window\n// order_by: order by fields and order (Ascending / Descending) in window\n// alias: alias of window expr in query\n// ---\n// Usage -\n// Window::Sum {\n// field: \"count\",\n// partition_by: Some(query_builder.transform_to_sql_values(&dimensions).switch()?),\n// order_by: Some((\"value\", Descending)),\n// alias: Some(\"total\"),\n// }\n#[derive(Debug)]\npub enum Window {\n Sum {\n field: R,\n partition_by: Option,\n order_by: Option<(String, Order)>,\n alias: Option<&'static str>,\n },\n RowNumber {\n field: R,\n partition_by: Option,\n order_by: Option<(String, Order)>,\n alias: Option<&'static str>,\n },\n}\n\n#[derive(Debug, Clone, Copy)]\npub enum Order {\n Ascending,\n Descending,\n}\n\nimpl fmt::Display for Order {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::Ascending => write!(f, \"asc\"),\n Self::Descending => write!(f, \"desc\"),\n }\n }\n}\n\n// Select TopN values for a group based on a metric\n// ---\n// Description -\n// columns: Columns in group to select TopN values for\n// count: N in TopN\n// order_column: metric used to sort and limit TopN\n// order: sort order of metric (Ascending / Descending)\n// ---\n// Usage -\n// Use via add_top_n_clause fn of query_builder\n// add_top_n_clause(\n// &dimensions,\n// distribution.distribution_cardinality.into(),\n// \"count\",\n// Order::Descending,\n// )\n#[allow(dead_code)]\n#[derive(Debug)]\npub struct TopN {\n pub columns: String,\n pub count: u64,\n pub order_column: String,\n pub order: Order,\n}\n\n#[derive(Debug, Clone)]\npub struct LimitByClause {\n limit: u64,\n columns: Vec,\n}\n\nimpl fmt::Display for LimitByClause {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"LIMIT {} BY {}\", self.limit, self.columns.join(\", \"))\n }\n}\n\n#[derive(Debug, Default, Clone, Copy)]\npub enum FilterCombinator {\n #[default]\n And,\n Or,\n}\n\nimpl ToSql for FilterCombinator {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(match self {\n Self::And => \" AND \",\n Self::Or => \" OR \",\n }\n .to_owned())\n }\n}\n\n#[derive(Debug, Clone)]\npub enum Filter {\n Plain(String, FilterTypes, String),\n NestedFilter(FilterCombinator, Vec),\n}\n\nimpl Default for Filter {\n fn default() -> Self {\n Self::NestedFilter(FilterCombinator::default(), Vec::new())\n }\n}\n\nimpl ToSql for Filter {\n fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result {\n Ok(match self {\n Self::Plain(l, op, r) => filter_type_to_sql(l, *op, r),\n Self::NestedFilter(operator, filters) => {\n format!(\n \"( {} )\",\n filters\n .iter()\n .map(|f| >::to_sql(f, table_engine))\n .collect::, _>>()?\n .join(\n >::to_sql(operator, table_engine)?\n .as_ref()\n )\n )\n }\n })\n }\n}\n\n#[derive(Debug)]\npub struct QueryBuilder\nwhere\n T: AnalyticsDataSource,\n AnalyticsCollection: ToSql,\n{\n columns: Vec,\n filters: Filter,\n group_by: Vec,\n order_by: Vec,\n having: Option>,\n limit_by: Option,\n outer_select: Vec,\n top_n: Option,\n table: AnalyticsCollection,\n distinct: bool,\n db_type: PhantomData,\n table_engine: TableEngine,\n}\n\npub trait ToSql {\n fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result;\n}\n\nimpl ToSql for &MerchantId {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.get_string_repr().to_owned())\n }\n}\n\nimpl ToSql for MerchantId {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.get_string_repr().to_owned())\n }\n}\n\nimpl ToSql for &OrganizationId {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.get_string_repr().to_owned())\n }\n}\n\nimpl ToSql for ProfileId {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.get_string_repr().to_owned())\n }\n}\n\nimpl ToSql for &common_utils::id_type::PaymentId {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.get_string_repr().to_owned())\n }\n}\n\nimpl ToSql for &common_utils::id_type::PayoutId {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.get_string_repr().to_owned())\n }\n}\n\nimpl ToSql for common_utils::id_type::CustomerId {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.get_string_repr().to_owned())\n }\n}\n\nimpl ToSql for bool {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n let flag = *self;\n Ok(i8::from(flag).to_string())\n }\n}\n\n/// Implement `ToSql` on arrays of types that impl `ToString`.\nmacro_rules! impl_to_sql_for_to_string {\n ($($type:ty),+) => {\n $(\n impl ToSql for $type {\n fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result {\n Ok(self.to_string())\n }\n }\n )+\n };\n}\n\nimpl_to_sql_for_to_string!(\n String,\n &str,\n &PaymentDimensions,\n &PaymentIntentDimensions,\n &RefundDimensions,\n &FrmDimensions,\n PaymentDimensions,\n PaymentIntentDimensions,\n &PaymentDistributions,\n RefundDimensions,\n &RefundDistributions,\n FrmDimensions,\n PaymentMethod,\n PaymentMethodType,\n AuthenticationType,\n Connector,\n AttemptStatus,\n IntentStatus,\n RefundStatus,\n FraudCheckStatus,\n storage_enums::RefundStatus,\n Currency,\n RefundType,\n FrmTransactionType,\n TransactionStatus,\n AuthenticationStatus,\n AuthenticationConnectors,\n DecoupledAuthenticationType,\n Flow,\n &String,\n &bool,\n &u64,\n u64,\n Order,\n RoutingApproach\n);\n\nimpl_to_sql_for_to_string!(\n &SdkEventDimensions,\n SdkEventDimensions,\n SdkEventNames,\n AuthEventFlows,\n &ApiEventDimensions,\n ApiEventDimensions,\n &DisputeDimensions,\n DisputeDimensions,\n DisputeStage,\n AuthEventDimensions,\n &AuthEventDimensions\n);\n\n#[derive(Debug, Clone, Copy)]\npub enum FilterTypes {\n Equal,\n NotEqual,\n EqualBool,\n In,\n Gte,\n Lte,\n Gt,\n Like,\n NotLike,\n IsNotNull,\n}\n\npub fn filter_type_to_sql(l: &str, op: FilterTypes, r: &str) -> String {\n match op {\n FilterTypes::EqualBool => format!(\"{l} = {r}\"),\n FilterTypes::Equal => format!(\"{l} = '{r}'\"),\n FilterTypes::NotEqual => format!(\"{l} != '{r}'\"),\n FilterTypes::In => format!(\"{l} IN ({r})\"),\n FilterTypes::Gte => format!(\"{l} >= '{r}'\"),\n FilterTypes::Gt => format!(\"{l} > {r}\"),\n FilterTypes::Lte => format!(\"{l} <= '{r}'\"),\n FilterTypes::Like => format!(\"{l} LIKE '%{r}%'\"),\n FilterTypes::NotLike => format!(\"{l} NOT LIKE '%{r}%'\"),\n FilterTypes::IsNotNull => format!(\"{l} IS NOT NULL\"),\n }\n}\n\nimpl QueryBuilder\nwhere\n T: AnalyticsDataSource,\n AnalyticsCollection: ToSql,\n{\n pub fn new(table: AnalyticsCollection) -> Self {\n Self {\n columns: Default::default(),\n filters: Default::default(),\n group_by: Default::default(),\n order_by: Default::default(),\n having: Default::default(),\n limit_by: Default::default(),\n outer_select: Default::default(),\n top_n: Default::default(),\n table,\n distinct: Default::default(),\n db_type: Default::default(),\n table_engine: T::get_table_engine(table),\n }\n }\n\n pub fn add_select_column(&mut self, column: impl ToSql) -> QueryResult<()> {\n self.columns.push(\n column\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing select column\")?,\n );\n Ok(())\n }\n\n pub fn transform_to_sql_values(&mut self, values: &[impl ToSql]) -> QueryResult {\n let res = values\n .iter()\n .map(|i| i.to_sql(&self.table_engine))\n .collect::, ParsingError>>()\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing range filter value\")?\n .join(\", \");\n Ok(res)\n }\n\n pub fn add_top_n_clause(\n &mut self,\n columns: &[impl ToSql],\n count: u64,\n order_column: impl ToSql,\n order: Order,\n ) -> QueryResult<()>\n where\n Window<&'static str>: ToSql,\n {\n let partition_by_columns = self.transform_to_sql_values(columns)?;\n let order_by_column = order_column\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing select column\")?;\n\n self.add_outer_select_column(Window::RowNumber {\n field: \"\",\n partition_by: Some(partition_by_columns.clone()),\n order_by: Some((order_by_column.clone(), order)),\n alias: Some(\"top_n\"),\n })?;\n\n self.top_n = Some(TopN {\n columns: partition_by_columns,\n count,\n order_column: order_by_column,\n order,\n });\n Ok(())\n }\n\n pub fn set_distinct(&mut self) {\n self.distinct = true\n }\n\n pub fn add_filter_clause(\n &mut self,\n key: impl ToSql,\n value: impl ToSql,\n ) -> QueryResult<()> {\n self.add_custom_filter_clause(key, value, FilterTypes::Equal)\n }\n\n pub fn add_bool_filter_clause(\n &mut self,\n key: impl ToSql,\n value: impl ToSql,\n ) -> QueryResult<()> {\n self.add_custom_filter_clause(key, value, FilterTypes::EqualBool)\n }\n\n pub fn add_negative_filter_clause(\n &mut self,\n key: impl ToSql,\n value: impl ToSql,\n ) -> QueryResult<()> {\n self.add_custom_filter_clause(key, value, FilterTypes::NotEqual)\n }\n\n pub fn add_custom_filter_clause(\n &mut self,\n lhs: impl ToSql,\n rhs: impl ToSql,\n comparison: FilterTypes,\n ) -> QueryResult<()> {\n let filter = Filter::Plain(\n lhs.to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing filter key\")?,\n comparison,\n rhs.to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing filter value\")?,\n );\n self.add_nested_filter_clause(filter);\n Ok(())\n }\n pub fn add_nested_filter_clause(&mut self, filter: Filter) {\n match &mut self.filters {\n Filter::NestedFilter(_, ref mut filters) => filters.push(filter),\n f @ Filter::Plain(_, _, _) => {\n self.filters = Filter::NestedFilter(FilterCombinator::And, vec![f.clone(), filter]);\n }\n }\n }\n\n pub fn add_filter_in_range_clause(\n &mut self,\n key: impl ToSql,\n values: &[impl ToSql],\n ) -> QueryResult<()> {\n let list = values\n .iter()\n .map(|i| {\n // trimming whitespaces from the filter values received in request, to prevent a possibility of an SQL injection\n i.to_sql(&self.table_engine).map(|s| {\n let trimmed_str = s.replace(' ', \"\");\n format!(\"'{trimmed_str}'\")\n })\n })\n .collect::, ParsingError>>()\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing range filter value\")?\n .join(\", \");\n self.add_custom_filter_clause(key, list, FilterTypes::In)\n }\n\n pub fn add_group_by_clause(&mut self, column: impl ToSql) -> QueryResult<()> {\n self.group_by.push(\n column\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing group by field\")?,\n );\n Ok(())\n }\n\n pub fn add_order_by_clause(\n &mut self,\n column: impl ToSql,\n order: impl ToSql,\n ) -> QueryResult<()> {\n let column_sql = column\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing order by column\")?;\n\n let order_sql = order\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing order direction\")?;\n\n self.order_by.push(format!(\"{column_sql} {order_sql}\"));\n Ok(())\n }\n\n pub fn set_limit_by(&mut self, limit: u64, columns: &[impl ToSql]) -> QueryResult<()> {\n let columns = columns\n .iter()\n .map(|col| col.to_sql(&self.table_engine))\n .collect::, _>>()\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing LIMIT BY columns\")?;\n\n self.limit_by = Some(LimitByClause { limit, columns });\n Ok(())\n }\n\n pub fn add_granularity_in_mins(&mut self, granularity: Granularity) -> QueryResult<()> {\n let interval = match granularity {\n Granularity::OneMin => \"1\",\n Granularity::FiveMin => \"5\",\n Granularity::FifteenMin => \"15\",\n Granularity::ThirtyMin => \"30\",\n Granularity::OneHour => \"60\",\n Granularity::OneDay => \"1440\",\n };\n let _ = self.add_select_column(format!(\n \"toStartOfInterval(created_at, INTERVAL {interval} MINUTE) as time_bucket\"\n ));\n Ok(())\n }\n\n fn get_filter_clause(&self) -> QueryResult {\n >::to_sql(&self.filters, &self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n }\n\n fn get_select_clause(&self) -> String {\n self.columns.join(\", \")\n }\n\n fn get_group_by_clause(&self) -> String {\n self.group_by.join(\", \")\n }\n\n fn get_outer_select_clause(&self) -> String {\n self.outer_select.join(\", \")\n }\n\n pub fn add_having_clause(\n &mut self,\n aggregate: Aggregate,\n filter_type: FilterTypes,\n value: impl ToSql,\n ) -> QueryResult<()>\n where\n Aggregate: ToSql,\n {\n let aggregate = aggregate\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing having aggregate\")?;\n let value = value\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing having value\")?;\n let entry = (aggregate, filter_type, value);\n if let Some(having) = &mut self.having {\n having.push(entry);\n } else {\n self.having = Some(vec![entry]);\n }\n Ok(())\n }\n\n pub fn add_outer_select_column(&mut self, column: impl ToSql) -> QueryResult<()> {\n self.outer_select.push(\n column\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing outer select column\")?,\n );\n Ok(())\n }\n\n pub fn get_filter_type_clause(&self) -> Option {\n self.having.as_ref().map(|vec| {\n vec.iter()\n .map(|(l, op, r)| filter_type_to_sql(l, *op, r))\n .collect::>()\n .join(\" AND \")\n })\n }\n\n pub fn build_query(&mut self) -> QueryResult\n where\n Aggregate<&'static str>: ToSql,\n Window<&'static str>: ToSql,\n {\n if self.columns.is_empty() {\n Err(QueryBuildingError::InvalidQuery(\n \"No select fields provided\",\n ))?;\n }\n let mut query = String::from(\"SELECT \");\n\n if self.distinct {\n query.push_str(\"DISTINCT \");\n }\n\n query.push_str(&self.get_select_clause());\n\n query.push_str(\" FROM \");\n\n query.push_str(\n &self\n .table\n .to_sql(&self.table_engine)\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Error serializing table value\")?,\n );\n\n let filter_clause = self.get_filter_clause()?;\n if !filter_clause.is_empty() {\n query.push_str(\" WHERE \");\n query.push_str(filter_clause.as_str());\n }\n\n if !self.group_by.is_empty() {\n query.push_str(\" GROUP BY \");\n query.push_str(&self.get_group_by_clause());\n if let TableEngine::CollapsingMergeTree { sign } = self.table_engine {\n self.add_having_clause(\n Aggregate::Count {\n field: Some(sign),\n alias: None,\n },\n FilterTypes::Gte,\n \"1\",\n )?;\n }\n }\n\n if self.having.is_some() {\n if let Some(condition) = self.get_filter_type_clause() {\n query.push_str(\" HAVING \");\n query.push_str(condition.as_str());\n }\n }\n\n if !self.order_by.is_empty() {\n query.push_str(\" ORDER BY \");\n query.push_str(&self.order_by.join(\", \"));\n }\n\n if let Some(limit_by) = &self.limit_by {\n query.push_str(&format!(\" {limit_by}\"));\n }\n\n if !self.outer_select.is_empty() {\n query.insert_str(\n 0,\n format!(\"SELECT {} FROM (\", &self.get_outer_select_clause()).as_str(),\n );\n query.push_str(\") _\");\n }\n\n if let Some(top_n) = &self.top_n {\n query.insert_str(0, \"SELECT * FROM (\");\n query.push_str(format!(\") _ WHERE top_n <= {}\", top_n.count).as_str());\n }\n\n logger::debug!(%query);\n\n Ok(query)\n }\n\n pub async fn execute_query(\n &mut self,\n store: &P,\n ) -> CustomResult, QueryExecutionError>, QueryBuildingError>\n where\n P: LoadRow + AnalyticsDataSource,\n Aggregate<&'static str>: ToSql,\n Window<&'static str>: ToSql,\n {\n let query = self\n .build_query()\n .change_context(QueryBuildingError::SqlSerializeError)\n .attach_printable(\"Failed to execute query\")?;\n\n Ok(store.load_results(query.as_str()).await)\n }\n}\n\nimpl QueryFilter for AuthInfo\nwhere\n T: AnalyticsDataSource,\n AnalyticsCollection: ToSql,\n{\n fn set_filter_clause(&self, builder: &mut QueryBuilder) -> QueryResult<()> {\n match self {\n Self::OrgLevel { org_id } => {\n builder\n .add_filter_clause(\"organization_id\", org_id)\n .attach_printable(\"Error adding organization_id filter\")?;\n }\n Self::MerchantLevel {\n org_id,\n merchant_ids,\n } => {\n builder\n .add_filter_clause(\"organization_id\", org_id)\n .attach_printable(\"Error adding organization_id filter\")?;\n builder\n .add_filter_in_range_clause(\"merchant_id\", merchant_ids)\n .attach_printable(\"Error adding merchant_id filter\")?;\n }\n Self::ProfileLevel {\n org_id,\n merchant_id,\n profile_ids,\n } => {\n builder\n .add_filter_clause(\"organization_id\", org_id)\n .attach_printable(\"Error adding organization_id filter\")?;\n builder\n .add_filter_clause(\"merchant_id\", merchant_id)\n .attach_printable(\"Error adding merchant_id filter\")?;\n builder\n .add_filter_in_range_clause(\"profile_id\", profile_ids)\n .attach_printable(\"Error adding profile_id filter\")?;\n }\n }\n Ok(())\n }\n}\n"} {"file_name": "crates__api_models__src__authentication.rs", "text": "use common_enums::{enums, AuthenticationConnectors};\n#[cfg(feature = \"v1\")]\nuse common_utils::errors::{self, CustomResult};\nuse common_utils::{\n events::{ApiEventMetric, ApiEventsType},\n id_type,\n};\n#[cfg(feature = \"v1\")]\nuse error_stack::ResultExt;\nuse serde::{Deserialize, Serialize};\nuse time::PrimitiveDateTime;\nuse utoipa::ToSchema;\n\n#[cfg(feature = \"v1\")]\nuse crate::payments::{Address, BrowserInformation, PaymentMethodData};\nuse crate::payments::{\n ClickToPaySessionResponse, CustomerDetails, DeviceChannel, SdkInformation,\n ThreeDsCompletionIndicator,\n};\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationCreateRequest {\n /// The unique identifier for this authentication.\n #[schema(value_type = Option, example = \"auth_mbabizu24mvu3mela5njyhpit4\")]\n pub authentication_id: Option,\n\n /// The business profile that is associated with this authentication\n #[schema(value_type = Option)]\n pub profile_id: Option,\n\n /// Customer details.\n #[schema(value_type = Option)]\n pub customer: Option,\n\n /// The amount for the transaction, required.\n #[schema(value_type = MinorUnit, example = 1000)]\n pub amount: common_utils::types::MinorUnit,\n\n /// The connector to be used for authentication, if known.\n #[schema(value_type = Option, example = \"netcetera\")]\n pub authentication_connector: Option,\n\n /// The currency for the transaction, required.\n #[schema(value_type = Currency)]\n pub currency: common_enums::Currency,\n\n /// The URL to which the user should be redirected after authentication.\n #[schema(value_type = Option, example = \"https://example.com/redirect\")]\n pub return_url: Option,\n\n /// Force 3DS challenge.\n #[serde(default)]\n pub force_3ds_challenge: Option,\n\n /// Choose what kind of sca exemption is required for this payment\n #[schema(value_type = Option)]\n pub psd2_sca_exemption_type: Option,\n\n /// Profile Acquirer ID get from profile acquirer configuration\n #[schema(value_type = Option)]\n pub profile_acquirer_id: Option,\n\n /// Acquirer details information\n #[schema(value_type = Option)]\n pub acquirer_details: Option,\n\n /// Customer details.\n #[schema(value_type = Option)]\n pub customer_details: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct AcquirerDetails {\n /// The bin of the card.\n #[schema(value_type = Option, example = \"123456\")]\n pub acquirer_bin: Option,\n /// The merchant id of the card.\n #[schema(value_type = Option, example = \"merchant_abc\")]\n pub acquirer_merchant_id: Option,\n /// The country code of the card.\n #[schema(value_type = Option, example = \"US/34456\")]\n pub merchant_country_code: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationResponse {\n /// The unique identifier for this authentication.\n #[schema(value_type = String, example = \"auth_mbabizu24mvu3mela5njyhpit4\")]\n pub authentication_id: id_type::AuthenticationId,\n\n /// This is an identifier for the merchant account. This is inferred from the API key\n /// provided during the request\n #[schema(value_type = String, example = \"merchant_abc\")]\n pub merchant_id: id_type::MerchantId,\n\n /// The current status of the authentication (e.g., Started).\n #[schema(value_type = AuthenticationStatus)]\n pub status: common_enums::AuthenticationStatus,\n\n /// The client secret for this authentication, to be used for client-side operations.\n #[schema(value_type = Option, example = \"auth_mbabizu24mvu3mela5njyhpit4_secret_el9ksDkiB8hi6j9N78yo\")]\n pub client_secret: Option>,\n\n /// The amount for the transaction.\n #[schema(value_type = MinorUnit, example = 1000)]\n pub amount: common_utils::types::MinorUnit,\n\n /// The currency for the transaction.\n #[schema(value_type = Currency)]\n pub currency: enums::Currency,\n\n /// The connector to be used for authentication, if known.\n #[schema(value_type = Option, example = \"netcetera\")]\n pub authentication_connector: Option,\n\n /// Whether 3DS challenge was forced.\n pub force_3ds_challenge: Option,\n\n /// The URL to which the user should be redirected after authentication, if provided.\n pub return_url: Option,\n\n #[schema(example = \"2022-09-10T10:11:12Z\")]\n #[serde(with = \"common_utils::custom_serde::iso8601::option\")]\n pub created_at: Option,\n\n #[schema(example = \"E0001\")]\n pub error_code: Option,\n\n /// If there was an error while calling the connector the error message is received here\n #[schema(example = \"Failed while verifying the card\")]\n pub error_message: Option,\n\n /// The business profile that is associated with this payment\n #[schema(value_type = Option)]\n pub profile_id: Option,\n\n /// Choose what kind of sca exemption is required for this payment\n #[schema(value_type = Option)]\n pub psd2_sca_exemption_type: Option,\n\n /// Acquirer details information\n #[schema(value_type = Option)]\n pub acquirer_details: Option,\n\n /// Profile Acquirer ID get from profile acquirer configuration\n #[schema(value_type = Option)]\n pub profile_acquirer_id: Option,\n\n /// Customer details.\n #[schema(value_type = Option)]\n pub customer_details: Option,\n}\n\nimpl ApiEventMetric for AuthenticationCreateRequest {\n fn get_api_event_type(&self) -> Option {\n self.authentication_id\n .as_ref()\n .map(|id| ApiEventsType::Authentication {\n authentication_id: id.clone(),\n })\n }\n}\n\nimpl ApiEventMetric for AuthenticationResponse {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl ApiEventMetric for AuthenticationEligibilityCheckRequest {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl ApiEventMetric for AuthenticationEligibilityCheckResponse {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl ApiEventMetric for AuthenticationRetrieveEligibilityCheckRequest {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl ApiEventMetric for AuthenticationRetrieveEligibilityCheckResponse {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationEligibilityRequest {\n /// Payment method-specific data such as card details, wallet info, etc.\n /// This holds the raw information required to process the payment method.\n #[schema(value_type = PaymentMethodData)]\n pub payment_method_data: PaymentMethodData,\n\n /// Enum representing the type of payment method being used\n /// (e.g., Card, Wallet, UPI, BankTransfer, etc.).\n #[schema(value_type = PaymentMethod)]\n pub payment_method: common_enums::PaymentMethod,\n\n /// Can be used to specify the Payment Method Type\n #[schema(value_type = Option, example = \"debit\")]\n pub payment_method_type: Option,\n\n /// Optional secret value used to identify and authorize the client making the request.\n /// This can help ensure that the payment session is secure and valid.\n #[schema(value_type = Option)]\n pub client_secret: Option>,\n\n /// Optional identifier for the business profile associated with the payment.\n /// This determines which configurations, rules, and branding are applied to the transaction.\n #[schema(value_type = Option)]\n pub profile_id: Option,\n\n /// Optional billing address of the customer.\n /// This can be used for fraud detection, authentication, or compliance purposes.\n #[schema(value_type = Option
)]\n pub billing: Option
,\n\n /// Optional shipping address of the customer.\n /// This can be useful for logistics, verification, or additional risk checks.\n #[schema(value_type = Option
)]\n pub shipping: Option
,\n\n /// Optional information about the customer's browser (user-agent, language, etc.).\n /// This is typically used to support 3DS authentication flows and improve risk assessment.\n #[schema(value_type = Option)]\n pub browser_information: Option,\n\n /// Optional email address of the customer.\n /// Used for customer identification, communication, and possibly for 3DS or fraud checks.\n #[schema(value_type = Option)]\n pub email: Option,\n}\n\n#[cfg(feature = \"v1\")]\nimpl AuthenticationEligibilityRequest {\n pub fn get_next_action_api(\n &self,\n base_url: String,\n authentication_id: String,\n ) -> CustomResult {\n let url = format!(\"{base_url}/authentication/{authentication_id}/authenticate\");\n Ok(NextAction {\n url: url::Url::parse(&url).change_context(errors::ParsingError::UrlParsingError)?,\n http_method: common_utils::request::Method::Post,\n })\n }\n\n pub fn get_billing_address(&self) -> Option
{\n self.billing.clone()\n }\n\n pub fn get_shipping_address(&self) -> Option
{\n self.shipping.clone()\n }\n\n pub fn get_browser_information(&self) -> Option {\n self.browser_information.clone()\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, ToSchema)]\npub struct AuthenticationEligibilityResponse {\n /// The unique identifier for this authentication.\n #[schema(value_type = String, example = \"auth_mbabizu24mvu3mela5njyhpit4\")]\n pub authentication_id: id_type::AuthenticationId,\n /// The URL to which the user should be redirected after authentication.\n #[schema(value_type = NextAction)]\n pub next_action: NextAction,\n /// The current status of the authentication (e.g., Started).\n #[schema(value_type = AuthenticationStatus)]\n pub status: common_enums::AuthenticationStatus,\n /// The 3DS data for this authentication.\n #[schema(value_type = Option)]\n pub eligibility_response_params: Option,\n /// The metadata for this authentication.\n #[schema(value_type = serde_json::Value)]\n pub connector_metadata: Option,\n /// The unique identifier for this authentication.\n #[schema(value_type = String)]\n pub profile_id: id_type::ProfileId,\n /// The error message for this authentication.\n #[schema(value_type = Option)]\n pub error_message: Option,\n /// The error code for this authentication.\n #[schema(value_type = Option)]\n pub error_code: Option,\n /// The connector used for this authentication.\n #[schema(value_type = Option)]\n pub authentication_connector: Option,\n /// Billing address\n #[schema(value_type = Option
)]\n pub billing: Option
,\n /// Shipping address\n #[schema(value_type = Option
)]\n pub shipping: Option
,\n /// Browser information\n #[schema(value_type = Option)]\n pub browser_information: Option,\n /// Email\n #[schema(value_type = Option)]\n pub email: common_utils::crypto::OptionalEncryptableEmail,\n /// Acquirer details information.\n #[schema(value_type = Option)]\n pub acquirer_details: Option,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationEligibilityCheckRequest {\n /// The unique identifier for this authentication.\n /// Added in the request for api event metrics, populated from path parameter\n #[serde(skip)]\n pub authentication_id: id_type::AuthenticationId,\n /// Optional secret value used to identify and authorize the client making the request.\n /// This can help ensure that the payment session is secure and valid.\n #[schema(value_type = Option)]\n pub client_secret: Option>,\n /// The data for this authentication eligibility check.\n pub eligibility_check_data: AuthenticationEligibilityCheckData,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, ToSchema)]\npub struct AuthenticationEligibilityCheckResponse {\n /// The unique identifier for this authentication.\n #[schema(value_type = String, example = \"auth_mbabizu24mvu3mela5njyhpit4\")]\n pub authentication_id: id_type::AuthenticationId,\n // The next action for this authentication eligibility check.\n pub sdk_next_action: AuthenticationSdkNextAction,\n}\n\n#[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)]\n#[serde(rename_all = \"snake_case\")]\npub enum AuthenticationSdkNextAction {\n /// The next action is to await for a merchant callback\n AwaitMerchantCallback,\n /// The next action is to deny the payment with an error message\n Deny { message: String },\n /// The next action is to proceed with the payment\n Proceed,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationRetrieveEligibilityCheckRequest {\n /// The unique identifier for this authentication.\n /// Added in the request for api event metrics, populated from path parameter\n #[serde(skip)]\n pub authentication_id: id_type::AuthenticationId,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationRetrieveEligibilityCheckResponse {\n /// The unique identifier for this authentication.\n /// Added in the request for api event metrics, populated from path parameter\n #[serde(skip)]\n pub authentication_id: id_type::AuthenticationId,\n /// The data for this authentication eligibility check.\n pub eligibility_check_data: AuthenticationEligibilityCheckResponseData,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\n#[serde(rename_all = \"snake_case\")]\npub enum AuthenticationEligibilityCheckData {\n ClickToPay(ClickToPayEligibilityCheckData),\n}\n\n#[cfg(feature = \"v1\")]\nimpl AuthenticationEligibilityCheckData {\n pub fn get_click_to_pay_data(&self) -> Option<&ClickToPayEligibilityCheckData> {\n match self {\n Self::ClickToPay(data) => Some(data),\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\n#[serde(rename_all = \"snake_case\")]\npub enum AuthenticationEligibilityCheckResponseData {\n ClickToPayEnrollmentStatus(ClickToPayEligibilityCheckResponseData),\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\npub struct ClickToPayEligibilityCheckData {\n // Visa specific eligibility check data\n pub visa: Option,\n // MasterCard specific eligibility check data\n pub mastercard: Option,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, ToSchema)]\npub struct ClickToPayEligibilityCheckResponseData {\n // Visa specific eligibility check data\n pub visa: Option,\n // MasterCard specific eligibility check data\n pub mastercard: Option,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]\n#[serde(rename_all = \"camelCase\")]\npub struct VisaEligibilityCheckData {\n // Indicates whether the consumer is enrolled in Visa Secure program\n pub consumer_present: bool,\n // Status of the consumer in Visa Secure program]\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub consumer_status: Option,\n // Additional data for eligibility check\n #[serde(skip_serializing_if = \"Option::is_none\")]\n #[schema(value_type = Option)]\n pub custom_data: Option,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]\n#[serde(rename_all = \"camelCase\")]\npub struct MasterCardEligibilityCheckData {\n // Indicates whether the consumer is enrolled in MasterCard Identity Check program\n pub consumer_present: bool,\n // Session ID from MasterCard Identity Check program\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub id_lookup_session_id: Option,\n // Timestamp of the last time the card was used\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub last_used_card_timestamp: Option,\n}\n\n#[derive(Debug, Serialize, ToSchema)]\npub enum EligibilityResponseParams {\n ThreeDsData(ThreeDsData),\n}\n\n#[derive(Debug, Serialize, ToSchema)]\npub struct ThreeDsData {\n /// The unique identifier for this authentication from the 3DS server.\n #[schema(value_type = String)]\n pub three_ds_server_transaction_id: Option,\n /// The maximum supported 3DS version.\n #[schema(value_type = String)]\n pub maximum_supported_3ds_version: Option,\n /// The unique identifier for this authentication from the connector.\n #[schema(value_type = String)]\n pub connector_authentication_id: Option,\n /// The data required to perform the 3DS method.\n #[schema(value_type = String)]\n pub three_ds_method_data: Option,\n /// The URL to which the user should be redirected after authentication.\n #[schema(value_type = String, example = \"https://example.com/redirect\")]\n pub three_ds_method_url: Option,\n /// The version of the message.\n #[schema(value_type = String)]\n pub message_version: Option,\n /// The unique identifier for this authentication.\n #[schema(value_type = String)]\n pub directory_server_id: Option,\n}\n\n#[derive(Debug, Serialize, ToSchema)]\npub struct NextAction {\n /// The URL for authenticatating the user.\n #[schema(value_type = String)]\n pub url: url::Url,\n /// The HTTP method to use for the request.\n #[schema(value_type = Method)]\n pub http_method: common_utils::request::Method,\n}\n\n#[cfg(feature = \"v1\")]\nimpl ApiEventMetric for AuthenticationEligibilityRequest {\n fn get_api_event_type(&self) -> Option {\n None\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl ApiEventMetric for AuthenticationEligibilityResponse {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationAuthenticateRequest {\n /// Authentication ID for the authentication\n #[serde(skip_deserializing)]\n pub authentication_id: id_type::AuthenticationId,\n /// Client secret for the authentication\n #[schema(value_type = String)]\n pub client_secret: Option>,\n /// SDK Information if request is from SDK\n pub sdk_information: Option,\n /// Device Channel indicating whether request is coming from App or Browser\n pub device_channel: DeviceChannel,\n /// Indicates if 3DS method data was successfully completed or not\n pub threeds_method_comp_ind: ThreeDsCompletionIndicator,\n}\n\nimpl ApiEventMetric for AuthenticationAuthenticateRequest {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationAuthenticateResponse {\n /// Indicates the transaction status\n #[serde(rename = \"trans_status\")]\n #[schema(value_type = Option)]\n pub transaction_status: Option,\n /// Access Server URL to be used for challenge submission\n #[schema(value_type = String, example = \"https://example.com/redirect\")]\n pub acs_url: Option,\n /// Challenge request which should be sent to acs_url\n pub challenge_request: Option,\n /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa)\n pub acs_reference_number: Option,\n /// Unique identifier assigned by the ACS to identify a single transaction\n pub acs_trans_id: Option,\n /// Unique identifier assigned by the 3DS Server to identify a single transaction\n pub three_ds_server_transaction_id: Option,\n /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message\n pub acs_signed_content: Option,\n /// Three DS Requestor URL\n pub three_ds_requestor_url: String,\n /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred\n pub three_ds_requestor_app_url: Option,\n\n /// The error message for this authentication.\n #[schema(value_type = String)]\n pub error_message: Option,\n /// The error code for this authentication.\n #[schema(value_type = String)]\n pub error_code: Option,\n /// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.\n #[schema(value_type = String)]\n pub authentication_value: Option>,\n\n /// The current status of the authentication (e.g., Started).\n #[schema(value_type = AuthenticationStatus)]\n pub status: common_enums::AuthenticationStatus,\n\n /// The connector to be used for authentication, if known.\n #[schema(value_type = Option, example = \"netcetera\")]\n pub authentication_connector: Option,\n\n /// The unique identifier for this authentication.\n #[schema(value_type = AuthenticationId, example = \"auth_mbabizu24mvu3mela5njyhpit4\")]\n pub authentication_id: id_type::AuthenticationId,\n\n /// The ECI value for this authentication.\n #[schema(value_type = String)]\n pub eci: Option,\n\n /// Acquirer details information.\n #[schema(value_type = Option)]\n pub acquirer_details: Option,\n}\n\nimpl ApiEventMetric for AuthenticationAuthenticateResponse {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Clone, Serialize, ToSchema)]\npub struct AuthenticationSyncResponse {\n // Core Authentication Fields (from AuthenticationResponse)\n /// The unique identifier for this authentication.\n #[schema(value_type = String, example = \"auth_mbabizu24mvu3mela5njyhpit4\")]\n pub authentication_id: id_type::AuthenticationId,\n\n /// This is an identifier for the merchant account.\n #[schema(value_type = String, example = \"merchant_abc\")]\n pub merchant_id: id_type::MerchantId,\n\n /// The current status of the authentication.\n #[schema(value_type = AuthenticationStatus)]\n pub status: common_enums::AuthenticationStatus,\n\n /// The client secret for this authentication.\n #[schema(value_type = Option)]\n pub client_secret: Option>,\n\n /// The amount for the transaction.\n #[schema(value_type = MinorUnit, example = 1000)]\n pub amount: common_utils::types::MinorUnit,\n\n /// The currency for the transaction.\n #[schema(value_type = Currency)]\n pub currency: enums::Currency,\n\n /// The connector used for authentication.\n #[schema(value_type = Option)]\n pub authentication_connector: Option,\n\n /// Whether 3DS challenge was forced.\n pub force_3ds_challenge: Option,\n\n /// The URL to which the user should be redirected after authentication.\n pub return_url: Option,\n\n #[schema(example = \"2022-09-10T10:11:12Z\")]\n #[serde(with = \"common_utils::custom_serde::iso8601\")]\n pub created_at: PrimitiveDateTime,\n\n /// The business profile that is associated with this authentication.\n #[schema(value_type = String)]\n pub profile_id: id_type::ProfileId,\n\n /// SCA exemption type for this authentication.\n #[schema(value_type = Option)]\n pub psd2_sca_exemption_type: Option,\n\n /// Acquirer details information.\n #[schema(value_type = Option)]\n pub acquirer_details: Option,\n\n /// The unique identifier from the 3DS server.\n #[schema(value_type = Option)]\n pub threeds_server_transaction_id: Option,\n\n /// The maximum supported 3DS version.\n #[schema(value_type = Option)]\n pub maximum_supported_3ds_version: Option,\n\n /// The unique identifier from the connector.\n #[schema(value_type = Option)]\n pub connector_authentication_id: Option,\n\n /// The data required to perform the 3DS method.\n #[schema(value_type = Option)]\n pub three_ds_method_data: Option,\n\n /// The URL for the 3DS method.\n #[schema(value_type = Option)]\n pub three_ds_method_url: Option,\n\n /// The version of the message.\n #[schema(value_type = Option)]\n pub message_version: Option,\n\n /// The metadata for this authentication.\n #[schema(value_type = Option)]\n pub connector_metadata: Option,\n\n /// The unique identifier for the directory server.\n #[schema(value_type = Option)]\n pub directory_server_id: Option,\n\n /// The insensitive payment method data\n pub payment_method_data: Option,\n\n /// The tokens for vaulted data\n pub vault_token_data: Option,\n\n /// Billing address.\n #[schema(value_type = Option
)]\n pub billing: Option
,\n\n /// Shipping address.\n #[schema(value_type = Option
)]\n pub shipping: Option
,\n\n /// Browser information.\n #[schema(value_type = Option)]\n pub browser_information: Option,\n\n /// Email.\n #[schema(value_type = Option)]\n pub email: common_utils::crypto::OptionalEncryptableEmail,\n\n /// Indicates the transaction status.\n #[serde(rename = \"trans_status\")]\n #[schema(value_type = Option)]\n pub transaction_status: Option,\n\n /// Access Server URL for challenge submission.\n pub acs_url: Option,\n\n /// Challenge request to be sent to acs_url.\n pub challenge_request: Option,\n\n /// Unique identifier assigned by EMVCo.\n pub acs_reference_number: Option,\n\n /// Unique identifier assigned by the ACS.\n pub acs_trans_id: Option,\n\n /// JWS object created by the ACS for the ARes message.\n pub acs_signed_content: Option,\n\n /// Three DS Requestor URL.\n pub three_ds_requestor_url: Option,\n\n /// Merchant app URL for OOB authentication.\n pub three_ds_requestor_app_url: Option,\n\n /// ECI value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern.\n pub eci: Option,\n\n // Common Error Fields (present in multiple responses)\n /// Error message if any.\n #[schema(value_type = Option)]\n pub error_message: Option,\n\n /// Error code if any.\n #[schema(value_type = Option)]\n pub error_code: Option,\n\n /// Profile Acquirer ID\n #[schema(value_type = Option)]\n pub profile_acquirer_id: Option,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Clone, Serialize, ToSchema)]\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum AuthenticationPaymentMethodDataResponse {\n CardData {\n /// card expiry year\n #[schema(value_type = Option)]\n card_expiry_year: Option>,\n\n /// card expiry month\n #[schema(value_type = Option)]\n card_expiry_month: Option>,\n },\n NetworkTokenData {\n /// network token expiry month\n #[schema(value_type = Option)]\n network_token_expiry_month: Option>,\n\n /// network token expiry year\n #[schema(value_type = Option)]\n network_token_expiry_year: Option>,\n },\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Clone, Serialize, ToSchema)]\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\npub enum AuthenticationVaultTokenData {\n CardData {\n /// token representing card_number\n #[schema(value_type = Option)]\n #[serde(rename = \"card_number\")]\n tokenized_card_number: Option>,\n\n /// token representing card_expiry_year\n #[schema(value_type = Option)]\n #[serde(rename = \"card_expiry_year\")]\n tokenized_card_expiry_year: Option>,\n\n /// token representing card_expiry_month\n #[schema(value_type = Option)]\n #[serde(rename = \"card_expiry_month\")]\n tokenized_card_expiry_month: Option>,\n\n /// token representing card_cvc\n #[schema(value_type = Option)]\n #[serde(rename = \"card_cvc\")]\n tokenized_card_cvc: Option>,\n },\n NetworkTokenData {\n /// token representing payment_token\n #[schema(value_type = Option)]\n #[serde(rename = \"network_token\")]\n tokenized_network_token: Option>,\n\n /// token representing token_expiry_year\n #[schema(value_type = Option)]\n #[serde(rename = \"network_token_expiry_year\")]\n tokenized_expiry_year: Option>,\n\n /// token representing token_expiry_month\n #[schema(value_type = Option)]\n #[serde(rename = \"network_token_expiry_month\")]\n tokenized_expiry_month: Option>,\n\n /// token representing token_cryptogram\n #[schema(value_type = Option)]\n #[serde(rename = \"network_token_cryptogram\")]\n tokenized_cryptogram: Option>,\n },\n}\n\n#[cfg(feature = \"v1\")]\nimpl ApiEventMetric for AuthenticationSyncResponse {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationSyncRequest {\n /// The client secret for this authentication.\n #[schema(value_type = String)]\n pub client_secret: Option>,\n /// Payment method data for Post Authentication sync\n pub payment_method_details: Option,\n /// Authentication ID for the authentication\n #[serde(skip_deserializing)]\n pub authentication_id: id_type::AuthenticationId,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct PostAuthenticationRequestPaymentMethodData {\n pub payment_method_type: AuthenticationPaymentMethodType,\n pub payment_method_data: AuthenticationPaymentMethodData,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub enum AuthenticationPaymentMethodType {\n #[serde(rename = \"ctp\")]\n ClickToPay,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\n#[serde(untagged)]\npub enum AuthenticationPaymentMethodData {\n ClickToPayDetails(ClickToPayDetails),\n}\n\nimpl AuthenticationPaymentMethodData {\n pub fn get_click_to_pay_details(&self) -> Option<&ClickToPayDetails> {\n match self {\n Self::ClickToPayDetails(details) => Some(details),\n }\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct ClickToPayDetails {\n /// merchant transaction id\n pub merchant_transaction_id: Option,\n /// network transaction correlation id\n pub correlation_id: Option,\n /// session transaction flow id\n pub x_src_flow_id: Option,\n /// provider Eg: Visa, Mastercard\n #[schema(value_type = Option)]\n pub provider: Option,\n /// Encrypted payload\n #[schema(value_type = Option)]\n pub encrypted_payload: Option>,\n}\n\nimpl ApiEventMetric for AuthenticationSyncRequest {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]\npub struct AuthenticationSyncPostUpdateRequest {\n /// Authentication ID for the authentication\n #[serde(skip_deserializing)]\n pub authentication_id: id_type::AuthenticationId,\n}\n\nimpl ApiEventMetric for AuthenticationSyncPostUpdateRequest {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\n#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]\npub struct AuthenticationSessionTokenRequest {\n /// Authentication ID for the authentication\n #[serde(skip_deserializing)]\n pub authentication_id: id_type::AuthenticationId,\n /// Client Secret for the authentication\n #[schema(value_type = String)]\n pub client_secret: Option>,\n}\n\n#[derive(Debug, serde::Serialize, Clone, ToSchema)]\npub struct AuthenticationSessionResponse {\n /// The identifier for the payment\n #[schema(value_type = String)]\n pub authentication_id: id_type::AuthenticationId,\n /// The list of session token object\n pub session_token: Vec,\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]\n#[serde(tag = \"wallet_name\")]\n#[serde(rename_all = \"snake_case\")]\npub enum AuthenticationSessionToken {\n /// The sessions response structure for ClickToPay\n ClickToPay(Box),\n NoSessionTokenReceived,\n}\n\nimpl ApiEventMetric for AuthenticationSessionTokenRequest {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n\nimpl ApiEventMetric for AuthenticationSessionResponse {\n fn get_api_event_type(&self) -> Option {\n Some(ApiEventsType::Authentication {\n authentication_id: self.authentication_id.clone(),\n })\n }\n}\n"} {"file_name": "crates__common_utils__src__new_type.rs", "text": "//! Contains new types with restrictions\nuse masking::{ExposeInterface, PeekInterface, Secret};\n\nuse crate::{\n consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH,\n pii::{Email, UpiVpaMaskingStrategy},\n transformers::ForeignFrom,\n};\n\n#[nutype::nutype(\n derive(Clone, Serialize, Deserialize, Debug),\n validate(len_char_min = 1, len_char_max = MAX_ALLOWED_MERCHANT_NAME_LENGTH)\n)]\npub struct MerchantName(String);\n\nimpl masking::SerializableSecret for MerchantName {}\n\n/// Function for masking alphanumeric characters in a string.\n///\n/// # Arguments\n/// `val`\n/// - holds reference to the string to be masked.\n/// `unmasked_char_count`\n/// - minimum character count to remain unmasked for identification\n/// - this number is for keeping the characters unmasked from\n/// both beginning (if feasible) and ending of the string.\n/// `min_masked_char_count`\n/// - this ensures the minimum number of characters to be masked\n///\n/// # Behaviour\n/// - Returns the original string if its length is less than or equal to `unmasked_char_count`.\n/// - If the string length allows, keeps `unmasked_char_count` characters unmasked at both start and end.\n/// - Otherwise, keeps `unmasked_char_count` characters unmasked only at the end.\n/// - Only alphanumeric characters are masked; other characters remain unchanged.\n///\n/// # Examples\n/// Sort Code\n/// (12-34-56, 2, 2) -> 12-**-56\n/// Routing number\n/// (026009593, 3, 3) -> 026***593\n/// CNPJ\n/// (12345678901, 4, 4) -> *******8901\n/// CNPJ\n/// (12345678901, 4, 3) -> 1234***8901\n/// Pix key\n/// (123e-a452-1243-1244-000, 4, 4) -> 123e-****-****-****-000\n/// IBAN\n/// (AL35202111090000000001234567, 5, 5) -> AL352******************34567\nfn apply_mask(val: &str, unmasked_char_count: usize, min_masked_char_count: usize) -> String {\n let len = val.len();\n if len <= unmasked_char_count {\n return val.to_string();\n }\n\n let mask_start_index =\n // For showing only last `unmasked_char_count` characters\n if len < (unmasked_char_count * 2 + min_masked_char_count) {\n 0\n // For showing first and last `unmasked_char_count` characters\n } else {\n unmasked_char_count\n };\n let mask_end_index = len - unmasked_char_count - 1;\n let range = mask_start_index..=mask_end_index;\n\n val.chars()\n .enumerate()\n .fold(String::new(), |mut acc, (index, ch)| {\n if ch.is_alphanumeric() && range.contains(&index) {\n acc.push('*');\n } else {\n acc.push(ch);\n }\n acc\n })\n}\n\n/// Masked sort code\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedSortCode(Secret);\nimpl From for MaskedSortCode {\n fn from(src: String) -> Self {\n let masked_value = apply_mask(src.as_ref(), 2, 2);\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedSortCode {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n/// Masked Routing number\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedRoutingNumber(Secret);\nimpl From for MaskedRoutingNumber {\n fn from(src: String) -> Self {\n let masked_value = apply_mask(src.as_ref(), 3, 3);\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedRoutingNumber {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n/// Masked bank account\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedBankAccount(Secret);\nimpl From for MaskedBankAccount {\n fn from(src: String) -> Self {\n let masked_value = apply_mask(src.as_ref(), 4, 4);\n Self(Secret::from(masked_value))\n }\n}\n\nimpl MaskedBankAccount {\n /// Expose the inner secret\n pub fn expose_inner(self) -> String {\n self.0.expose()\n }\n}\nimpl From> for MaskedBankAccount {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n/// Masked IBAN\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedIban(Secret);\nimpl From for MaskedIban {\n fn from(src: String) -> Self {\n let masked_value = apply_mask(src.as_ref(), 5, 5);\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedIban {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n/// Masked IBAN\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedBic(Secret);\nimpl From for MaskedBic {\n fn from(src: String) -> Self {\n let masked_value = apply_mask(src.as_ref(), 3, 2);\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedBic {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n/// Masked UPI ID\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedUpiVpaId(Secret);\nimpl From for MaskedUpiVpaId {\n fn from(src: String) -> Self {\n let unmasked_char_count = 2;\n let masked_value = if let Some((user_identifier, bank_or_psp)) = src.split_once('@') {\n let masked_user_identifier = user_identifier\n .to_string()\n .chars()\n .take(unmasked_char_count)\n .collect::()\n + &\"*\".repeat(user_identifier.len() - unmasked_char_count);\n format!(\"{masked_user_identifier}@{bank_or_psp}\")\n } else {\n let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8);\n masked_value\n };\n\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedUpiVpaId {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n/// Masked Email\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedEmail(Secret);\nimpl From for MaskedEmail {\n fn from(src: String) -> Self {\n let unmasked_char_count = 2;\n let masked_value = if let Some((user_identifier, domain)) = src.split_once('@') {\n let masked_user_identifier = user_identifier\n .to_string()\n .chars()\n .take(unmasked_char_count)\n .collect::()\n + &\"*\".repeat(user_identifier.len() - unmasked_char_count);\n format!(\"{masked_user_identifier}@{domain}\")\n } else {\n let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8);\n masked_value\n };\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedEmail {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\nimpl ForeignFrom for MaskedEmail {\n fn foreign_from(email: Email) -> Self {\n let email_value: String = email.expose().peek().to_owned();\n Self::from(email_value)\n }\n}\n\n/// Masked Phone Number\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedPhoneNumber(Secret);\nimpl From for MaskedPhoneNumber {\n fn from(src: String) -> Self {\n let unmasked_char_count = 2;\n let masked_value = if unmasked_char_count <= src.len() {\n let len = src.len();\n // mask every character except the last 2\n \"*\".repeat(len - unmasked_char_count).to_string()\n + src\n .get(len.saturating_sub(unmasked_char_count)..)\n .unwrap_or(\"\")\n } else {\n src\n };\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedPhoneNumber {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n/// Masked Psp token\n#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct MaskedPspToken(Secret);\nimpl From for MaskedPspToken {\n fn from(src: String) -> Self {\n let masked_value = apply_mask(src.as_ref(), 3, 3);\n Self(Secret::from(masked_value))\n }\n}\nimpl From> for MaskedPspToken {\n fn from(secret: Secret) -> Self {\n Self::from(secret.expose())\n }\n}\n\n#[cfg(test)]\nmod apply_mask_fn_test {\n use masking::PeekInterface;\n\n use crate::new_type::{\n apply_mask, MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode,\n MaskedUpiVpaId,\n };\n #[test]\n fn test_masked_types() {\n let sort_code = MaskedSortCode::from(\"110011\".to_string());\n let routing_number = MaskedRoutingNumber::from(\"056008849\".to_string());\n let bank_account = MaskedBankAccount::from(\"12345678901234\".to_string());\n let iban = MaskedIban::from(\"NL02ABNA0123456789\".to_string());\n let upi_vpa = MaskedUpiVpaId::from(\"someusername@okhdfcbank\".to_string());\n\n // Standard masked data tests\n assert_eq!(sort_code.0.peek().to_owned(), \"11**11\".to_string());\n assert_eq!(routing_number.0.peek().to_owned(), \"056***849\".to_string());\n assert_eq!(\n bank_account.0.peek().to_owned(),\n \"1234******1234\".to_string()\n );\n assert_eq!(iban.0.peek().to_owned(), \"NL02A********56789\".to_string());\n assert_eq!(\n upi_vpa.0.peek().to_owned(),\n \"so**********@okhdfcbank\".to_string()\n );\n }\n\n #[test]\n fn test_apply_mask_fn() {\n let value = \"12345678901\".to_string();\n\n // Generic masked tests\n assert_eq!(apply_mask(&value, 2, 2), \"12*******01\".to_string());\n assert_eq!(apply_mask(&value, 3, 2), \"123*****901\".to_string());\n assert_eq!(apply_mask(&value, 3, 3), \"123*****901\".to_string());\n assert_eq!(apply_mask(&value, 4, 3), \"1234***8901\".to_string());\n assert_eq!(apply_mask(&value, 4, 4), \"*******8901\".to_string());\n assert_eq!(apply_mask(&value, 5, 4), \"******78901\".to_string());\n assert_eq!(apply_mask(&value, 5, 5), \"******78901\".to_string());\n assert_eq!(apply_mask(&value, 6, 5), \"*****678901\".to_string());\n assert_eq!(apply_mask(&value, 6, 6), \"*****678901\".to_string());\n assert_eq!(apply_mask(&value, 7, 6), \"****5678901\".to_string());\n assert_eq!(apply_mask(&value, 7, 7), \"****5678901\".to_string());\n assert_eq!(apply_mask(&value, 8, 7), \"***45678901\".to_string());\n assert_eq!(apply_mask(&value, 8, 8), \"***45678901\".to_string());\n }\n}\n"} {"file_name": "crates__euclid__src__dssa__graph.rs", "text": "use std::{fmt::Debug, sync::Weak};\n\nuse hyperswitch_constraint_graph as cgraph;\nuse rustc_hash::{FxHashMap, FxHashSet};\n\nuse crate::{\n dssa::types,\n frontend::dir,\n types::{DataType, Metadata},\n};\n\npub mod euclid_graph_prelude {\n pub use hyperswitch_constraint_graph as cgraph;\n pub use rustc_hash::{FxHashMap, FxHashSet};\n pub use strum::EnumIter;\n\n pub use crate::{\n dssa::graph::*,\n frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue},\n types::*,\n };\n}\n\nimpl cgraph::KeyNode for dir::DirKey {}\n\nimpl cgraph::NodeViz for dir::DirKey {\n fn viz(&self) -> String {\n self.kind.to_string()\n }\n}\n\nimpl cgraph::ValueNode for dir::DirValue {\n type Key = dir::DirKey;\n\n fn get_key(&self) -> Self::Key {\n Self::get_key(self)\n }\n}\n\nimpl cgraph::NodeViz for dir::DirValue {\n fn viz(&self) -> String {\n match self {\n Self::PaymentMethod(pm) => pm.to_string(),\n Self::CardBin(bin) => bin.value.clone(),\n Self::ExtendedCardBin(ebin) => ebin.value.clone(),\n Self::CardType(ct) => ct.to_string(),\n Self::CardNetwork(cn) => cn.to_string(),\n Self::PayLaterType(plt) => plt.to_string(),\n Self::WalletType(wt) => wt.to_string(),\n Self::UpiType(ut) => ut.to_string(),\n Self::BankTransferType(btt) => btt.to_string(),\n Self::BankRedirectType(brt) => brt.to_string(),\n Self::BankDebitType(bdt) => bdt.to_string(),\n Self::CryptoType(ct) => ct.to_string(),\n Self::RewardType(rt) => rt.to_string(),\n Self::PaymentAmount(amt) => amt.number.to_string(),\n Self::PaymentCurrency(curr) => curr.to_string(),\n Self::AuthenticationType(at) => at.to_string(),\n Self::CaptureMethod(cm) => cm.to_string(),\n Self::BusinessCountry(bc) => bc.to_string(),\n Self::BillingCountry(bc) => bc.to_string(),\n Self::Connector(conn) => conn.connector.to_string(),\n Self::MetaData(mv) => format!(\"[{} = {}]\", mv.key, mv.value),\n Self::MandateAcceptanceType(mat) => mat.to_string(),\n Self::MandateType(mt) => mt.to_string(),\n Self::PaymentType(pt) => pt.to_string(),\n Self::VoucherType(vt) => vt.to_string(),\n Self::GiftCardType(gct) => gct.to_string(),\n Self::BusinessLabel(bl) => bl.value.to_string(),\n Self::SetupFutureUsage(sfu) => sfu.to_string(),\n Self::CardRedirectType(crt) => crt.to_string(),\n Self::RealTimePaymentType(rtpt) => rtpt.to_string(),\n Self::OpenBankingType(ob) => ob.to_string(),\n Self::MobilePaymentType(mpt) => mpt.to_string(),\n Self::IssuerName(issuer_name) => issuer_name.value.clone(),\n Self::IssuerCountry(issuer_country) => issuer_country.to_string(),\n Self::CustomerDevicePlatform(customer_device_platform) => {\n customer_device_platform.to_string()\n }\n Self::CustomerDeviceType(customer_device_type) => customer_device_type.to_string(),\n Self::CustomerDeviceDisplaySize(customer_device_display_size) => {\n customer_device_display_size.to_string()\n }\n Self::AcquirerCountry(acquirer_country) => acquirer_country.to_string(),\n Self::AcquirerFraudRate(acquirer_fraud_rate) => acquirer_fraud_rate.number.to_string(),\n Self::TransactionInitiator(transaction_initiator) => transaction_initiator.to_string(),\n Self::NetworkTokenType(ntt) => ntt.to_string(),\n }\n }\n}\n\n#[derive(Debug, Clone, serde::Serialize)]\n#[serde(tag = \"type\", content = \"details\", rename_all = \"snake_case\")]\npub enum AnalysisError {\n Graph(cgraph::GraphError),\n AssertionTrace {\n trace: Weak>,\n metadata: Metadata,\n },\n NegationTrace {\n trace: Weak>,\n metadata: Vec,\n },\n}\n\nimpl AnalysisError {\n fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError) -> Self {\n match graph_error {\n cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace {\n trace,\n metadata: metadata.clone(),\n },\n\n other => Self::Graph(other),\n }\n }\n\n fn negation_from_graph_error(\n metadata: Vec<&Metadata>,\n graph_error: cgraph::GraphError,\n ) -> Self {\n match graph_error {\n cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace {\n trace,\n metadata: metadata.iter().map(|m| (*m).clone()).collect(),\n },\n\n other => Self::Graph(other),\n }\n }\n}\n\n#[derive(Debug)]\npub struct AnalysisContext {\n keywise_values: FxHashMap>,\n}\n\nimpl AnalysisContext {\n pub fn from_dir_values(vals: impl IntoIterator) -> Self {\n let mut keywise_values: FxHashMap> =\n FxHashMap::default();\n\n for dir_val in vals {\n let key = dir_val.get_key();\n let set = keywise_values.entry(key).or_default();\n set.insert(dir_val);\n }\n\n Self { keywise_values }\n }\n\n pub fn insert(&mut self, value: dir::DirValue) {\n self.keywise_values\n .entry(value.get_key())\n .or_default()\n .insert(value);\n }\n\n pub fn remove(&mut self, value: dir::DirValue) {\n let set = self.keywise_values.entry(value.get_key()).or_default();\n\n set.remove(&value);\n\n if set.is_empty() {\n self.keywise_values.remove(&value.get_key());\n }\n }\n}\n\nimpl cgraph::CheckingContext for AnalysisContext {\n type Value = dir::DirValue;\n\n fn from_node_values(vals: impl IntoIterator) -> Self\n where\n L: Into,\n {\n let mut keywise_values: FxHashMap> =\n FxHashMap::default();\n\n for dir_val in vals.into_iter().map(L::into) {\n let key = dir_val.get_key();\n let set = keywise_values.entry(key).or_default();\n set.insert(dir_val);\n }\n\n Self { keywise_values }\n }\n\n fn check_presence(\n &self,\n value: &cgraph::NodeValue,\n strength: cgraph::Strength,\n ) -> bool {\n match value {\n cgraph::NodeValue::Key(k) => {\n self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak)\n }\n\n cgraph::NodeValue::Value(val) => {\n let key = val.get_key();\n let value_set = if let Some(set) = self.keywise_values.get(&key) {\n set\n } else {\n return matches!(strength, cgraph::Strength::Weak);\n };\n\n match key.kind.get_type() {\n DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => {\n value_set.contains(val)\n }\n DataType::Number => val.get_num_value().is_some_and(|num_val| {\n value_set.iter().any(|ctx_val| {\n ctx_val\n .get_num_value()\n .is_some_and(|ctx_num_val| num_val.fits(&ctx_num_val))\n })\n }),\n }\n }\n }\n }\n\n fn get_values_by_key(\n &self,\n key: &::Key,\n ) -> Option> {\n self.keywise_values\n .get(key)\n .map(|set| set.iter().cloned().collect())\n }\n}\n\npub trait CgraphExt {\n fn key_analysis(\n &self,\n key: dir::DirKey,\n ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), cgraph::GraphError>;\n\n fn value_analysis(\n &self,\n val: dir::DirValue,\n ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), cgraph::GraphError>;\n\n fn check_value_validity(\n &self,\n val: dir::DirValue,\n analysis_ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result>;\n\n fn key_value_analysis(\n &self,\n val: dir::DirValue,\n ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), cgraph::GraphError>;\n\n fn assertion_analysis(\n &self,\n positive_ctx: &[(&dir::DirValue, &Metadata)],\n analysis_ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), AnalysisError>;\n\n fn negation_analysis(\n &self,\n negative_ctx: &[(&[dir::DirValue], &Metadata)],\n analysis_ctx: &mut AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), AnalysisError>;\n\n fn perform_context_analysis(\n &self,\n ctx: &types::ConjunctiveContext<'_>,\n memo: &mut cgraph::Memoization,\n domains: Option<&[String]>,\n ) -> Result<(), AnalysisError>;\n}\n\nimpl CgraphExt for cgraph::ConstraintGraph {\n fn key_analysis(\n &self,\n key: dir::DirKey,\n ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), cgraph::GraphError> {\n self.value_map\n .get(&cgraph::NodeValue::Key(key))\n .map_or(Ok(()), |node_id| {\n self.check_node(\n ctx,\n *node_id,\n cgraph::Relation::Positive,\n cgraph::Strength::Strong,\n memo,\n cycle_map,\n domains,\n )\n })\n }\n\n fn value_analysis(\n &self,\n val: dir::DirValue,\n ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), cgraph::GraphError> {\n self.value_map\n .get(&cgraph::NodeValue::Value(val))\n .map_or(Ok(()), |node_id| {\n self.check_node(\n ctx,\n *node_id,\n cgraph::Relation::Positive,\n cgraph::Strength::Strong,\n memo,\n cycle_map,\n domains,\n )\n })\n }\n\n fn check_value_validity(\n &self,\n val: dir::DirValue,\n analysis_ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result> {\n let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val));\n\n let node_id = if let Some(nid) = maybe_node_id {\n nid\n } else {\n return Ok(false);\n };\n\n let result = self.check_node(\n analysis_ctx,\n *node_id,\n cgraph::Relation::Positive,\n cgraph::Strength::Weak,\n memo,\n cycle_map,\n domains,\n );\n\n match result {\n Ok(_) => Ok(true),\n Err(e) => {\n e.get_analysis_trace()?;\n Ok(false)\n }\n }\n }\n\n fn key_value_analysis(\n &self,\n val: dir::DirValue,\n ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), cgraph::GraphError> {\n self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains)\n .and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains))\n }\n\n fn assertion_analysis(\n &self,\n positive_ctx: &[(&dir::DirValue, &Metadata)],\n analysis_ctx: &AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), AnalysisError> {\n positive_ctx.iter().try_for_each(|(value, metadata)| {\n self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains)\n .map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e))\n })\n }\n\n fn negation_analysis(\n &self,\n negative_ctx: &[(&[dir::DirValue], &Metadata)],\n analysis_ctx: &mut AnalysisContext,\n memo: &mut cgraph::Memoization,\n cycle_map: &mut cgraph::CycleCheck,\n domains: Option<&[String]>,\n ) -> Result<(), AnalysisError> {\n let mut keywise_metadata: FxHashMap> = FxHashMap::default();\n let mut keywise_negation: FxHashMap> =\n FxHashMap::default();\n\n for (values, metadata) in negative_ctx {\n let mut metadata_added = false;\n\n for dir_value in *values {\n if !metadata_added {\n keywise_metadata\n .entry(dir_value.get_key())\n .or_default()\n .push(metadata);\n\n metadata_added = true;\n }\n\n keywise_negation\n .entry(dir_value.get_key())\n .or_default()\n .insert(dir_value);\n }\n }\n\n for (key, negation_set) in keywise_negation {\n let all_metadata = keywise_metadata.remove(&key).unwrap_or_default();\n let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default();\n\n self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains)\n .map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?;\n\n let mut value_set = if let Some(set) = key.kind.get_value_set() {\n set\n } else {\n continue;\n };\n\n value_set.retain(|v| !negation_set.contains(v));\n\n for value in value_set {\n analysis_ctx.insert(value.clone());\n self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains)\n .map_err(|e| {\n AnalysisError::negation_from_graph_error(all_metadata.clone(), e)\n })?;\n analysis_ctx.remove(value);\n }\n }\n\n Ok(())\n }\n\n fn perform_context_analysis(\n &self,\n ctx: &types::ConjunctiveContext<'_>,\n memo: &mut cgraph::Memoization,\n domains: Option<&[String]>,\n ) -> Result<(), AnalysisError> {\n let mut analysis_ctx = AnalysisContext::from_dir_values(\n ctx.iter()\n .filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()),\n );\n\n let positive_ctx = ctx\n .iter()\n .filter_map(|ctx_val| {\n ctx_val\n .value\n .get_assertion()\n .map(|val| (val, ctx_val.metadata))\n })\n .collect::>();\n self.assertion_analysis(\n &positive_ctx,\n &analysis_ctx,\n memo,\n &mut cgraph::CycleCheck::new(),\n domains,\n )?;\n\n let negative_ctx = ctx\n .iter()\n .filter_map(|ctx_val| {\n ctx_val\n .value\n .get_negation()\n .map(|vals| (vals, ctx_val.metadata))\n })\n .collect::>();\n self.negation_analysis(\n &negative_ctx,\n &mut analysis_ctx,\n memo,\n &mut cgraph::CycleCheck::new(),\n domains,\n )?;\n\n Ok(())\n }\n}\n\n#[cfg(test)]\nmod test {\n use std::ops::Deref;\n\n use euclid_macros::knowledge;\n use hyperswitch_constraint_graph::CycleCheck;\n\n use super::*;\n use crate::{dirval, frontend::dir::enums};\n\n #[test]\n fn test_strong_positive_relation_success() {\n let graph = knowledge! {\n PaymentMethod(Card) ->> CaptureMethod(Automatic);\n PaymentMethod(not Wallet)\n & PaymentMethod(not PayLater) -> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = Card),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_ok());\n }\n\n #[test]\n fn test_strong_positive_relation_failure() {\n let graph = knowledge! {\n PaymentMethod(Card) ->> CaptureMethod(Automatic);\n PaymentMethod(not Wallet) -> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_err());\n }\n\n #[test]\n fn test_strong_negative_relation_success() {\n let graph = knowledge! {\n PaymentMethod(Card) -> CaptureMethod(Automatic);\n PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = Card),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_ok());\n }\n\n #[test]\n fn test_strong_negative_relation_failure() {\n let graph = knowledge! {\n PaymentMethod(Card) -> CaptureMethod(Automatic);\n PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = Wallet),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_err());\n }\n\n #[test]\n fn test_normal_one_of_failure() {\n let graph = knowledge! {\n PaymentMethod(Card) -> CaptureMethod(Automatic);\n PaymentMethod(Wallet) -> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = PayLater),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n assert!(matches!(\n *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())\n .expect(\"Expected Arc\"),\n cgraph::AnalysisTrace::Value {\n predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)),\n ..\n }\n ));\n }\n\n #[test]\n fn test_all_aggregator_success() {\n let graph = knowledge! {\n PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(PaymentMethod = Card),\n dirval!(CaptureMethod = Automatic),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_ok());\n }\n\n #[test]\n fn test_all_aggregator_failure() {\n let graph = knowledge! {\n PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = PayLater),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_err());\n }\n\n #[test]\n fn test_all_aggregator_mandatory_failure() {\n let graph = knowledge! {\n PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);\n };\n let mut memo = cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = PayLater),\n ]),\n &mut memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(matches!(\n *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())\n .expect(\"Expected Arc\"),\n cgraph::AnalysisTrace::Value {\n predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)),\n ..\n }\n ));\n }\n\n #[test]\n fn test_in_aggregator_success() {\n let graph = knowledge! {\n PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = Card),\n dirval!(PaymentMethod = Wallet),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_ok());\n }\n\n #[test]\n fn test_in_aggregator_failure() {\n let graph = knowledge! {\n PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = Card),\n dirval!(PaymentMethod = Wallet),\n dirval!(PaymentMethod = PayLater),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_err());\n }\n\n #[test]\n fn test_not_in_aggregator_success() {\n let graph = knowledge! {\n PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = PayLater),\n dirval!(PaymentMethod = BankRedirect),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_ok());\n }\n\n #[test]\n fn test_not_in_aggregator_failure() {\n let graph = knowledge! {\n PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = PayLater),\n dirval!(PaymentMethod = BankRedirect),\n dirval!(PaymentMethod = Card),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n assert!(result.is_err());\n }\n\n #[test]\n fn test_in_aggregator_failure_trace() {\n let graph = knowledge! {\n PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic);\n };\n let memo = &mut cgraph::Memoization::new();\n let result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(CaptureMethod = Automatic),\n dirval!(PaymentMethod = Card),\n dirval!(PaymentMethod = Wallet),\n dirval!(PaymentMethod = PayLater),\n ]),\n memo,\n &mut CycleCheck::new(),\n None,\n );\n\n if let cgraph::AnalysisTrace::Value {\n predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)),\n ..\n } = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())\n .expect(\"Expected arc\")\n .deref()\n {\n assert!(matches!(\n *Weak::upgrade(agg_error.deref()).expect(\"Expected Arc\"),\n cgraph::AnalysisTrace::InAggregation {\n found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)),\n ..\n }\n ));\n } else {\n panic!(\"Failed unwrapping OnlyInAggregation trace from AnalysisTrace\");\n }\n }\n\n #[test]\n fn test_memoization_in_kgraph() {\n let mut builder = cgraph::ConstraintGraphBuilder::new();\n let _node_1 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),\n None,\n None::<()>,\n );\n let _node_2 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)),\n None,\n None::<()>,\n );\n let _node_3 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::BusinessCountry(\n enums::BusinessCountry::UnitedStatesOfAmerica,\n )),\n None,\n None::<()>,\n );\n let mut memo = cgraph::Memoization::new();\n let mut cycle_map = CycleCheck::new();\n let _edge_1 = builder\n .make_edge(\n _node_1,\n _node_2,\n cgraph::Strength::Strong,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_2 = builder\n .make_edge(\n _node_2,\n _node_3,\n cgraph::Strength::Strong,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to an edge\");\n let graph = builder.build();\n let _result = graph.key_value_analysis(\n dirval!(BusinessCountry = UnitedStatesOfAmerica),\n &AnalysisContext::from_dir_values([\n dirval!(PaymentMethod = Wallet),\n dirval!(BillingCountry = India),\n dirval!(BusinessCountry = UnitedStatesOfAmerica),\n ]),\n &mut memo,\n &mut cycle_map,\n None,\n );\n let _answer = memo\n .get(&(\n _node_3,\n cgraph::Relation::Positive,\n cgraph::Strength::Strong,\n ))\n .expect(\"Memoization not workng\");\n matches!(_answer, Ok(()));\n }\n\n #[test]\n fn test_cycle_resolution_in_graph() {\n let mut builder = cgraph::ConstraintGraphBuilder::new();\n let _node_1 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),\n None,\n None::<()>,\n );\n let _node_2 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),\n None,\n None::<()>,\n );\n let mut memo = cgraph::Memoization::new();\n let mut cycle_map = CycleCheck::new();\n let _edge_1 = builder\n .make_edge(\n _node_1,\n _node_2,\n cgraph::Strength::Weak,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_2 = builder\n .make_edge(\n _node_2,\n _node_1,\n cgraph::Strength::Weak,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to an edge\");\n let graph = builder.build();\n let _result = graph.key_value_analysis(\n dirval!(PaymentMethod = Wallet),\n &AnalysisContext::from_dir_values([\n dirval!(PaymentMethod = Wallet),\n dirval!(PaymentMethod = Card),\n ]),\n &mut memo,\n &mut cycle_map,\n None,\n );\n\n assert!(_result.is_ok());\n }\n\n #[test]\n fn test_cycle_resolution_in_graph1() {\n let mut builder = cgraph::ConstraintGraphBuilder::new();\n let _node_1 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(\n enums::CaptureMethod::Automatic,\n )),\n None,\n None::<()>,\n );\n\n let _node_2 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),\n None,\n None::<()>,\n );\n let _node_3 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),\n None,\n None::<()>,\n );\n let mut memo = cgraph::Memoization::new();\n let mut cycle_map = CycleCheck::new();\n\n let _edge_1 = builder\n .make_edge(\n _node_1,\n _node_2,\n cgraph::Strength::Weak,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_2 = builder\n .make_edge(\n _node_1,\n _node_3,\n cgraph::Strength::Weak,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_3 = builder\n .make_edge(\n _node_2,\n _node_1,\n cgraph::Strength::Weak,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_4 = builder\n .make_edge(\n _node_3,\n _node_1,\n cgraph::Strength::Strong,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n\n let graph = builder.build();\n let _result = graph.key_value_analysis(\n dirval!(CaptureMethod = Automatic),\n &AnalysisContext::from_dir_values([\n dirval!(PaymentMethod = Card),\n dirval!(PaymentMethod = Wallet),\n dirval!(CaptureMethod = Automatic),\n ]),\n &mut memo,\n &mut cycle_map,\n None,\n );\n\n assert!(_result.is_ok());\n }\n\n #[test]\n fn test_cycle_resolution_in_graph2() {\n let mut builder = cgraph::ConstraintGraphBuilder::new();\n let _node_0 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::BillingCountry(\n enums::BillingCountry::Afghanistan,\n )),\n None,\n None::<()>,\n );\n\n let _node_1 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(\n enums::CaptureMethod::Automatic,\n )),\n None,\n None::<()>,\n );\n\n let _node_2 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),\n None,\n None::<()>,\n );\n let _node_3 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),\n None,\n None::<()>,\n );\n\n let _node_4 = builder.make_value_node(\n cgraph::NodeValue::Value(dir::DirValue::PaymentCurrency(enums::PaymentCurrency::USD)),\n None,\n None::<()>,\n );\n\n let mut memo = cgraph::Memoization::new();\n let mut cycle_map = CycleCheck::new();\n\n let _edge_1 = builder\n .make_edge(\n _node_0,\n _node_1,\n cgraph::Strength::Weak,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_2 = builder\n .make_edge(\n _node_1,\n _node_2,\n cgraph::Strength::Normal,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_3 = builder\n .make_edge(\n _node_1,\n _node_3,\n cgraph::Strength::Weak,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_4 = builder\n .make_edge(\n _node_3,\n _node_4,\n cgraph::Strength::Normal,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_5 = builder\n .make_edge(\n _node_2,\n _node_4,\n cgraph::Strength::Normal,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n\n let _edge_6 = builder\n .make_edge(\n _node_4,\n _node_1,\n cgraph::Strength::Normal,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n let _edge_7 = builder\n .make_edge(\n _node_4,\n _node_0,\n cgraph::Strength::Normal,\n cgraph::Relation::Positive,\n None::,\n )\n .expect(\"Failed to make an edge\");\n\n let graph = builder.build();\n let _result = graph.key_value_analysis(\n dirval!(BillingCountry = Afghanistan),\n &AnalysisContext::from_dir_values([\n dirval!(PaymentCurrency = USD),\n dirval!(PaymentMethod = Card),\n dirval!(PaymentMethod = Wallet),\n dirval!(CaptureMethod = Automatic),\n dirval!(BillingCountry = Afghanistan),\n ]),\n &mut memo,\n &mut cycle_map,\n None,\n );\n\n assert!(_result.is_ok());\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__airwallex.rs", "text": "pub mod transformers;\n\nuse std::sync::LazyLock;\n\nuse api_models::webhooks::IncomingWebhookEvent;\nuse common_enums::{enums, CallConnectorAction, PaymentAction};\nuse common_utils::{\n crypto,\n errors::CustomResult,\n ext_traits::{ByteSliceExt, BytesExt, ValueExt},\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{\n AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit,\n StringMinorUnitForConnector,\n },\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n payment_method_data::PaymentMethodData,\n router_data::{AccessToken, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{\n Authorize, Capture, CreateOrder, PSync, PaymentMethodToken, Session, SetupMandate, Void,\n },\n refunds::{Execute, RSync},\n CompleteAuthorize, CreateConnectorCustomer,\n },\n router_request_types::{\n AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData,\n CreateOrderRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n ConnectorCustomerRouterData, CreateOrderRouterData, PaymentsAuthorizeRouterData,\n PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,\n PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,\n ConnectorSpecifications, ConnectorValidation,\n },\n configs::Connectors,\n disputes::DisputePayload,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, ConnectorCustomerType, CreateOrderType, Response},\n webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},\n};\nuse masking::{Mask, PeekInterface};\nuse router_env::logger;\nuse transformers as airwallex;\n\nuse crate::{\n connectors::airwallex::transformers::AirwallexAuthorizeResponse,\n constants::headers,\n types::{RefreshTokenRouterData, ResponseRouterData},\n utils::{\n self as connector_utils, convert_amount, AccessTokenRequestInfo, ForeignTryFrom,\n PaymentMethodDataType, PaymentsAuthorizeRequestData, RefundsRequestData,\n },\n};\n\n#[derive(Clone)]\npub struct Airwallex {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n amount_converter_to_string_minor:\n &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Airwallex {\n pub const fn new() -> &'static Self {\n &Self {\n amount_converter: &StringMajorUnitForConnector,\n amount_converter_to_string_minor: &StringMinorUnitForConnector,\n }\n }\n}\n\nimpl ConnectorCommonExt for Airwallex\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let mut headers = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )];\n let access_token = req\n .access_token\n .clone()\n .ok_or(errors::ConnectorError::FailedToObtainAuthType)?;\n\n let auth_header = (\n headers::AUTHORIZATION.to_string(),\n format!(\"Bearer {}\", access_token.token.peek()).into_masked(),\n );\n\n headers.push(auth_header);\n Ok(headers)\n }\n}\n\nimpl ConnectorCommon for Airwallex {\n fn id(&self) -> &'static str {\n \"airwallex\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.airwallex.base_url.as_ref()\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n logger::debug!(payu_error_response=?res);\n\n let status_code = res.status_code;\n let response: Result =\n res.response.parse_struct(\"Airwallex ErrorResponse\");\n\n match response {\n Ok(response) => {\n event_builder.map(|i| i.set_error_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n let network_error_message = response\n .provider_original_response_code\n .clone()\n .and_then(airwallex::map_error_code_to_message);\n Ok(ErrorResponse {\n status_code,\n code: response.code,\n message: response.message,\n reason: response.source,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: response.provider_original_response_code.clone(),\n network_error_message,\n connector_metadata: None,\n })\n }\n Err(error_msg) => {\n event_builder.map(|event| event.set_error(serde_json::json!({\"error\": res.response.escape_ascii().to_string(), \"status_code\": status_code})));\n router_env::logger::error!(deserialization_error =? error_msg);\n connector_utils::handle_json_response_deserialization_failure(res, \"tesouro\")\n }\n }\n }\n}\n\nimpl ConnectorValidation for Airwallex {\n fn validate_mandate_payment(\n &self,\n pm_type: Option,\n pm_data: PaymentMethodData,\n ) -> CustomResult<(), errors::ConnectorError> {\n let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);\n connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())\n }\n}\n\nimpl api::Payment for Airwallex {}\nimpl api::PaymentsCompleteAuthorize for Airwallex {}\nimpl api::PaymentsCreateOrder for Airwallex {}\nimpl api::MandateSetup for Airwallex {}\nimpl ConnectorIntegration\n for Airwallex\n{\n fn build_request(\n &self,\n _req: &SetupMandateRouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(\n errors::ConnectorError::NotImplemented(\"Setup Mandate flow for Airwallex\".to_string())\n .into(),\n )\n }\n}\n\nimpl api::ConnectorCustomer for Airwallex {}\n\nimpl ConnectorIntegration\n for Airwallex\n{\n fn get_headers(\n &self,\n req: &ConnectorCustomerRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &ConnectorCustomerRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}\",\n self.base_url(connectors),\n \"api/v1/pa/customers/create\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &ConnectorCustomerRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = airwallex::CustomerRequest::try_from(req)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &ConnectorCustomerRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&ConnectorCustomerType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(ConnectorCustomerType::get_headers(self, req, connectors)?)\n .set_body(ConnectorCustomerType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &ConnectorCustomerRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult\n where\n PaymentsResponseData: Clone,\n {\n let response: airwallex::AirwallexCustomerResponse = res\n .response\n .parse_struct(\"AirwallexCustomerResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::PaymentToken for Airwallex {}\n\nimpl ConnectorIntegration\n for Airwallex\n{\n // Not Implemented (R)\n}\n\nimpl api::ConnectorAccessToken for Airwallex {}\n\nimpl ConnectorIntegration for Airwallex {\n fn get_url(\n &self,\n _req: &RefreshTokenRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}\",\n self.base_url(connectors),\n \"api/v1/authentication/login\"\n ))\n }\n\n fn get_headers(\n &self,\n req: &RefreshTokenRouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let headers = vec![\n (\n headers::X_API_KEY.to_string(),\n req.request.app_id.clone().into_masked(),\n ),\n (\"Content-Length\".to_string(), \"0\".to_string().into()),\n (\n \"x-client-id\".to_string(),\n req.get_request_id()?.into_masked(),\n ),\n ];\n Ok(headers)\n }\n\n fn build_request(\n &self,\n req: &RefreshTokenRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let req = Some(\n RequestBuilder::new()\n .method(Method::Post)\n .attach_default_headers()\n .headers(types::RefreshTokenType::get_headers(self, req, connectors)?)\n .url(&types::RefreshTokenType::get_url(self, req, connectors)?)\n .build(),\n );\n logger::debug!(payu_access_token_request=?req);\n Ok(req)\n }\n fn handle_response(\n &self,\n data: &RefreshTokenRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n logger::debug!(access_token_response=?res);\n let response: airwallex::AirwallexAuthUpdateResponse = res\n .response\n .parse_struct(\"airwallex AirwallexAuthUpdateResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Airwallex {\n fn get_headers(\n &self,\n req: &CreateOrderRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &CreateOrderRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}\",\n self.base_url(connectors),\n \"api/v1/pa/payment_intents/create\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &CreateOrderRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n let connector_router_data = airwallex::AirwallexRouterData::try_from((amount, req))?;\n let connector_req = airwallex::AirwallexIntentRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &CreateOrderRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&CreateOrderType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(CreateOrderType::get_headers(self, req, connectors)?)\n .set_body(CreateOrderType::get_request_body(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &CreateOrderRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: airwallex::AirwallexOrderResponse = res\n .response\n .parse_struct(\"airwallex AirwallexOrderResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::PaymentAuthorize for Airwallex {}\n\n#[async_trait::async_trait]\nimpl ConnectorIntegration for Airwallex {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}{}{}\",\n self.base_url(connectors),\n \"api/v1/pa/payment_intents/\",\n req.request.get_order_id()?,\n \"/confirm\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount_in_minor_unit = MinorUnit::new(req.request.amount);\n let amount = convert_amount(\n self.amount_converter,\n amount_in_minor_unit,\n req.request.currency,\n )?;\n let connector_router_data = airwallex::AirwallexRouterData::try_from((amount, req))?;\n let connector_req = airwallex::AirwallexPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: AirwallexAuthorizeResponse = res\n .response\n .parse_struct(\"AirwallexAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n RouterData::foreign_try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::PaymentSync for Airwallex {}\nimpl ConnectorIntegration for Airwallex {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req\n .request\n .connector_transaction_id\n .get_connector_transaction_id()\n .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;\n Ok(format!(\n \"{}{}{}\",\n self.base_url(connectors),\n \"api/v1/pa/payment_intents/\",\n connector_payment_id,\n ))\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n logger::debug!(payment_sync_response=?res);\n let response: airwallex::AirwallexPaymentsSyncResponse = res\n .response\n .parse_struct(\"airwallex AirwallexPaymentsSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Airwallex\n{\n fn get_headers(\n &self,\n req: &PaymentsCompleteAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n fn get_url(\n &self,\n req: &PaymentsCompleteAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req\n .request\n .connector_transaction_id\n .clone()\n .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;\n Ok(format!(\n \"{}api/v1/pa/payment_intents/{}/confirm_continue\",\n self.base_url(connectors),\n connector_payment_id,\n ))\n }\n fn get_request_body(\n &self,\n req: &PaymentsCompleteAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let req_obj = airwallex::AirwallexCompleteRequest::try_from(req)?;\n\n Ok(RequestContent::Json(Box::new(req_obj)))\n }\n fn build_request(\n &self,\n req: &PaymentsCompleteAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsCompleteAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .headers(types::PaymentsCompleteAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &PaymentsCompleteAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: airwallex::AirwallexPaymentsResponse = res\n .response\n .parse_struct(\"AirwallexPaymentsResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::PaymentCapture for Airwallex {}\nimpl ConnectorIntegration for Airwallex {\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}{}{}\",\n self.base_url(connectors),\n \"api/v1/pa/payment_intents/\",\n req.request.connector_transaction_id,\n \"/capture\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = airwallex::AirwallexPaymentsCaptureRequest::try_from(req)?;\n\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsCaptureType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: airwallex::AirwallexPaymentsResponse = res\n .response\n .parse_struct(\"Airwallex PaymentsResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::PaymentSession for Airwallex {}\n\nimpl ConnectorIntegration for Airwallex {\n //TODO: implement sessions flow\n}\n\nimpl api::PaymentVoid for Airwallex {}\n\nimpl ConnectorIntegration for Airwallex {\n fn get_headers(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}{}{}\",\n self.base_url(connectors),\n \"api/v1/pa/payment_intents/\",\n req.request.connector_transaction_id,\n \"/cancel\"\n ))\n }\n fn get_request_body(\n &self,\n req: &PaymentsCancelRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = airwallex::AirwallexPaymentsCancelRequest::try_from(req)?;\n\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n fn handle_response(\n &self,\n data: &PaymentsCancelRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: airwallex::AirwallexPaymentsResponse = res\n .response\n .parse_struct(\"Airwallex PaymentsResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn build_request(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)\n .set_body(types::PaymentsVoidType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::Refund for Airwallex {}\nimpl api::RefundExecute for Airwallex {}\nimpl api::RefundSync for Airwallex {}\n\nimpl ConnectorIntegration for Airwallex {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}\",\n self.base_url(connectors),\n \"api/v1/pa/refunds/create\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount_in_minor_unit = MinorUnit::new(req.request.refund_amount);\n let amount = convert_amount(\n self.amount_converter,\n amount_in_minor_unit,\n req.request.currency,\n )?;\n let connector_router_data = airwallex::AirwallexRouterData::try_from((amount, req))?;\n let connector_req = airwallex::AirwallexRefundRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&types::RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundExecuteType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::RefundExecuteType::get_request_body(\n self, req, connectors,\n )?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n logger::debug!(target: \"router::connector::airwallex\", response=?res);\n let response: airwallex::RefundResponse = res\n .response\n .parse_struct(\"airwallex RefundResponse\")\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Airwallex {\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}{}\",\n self.base_url(connectors),\n \"/api/v1/pa/refunds/\",\n req.request.get_connector_refund_id()?\n ))\n }\n\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n logger::debug!(target: \"router::connector::airwallex\", response=?res);\n let response: airwallex::RefundResponse = res\n .response\n .parse_struct(\"airwallex RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl IncomingWebhook for Airwallex {\n fn get_webhook_source_verification_algorithm(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Box::new(crypto::HmacSha256))\n }\n\n fn get_webhook_source_verification_signature(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n let security_header = request\n .headers\n .get(\"x-signature\")\n .map(|header_value| {\n header_value\n .to_str()\n .map(String::from)\n .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)\n })\n .ok_or(errors::ConnectorError::WebhookSignatureNotFound)??;\n\n hex::decode(security_header)\n .change_context(errors::ConnectorError::WebhookSignatureNotFound)\n }\n\n fn get_webhook_source_verification_message(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n _merchant_id: &common_utils::id_type::MerchantId,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n let timestamp = request\n .headers\n .get(\"x-timestamp\")\n .map(|header_value| {\n header_value\n .to_str()\n .map(String::from)\n .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)\n })\n .ok_or(errors::ConnectorError::WebhookSignatureNotFound)??;\n\n Ok(format!(\"{}{}\", timestamp, String::from_utf8_lossy(request.body)).into_bytes())\n }\n\n fn get_webhook_object_reference_id(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n let details: airwallex::AirwallexWebhookData = request\n .body\n .parse_struct(\"airwallexWebhookData\")\n .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;\n\n if airwallex::is_transaction_event(&details.name) {\n Ok(api_models::webhooks::ObjectReferenceId::PaymentId(\n api_models::payments::PaymentIdType::ConnectorTransactionId(\n details\n .source_id\n .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,\n ),\n ))\n } else if airwallex::is_refund_event(&details.name) {\n Ok(api_models::webhooks::ObjectReferenceId::RefundId(\n api_models::webhooks::RefundIdType::ConnectorRefundId(\n details\n .source_id\n .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,\n ),\n ))\n } else if airwallex::is_dispute_event(&details.name) {\n let dispute_details: airwallex::AirwallexDisputeObject = details\n .data\n .object\n .parse_value(\"AirwallexDisputeObject\")\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n\n Ok(api_models::webhooks::ObjectReferenceId::PaymentId(\n api_models::payments::PaymentIdType::ConnectorTransactionId(\n dispute_details.payment_intent_id,\n ),\n ))\n } else {\n Err(report!(errors::ConnectorError::WebhookEventTypeNotFound))\n }\n }\n\n fn get_webhook_event_type(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n _context: Option<&WebhookContext>,\n ) -> CustomResult {\n let details: airwallex::AirwallexWebhookData = request\n .body\n .parse_struct(\"airwallexWebhookData\")\n .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;\n Ok(IncomingWebhookEvent::try_from(details.name)?)\n }\n\n fn get_webhook_resource_object(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n let details: airwallex::AirwallexWebhookObjectResource = request\n .body\n .parse_struct(\"AirwallexWebhookObjectResource\")\n .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;\n\n Ok(Box::new(details.data.object))\n }\n\n fn get_dispute_details(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n _context: Option<&WebhookContext>,\n ) -> CustomResult {\n let details: airwallex::AirwallexWebhookData = request\n .body\n .parse_struct(\"airwallexWebhookData\")\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n let dispute_details: airwallex::AirwallexDisputeObject = details\n .data\n .object\n .parse_value(\"AirwallexDisputeObject\")\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n let amount = convert_amount(\n self.amount_converter_to_string_minor,\n dispute_details.dispute_amount,\n dispute_details.dispute_currency,\n )?;\n Ok(DisputePayload {\n amount,\n currency: dispute_details.dispute_currency,\n dispute_stage: api_models::enums::DisputeStage::from(dispute_details.stage.clone()),\n connector_dispute_id: dispute_details.dispute_id,\n connector_reason: dispute_details.dispute_reason_type,\n connector_reason_code: dispute_details.dispute_original_reason_code,\n challenge_required_by: None,\n connector_status: dispute_details.status.to_string(),\n created_at: dispute_details.created_at,\n updated_at: dispute_details.updated_at,\n })\n }\n}\n\nimpl ConnectorRedirectResponse for Airwallex {\n fn get_flow_type(\n &self,\n _query_params: &str,\n _json_payload: Option,\n action: PaymentAction,\n ) -> CustomResult {\n match action {\n PaymentAction::PSync\n | PaymentAction::CompleteAuthorize\n | PaymentAction::PaymentAuthenticateCompleteAuthorize => {\n Ok(CallConnectorAction::Trigger)\n }\n }\n }\n}\n\nstatic AIRWALLEX_SUPPORTED_PAYMENT_METHODS: LazyLock =\n LazyLock::new(|| {\n let supported_capture_methods = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::Manual,\n enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let supported_capture_methods_redirect = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let supported_card_network = vec![\n common_enums::CardNetwork::Visa,\n common_enums::CardNetwork::Mastercard,\n common_enums::CardNetwork::AmericanExpress,\n common_enums::CardNetwork::JCB,\n common_enums::CardNetwork::DinersClub,\n common_enums::CardNetwork::UnionPay,\n common_enums::CardNetwork::Discover,\n ];\n\n let mut airwallex_supported_payment_methods = SupportedPaymentMethods::new();\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Credit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::Supported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Debit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::Supported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n enums::PaymentMethodType::GooglePay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n enums::PaymentMethodType::Paypal,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods_redirect.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n enums::PaymentMethodType::Skrill,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods_redirect.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::PayLater,\n enums::PaymentMethodType::Klarna,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::PayLater,\n enums::PaymentMethodType::Atome,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods_redirect.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::BankRedirect,\n enums::PaymentMethodType::Trustly,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods_redirect.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::BankRedirect,\n enums::PaymentMethodType::Blik,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods_redirect.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::BankRedirect,\n enums::PaymentMethodType::Ideal,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods_redirect.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods.add(\n enums::PaymentMethod::BankTransfer,\n enums::PaymentMethodType::IndonesianBankTransfer,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::NotSupported,\n supported_capture_methods: supported_capture_methods_redirect.clone(),\n specific_features: None,\n },\n );\n\n airwallex_supported_payment_methods\n });\n\nstatic AIRWALLEX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Airwallex\",\n description: \"Airwallex is a multinational financial technology company offering financial services and software as a service (SaaS)\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: enums::ConnectorIntegrationStatus::Sandbox,\n};\n\nstatic AIRWALLEX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [\n enums::EventClass::Payments,\n enums::EventClass::Refunds,\n enums::EventClass::Disputes,\n];\n\nimpl ConnectorSpecifications for Airwallex {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&AIRWALLEX_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*AIRWALLEX_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&AIRWALLEX_SUPPORTED_WEBHOOK_FLOWS)\n }\n\n #[cfg(feature = \"v1\")]\n fn should_call_connector_customer(\n &self,\n payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,\n ) -> bool {\n matches!(\n payment_attempt.setup_future_usage_applied,\n Some(enums::FutureUsage::OffSession)\n ) && payment_attempt.customer_acceptance.is_some()\n && matches!(\n payment_attempt.payment_method,\n Some(enums::PaymentMethod::Card)\n )\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__archipel__transformers.rs", "text": "use bytes::Bytes;\nuse common_enums::{\n self, AttemptStatus, AuthorizationStatus, CaptureMethod, Currency, FutureUsage,\n PaymentMethodStatus, RefundStatus,\n};\nuse common_utils::{date_time, ext_traits::Encode, pii, types::MinorUnit};\nuse error_stack::ResultExt;\nuse hyperswitch_domain_models::{\n address::AddressDetails,\n payment_method_data::{Card, PaymentMethodData, WalletData},\n router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},\n router_flow_types::refunds::{Execute, RSync},\n router_request_types::{\n AuthenticationData, PaymentsIncrementalAuthorizationData, ResponseId,\n SetupMandateRequestData,\n },\n router_response_types::{PaymentsResponseData, RefundsResponseData},\n types::{\n PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,\n PaymentsIncrementalAuthorizationRouterData, PaymentsSyncRouterData, RefundsRouterData,\n SetupMandateRouterData,\n },\n};\nuse hyperswitch_interfaces::{consts, errors};\nuse masking::Secret;\nuse serde::{Deserialize, Serialize};\n\nuse crate::{\n types::{\n PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,\n PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,\n ResponseRouterData,\n },\n unimplemented_payment_method,\n utils::{\n self, AddressData, AddressDetailsData, CardData, CardIssuer, PaymentsAuthorizeRequestData,\n RouterData as _,\n },\n};\n\nconst THREE_DS_MAX_SUPPORTED_VERSION: &str = \"2.2.0\";\n\n#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]\n#[serde(transparent)]\npub struct ArchipelTenantId(pub String);\n\nimpl From for ArchipelTenantId {\n fn from(value: String) -> Self {\n Self(value)\n }\n}\n\npub struct ArchipelRouterData {\n pub amount: MinorUnit,\n pub tenant_id: ArchipelTenantId,\n pub router_data: T,\n}\n\nimpl From<(MinorUnit, ArchipelTenantId, T)> for ArchipelRouterData {\n fn from((amount, tenant_id, router_data): (MinorUnit, ArchipelTenantId, T)) -> Self {\n Self {\n amount,\n tenant_id,\n router_data,\n }\n }\n}\n\npub struct ArchipelAuthType {\n pub(super) ca_certificate: Option>,\n}\n\nimpl TryFrom<&ConnectorAuthType> for ArchipelAuthType {\n type Error = error_stack::Report;\n fn try_from(auth_type: &ConnectorAuthType) -> Result {\n match auth_type {\n ConnectorAuthType::HeaderKey { api_key } => Ok(Self {\n ca_certificate: Some(api_key.to_owned()),\n }),\n _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),\n }\n }\n}\n\n#[derive(Debug, Deserialize, Serialize, Eq, PartialEq)]\npub struct ArchipelConfigData {\n pub tenant_id: ArchipelTenantId,\n pub platform_url: String,\n}\n\nimpl TryFrom<&Option> for ArchipelConfigData {\n type Error = error_stack::Report;\n fn try_from(connector_metadata: &Option) -> Result {\n let config_data = utils::to_connector_meta_from_secret::(connector_metadata.clone())\n .change_context(errors::ConnectorError::InvalidConnectorConfig {\n config: \"metadata. Required fields: tenant_id, platform_url\",\n })?;\n Ok(config_data)\n }\n}\n\n#[derive(Debug, Default, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum ArchipelPaymentInitiator {\n #[default]\n Customer,\n Merchant,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum ArchipelWalletProvider {\n ApplePay,\n GooglePay,\n SamsungPay,\n}\n\n#[derive(Debug, Default, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum ArchipelPaymentCertainty {\n #[default]\n Final,\n Estimated,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelOrderRequest {\n amount: MinorUnit,\n currency: String,\n certainty: ArchipelPaymentCertainty,\n initiator: ArchipelPaymentInitiator,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\npub struct CardExpiryDate {\n month: Secret,\n year: Secret,\n}\n\n#[derive(Debug, Serialize, Default, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum ApplicationSelectionIndicator {\n #[default]\n ByDefault,\n CustomerChoice,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct Archipel3DS {\n #[serde(rename = \"acsTransID\")]\n acs_trans_id: Option>,\n #[serde(rename = \"dsTransID\")]\n ds_trans_id: Option>,\n #[serde(rename = \"3DSRequestorName\")]\n three_ds_requestor_name: Option>,\n #[serde(rename = \"3DSAuthDate\")]\n three_ds_auth_date: Option,\n #[serde(rename = \"3DSAuthAmt\")]\n three_ds_auth_amt: Option,\n #[serde(rename = \"3DSAuthStatus\")]\n three_ds_auth_status: Option,\n #[serde(rename = \"3DSMaxSupportedVersion\")]\n three_ds_max_supported_version: String,\n #[serde(rename = \"3DSVersion\")]\n three_ds_version: Option,\n authentication_value: Secret,\n authentication_method: Option>,\n eci: Option,\n}\n\nimpl From for Archipel3DS {\n fn from(three_ds_data: AuthenticationData) -> Self {\n let now = date_time::date_as_yyyymmddthhmmssmmmz().ok();\n Self {\n acs_trans_id: None,\n ds_trans_id: three_ds_data.ds_trans_id.map(Secret::new),\n three_ds_requestor_name: None,\n three_ds_auth_date: now,\n three_ds_auth_amt: None,\n three_ds_auth_status: None,\n three_ds_max_supported_version: THREE_DS_MAX_SUPPORTED_VERSION.into(),\n three_ds_version: three_ds_data.message_version,\n authentication_value: three_ds_data.cavv,\n authentication_method: None,\n eci: three_ds_data.eci,\n }\n }\n}\n\n#[derive(Clone, Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelCardHolder {\n billing_address: Option,\n}\n\nimpl From> for ArchipelCardHolder {\n fn from(value: Option) -> Self {\n Self {\n billing_address: value,\n }\n }\n}\n\n#[derive(Clone, Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelBillingAddress {\n address: Option>,\n postal_code: Option>,\n}\n\npub trait ToArchipelBillingAddress {\n fn to_archipel_billing_address(&self) -> Option;\n}\n\nimpl ToArchipelBillingAddress for AddressDetails {\n fn to_archipel_billing_address(&self) -> Option {\n let address = self.get_combined_address_line().ok();\n let postal_code = self.get_optional_zip();\n\n match (address, postal_code) {\n (None, None) => None,\n (addr, zip) => Some(ArchipelBillingAddress {\n address: addr,\n postal_code: zip,\n }),\n }\n }\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum ArchipelCredentialIndicatorStatus {\n Initial,\n Subsequent,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelCredentialIndicator {\n status: ArchipelCredentialIndicatorStatus,\n recurring: Option,\n transaction_id: Option,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct TokenizedCardData {\n card_data: ArchipelTokenizedCard,\n wallet_information: ArchipelWalletInformation,\n}\n\nimpl TryFrom<(&WalletData, &Option)> for TokenizedCardData {\n type Error = error_stack::Report;\n fn try_from(\n (wallet_data, pm_token): (&WalletData, &Option),\n ) -> Result {\n let WalletData::ApplePay(apple_pay_data) = wallet_data else {\n return Err(error_stack::Report::from(\n errors::ConnectorError::NotSupported {\n message: \"Wallet type used\".to_string(),\n connector: \"Archipel\",\n },\n ));\n };\n\n let Some(PaymentMethodToken::ApplePayDecrypt(apple_pay_decrypt_data)) = pm_token else {\n return Err(error_stack::Report::from(unimplemented_payment_method!(\n \"Apple Pay\",\n \"Manual\",\n \"Archipel\"\n )));\n };\n\n let card_number = apple_pay_decrypt_data\n .application_primary_account_number\n .clone();\n\n let expiry_year_2_digit = apple_pay_decrypt_data\n .get_two_digit_expiry_year()\n .change_context(errors::ConnectorError::MissingRequiredField {\n field_name: \"Apple pay expiry year\",\n })?;\n let expiry_month = apple_pay_decrypt_data.get_expiry_month().change_context(\n errors::ConnectorError::InvalidDataFormat {\n field_name: \"expiration_month\",\n },\n )?;\n\n Ok(Self {\n card_data: ArchipelTokenizedCard {\n expiry: CardExpiryDate {\n year: expiry_year_2_digit,\n month: expiry_month,\n },\n number: card_number,\n scheme: ArchipelCardScheme::from(apple_pay_data.payment_method.network.as_str()),\n },\n wallet_information: {\n ArchipelWalletInformation {\n wallet_provider: ArchipelWalletProvider::ApplePay,\n wallet_indicator: apple_pay_decrypt_data.payment_data.eci_indicator.clone(),\n wallet_cryptogram: apple_pay_decrypt_data\n .payment_data\n .online_payment_cryptogram\n .clone(),\n }\n },\n })\n }\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelTokenizedCard {\n number: cards::CardNumber,\n expiry: CardExpiryDate,\n scheme: ArchipelCardScheme,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelCard {\n number: cards::CardNumber,\n expiry: CardExpiryDate,\n security_code: Option>,\n card_holder_name: Option>,\n application_selection_indicator: ApplicationSelectionIndicator,\n scheme: ArchipelCardScheme,\n}\n\nimpl TryFrom<(Option>, Option, &Card)> for ArchipelCard {\n type Error = error_stack::Report;\n fn try_from(\n (card_holder_name, card_holder_billing, ccard): (\n Option>,\n Option,\n &Card,\n ),\n ) -> Result {\n // NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.\n // So if `card_holder` is None, `card.card_holder_name` must also be None.\n // However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.\n let card_holder_name = card_holder_billing\n .as_ref()\n .and_then(|_| ccard.card_holder_name.clone().or(card_holder_name.clone()));\n\n let scheme: ArchipelCardScheme = ccard.get_card_issuer().ok().into();\n Ok(Self {\n number: ccard.card_number.clone(),\n expiry: CardExpiryDate {\n month: ccard.card_exp_month.clone(),\n year: ccard.get_card_expiry_year_2_digit()?,\n },\n security_code: Some(ccard.card_cvc.clone()),\n application_selection_indicator: ApplicationSelectionIndicator::ByDefault,\n card_holder_name,\n scheme,\n })\n }\n}\n\nimpl\n TryFrom<(\n Option>,\n Option,\n &hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,\n )> for ArchipelCard\n{\n type Error = error_stack::Report;\n fn try_from(\n (card_holder_name, card_holder_billing, card_details): (\n Option>,\n Option,\n &hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,\n ),\n ) -> Result {\n // NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.\n // So if `card_holder` is None, `card.card_holder_name` must also be None.\n // However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.\n let card_holder_name = card_holder_billing.as_ref().and_then(|_| {\n card_details\n .card_holder_name\n .clone()\n .or(card_holder_name.clone())\n });\n\n let scheme: ArchipelCardScheme = card_details.get_card_issuer().ok().into();\n Ok(Self {\n number: card_details.card_number.clone(),\n expiry: CardExpiryDate {\n month: card_details.card_exp_month.clone(),\n year: card_details.get_card_expiry_year_2_digit()?,\n },\n security_code: None,\n application_selection_indicator: ApplicationSelectionIndicator::ByDefault,\n card_holder_name,\n scheme,\n })\n }\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelWalletInformation {\n wallet_indicator: Option,\n wallet_provider: ArchipelWalletProvider,\n wallet_cryptogram: Secret,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelPaymentInformation {\n order: ArchipelOrderRequest,\n cardholder: Option,\n card_holder_name: Option>,\n credential_indicator: Option,\n stored_on_file: bool,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelWalletAuthorizationRequest {\n order: ArchipelOrderRequest,\n card: ArchipelTokenizedCard,\n cardholder: Option,\n wallet: ArchipelWalletInformation,\n #[serde(rename = \"3DS\")]\n three_ds: Option,\n credential_indicator: Option,\n stored_on_file: bool,\n tenant_id: ArchipelTenantId,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelCardAuthorizationRequest {\n order: ArchipelOrderRequest,\n card: ArchipelCard,\n cardholder: Option,\n #[serde(rename = \"3DS\")]\n three_ds: Option,\n credential_indicator: Option,\n stored_on_file: bool,\n tenant_id: ArchipelTenantId,\n}\n\n// PaymentsResponse\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum ArchipelCardScheme {\n Amex,\n Mastercard,\n Visa,\n Discover,\n Diners,\n Unknown,\n}\n\nimpl From<&str> for ArchipelCardScheme {\n fn from(input: &str) -> Self {\n match input {\n \"Visa\" => Self::Visa,\n \"Amex\" => Self::Amex,\n \"Diners\" => Self::Diners,\n \"MasterCard\" => Self::Mastercard,\n \"Discover\" => Self::Discover,\n _ => Self::Unknown,\n }\n }\n}\n\nimpl From> for ArchipelCardScheme {\n fn from(card_issuer: Option) -> Self {\n match card_issuer {\n Some(CardIssuer::Visa) => Self::Visa,\n Some(CardIssuer::Master | CardIssuer::Maestro) => Self::Mastercard,\n Some(CardIssuer::AmericanExpress) => Self::Amex,\n Some(CardIssuer::Discover) => Self::Discover,\n Some(CardIssuer::DinersClub) => Self::Diners,\n _ => Self::Unknown,\n }\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]\n#[serde(rename_all = \"lowercase\")]\npub enum ArchipelPaymentStatus {\n #[default]\n Succeeded,\n Failed,\n}\n\nimpl TryFrom<(AttemptStatus, CaptureMethod)> for ArchipelPaymentFlow {\n type Error = errors::ConnectorError;\n\n fn try_from(\n (status, capture_method): (AttemptStatus, CaptureMethod),\n ) -> Result {\n let is_auto_capture = matches!(capture_method, CaptureMethod::Automatic);\n\n match status {\n AttemptStatus::AuthenticationFailed => Ok(Self::Verify),\n AttemptStatus::Authorizing\n | AttemptStatus::Authorized\n | AttemptStatus::AuthorizationFailed => Ok(Self::Authorize),\n AttemptStatus::Voided | AttemptStatus::VoidInitiated | AttemptStatus::VoidFailed => {\n Ok(Self::Cancel)\n }\n AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed => {\n if is_auto_capture {\n Ok(Self::Pay)\n } else {\n Ok(Self::Capture)\n }\n }\n AttemptStatus::PaymentMethodAwaited | AttemptStatus::ConfirmationAwaited => {\n if is_auto_capture {\n Ok(Self::Pay)\n } else {\n Ok(Self::Authorize)\n }\n }\n _ => Err(errors::ConnectorError::ProcessingStepFailed(Some(\n Bytes::from_static(\n \"Impossible to determine Archipel flow from AttemptStatus\".as_bytes(),\n ),\n ))),\n }\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\npub enum ArchipelPaymentFlow {\n Verify,\n Authorize,\n Pay,\n Capture,\n Cancel,\n}\n\nstruct ArchipelFlowStatus {\n status: ArchipelPaymentStatus,\n flow: ArchipelPaymentFlow,\n}\nimpl ArchipelFlowStatus {\n fn new(status: ArchipelPaymentStatus, flow: ArchipelPaymentFlow) -> Self {\n Self { status, flow }\n }\n}\n\nimpl From for AttemptStatus {\n fn from(ArchipelFlowStatus { status, flow }: ArchipelFlowStatus) -> Self {\n match status {\n ArchipelPaymentStatus::Succeeded => match flow {\n ArchipelPaymentFlow::Authorize => Self::Authorized,\n ArchipelPaymentFlow::Pay\n | ArchipelPaymentFlow::Verify\n | ArchipelPaymentFlow::Capture => Self::Charged,\n ArchipelPaymentFlow::Cancel => Self::Voided,\n },\n ArchipelPaymentStatus::Failed => match flow {\n ArchipelPaymentFlow::Authorize | ArchipelPaymentFlow::Pay => {\n Self::AuthorizationFailed\n }\n ArchipelPaymentFlow::Verify => Self::AuthenticationFailed,\n ArchipelPaymentFlow::Capture => Self::CaptureFailed,\n ArchipelPaymentFlow::Cancel => Self::VoidFailed,\n },\n }\n }\n}\n\n#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelOrderResponse {\n id: String,\n amount: Option,\n currency: Option,\n captured_amount: Option,\n authorized_amount: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\npub struct ArchipelErrorMessage {\n pub code: String,\n pub description: Option,\n}\n\nimpl Default for ArchipelErrorMessage {\n fn default() -> Self {\n Self {\n code: consts::NO_ERROR_CODE.to_string(),\n description: Some(consts::NO_ERROR_MESSAGE.to_string()),\n }\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\nstruct ArchipelErrorMessageWithHttpCode {\n error_message: ArchipelErrorMessage,\n http_code: u16,\n}\nimpl ArchipelErrorMessageWithHttpCode {\n fn new(error_message: ArchipelErrorMessage, http_code: u16) -> Self {\n Self {\n error_message,\n http_code,\n }\n }\n}\n\n#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelTransactionMetadata {\n pub transaction_id: String,\n pub transaction_date: String,\n pub financial_network_code: Option,\n pub issuer_transaction_id: Option,\n pub response_code: Option,\n pub authorization_code: Option,\n pub payment_account_reference: Option>,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelPaymentsResponse {\n order: ArchipelOrderResponse,\n transaction_id: String,\n transaction_date: String,\n transaction_result: ArchipelPaymentStatus,\n error: Option,\n financial_network_code: Option,\n issuer_transaction_id: Option,\n response_code: Option,\n authorization_code: Option,\n payment_account_reference: Option>,\n}\n\nimpl From<&ArchipelPaymentsResponse> for ArchipelTransactionMetadata {\n fn from(payment_response: &ArchipelPaymentsResponse) -> Self {\n Self {\n transaction_id: payment_response.transaction_id.clone(),\n transaction_date: payment_response.transaction_date.clone(),\n financial_network_code: payment_response.financial_network_code.clone(),\n issuer_transaction_id: payment_response.issuer_transaction_id.clone(),\n response_code: payment_response.response_code.clone(),\n authorization_code: payment_response.authorization_code.clone(),\n payment_account_reference: payment_response.payment_account_reference.clone(),\n }\n }\n}\n\n// AUTHORIZATION FLOW\nimpl TryFrom<(MinorUnit, &PaymentsAuthorizeRouterData)> for ArchipelPaymentInformation {\n type Error = error_stack::Report;\n\n fn try_from(\n (amount, router_data): (MinorUnit, &PaymentsAuthorizeRouterData),\n ) -> Result {\n let is_recurring_payment = router_data\n .request\n .mandate_id\n .as_ref()\n .and_then(|mandate_ids| mandate_ids.mandate_id.as_ref())\n .is_some();\n\n let is_subsequent_trx = router_data\n .request\n .mandate_id\n .as_ref()\n .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())\n .is_some();\n\n let is_saved_card_payment = (router_data.request.is_mandate_payment())\n | (router_data.request.setup_future_usage == Some(FutureUsage::OnSession))\n | (router_data.payment_method_status == Some(PaymentMethodStatus::Active));\n\n let certainty = if router_data.request.request_incremental_authorization {\n if is_recurring_payment {\n ArchipelPaymentCertainty::Final\n } else {\n ArchipelPaymentCertainty::Estimated\n }\n } else {\n ArchipelPaymentCertainty::Final\n };\n\n let transaction_initiator = if is_recurring_payment {\n ArchipelPaymentInitiator::Merchant\n } else {\n ArchipelPaymentInitiator::Customer\n };\n\n let order = ArchipelOrderRequest {\n amount,\n currency: router_data.request.currency.to_string(),\n certainty,\n initiator: transaction_initiator.clone(),\n };\n\n let cardholder = router_data\n .get_billing_address()\n .ok()\n .and_then(|address| address.to_archipel_billing_address())\n .map(|billing_address| ArchipelCardHolder {\n billing_address: Some(billing_address),\n });\n\n // NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.\n // So if `card_holder` is None, `card.card_holder_name` must also be None.\n // However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.\n let card_holder_name = cardholder.as_ref().and_then(|_| {\n router_data\n .get_billing()\n .ok()\n .and_then(|billing| billing.get_optional_full_name())\n });\n\n let indicator_status = if is_subsequent_trx {\n ArchipelCredentialIndicatorStatus::Subsequent\n } else {\n ArchipelCredentialIndicatorStatus::Initial\n };\n\n let stored_on_file =\n is_saved_card_payment | router_data.request.is_customer_initiated_mandate_payment();\n\n let credential_indicator = stored_on_file.then(|| ArchipelCredentialIndicator {\n status: indicator_status.clone(),\n recurring: Some(is_recurring_payment),\n transaction_id: match indicator_status {\n ArchipelCredentialIndicatorStatus::Initial => None,\n ArchipelCredentialIndicatorStatus::Subsequent => {\n router_data.request.get_optional_network_transaction_id()\n }\n },\n });\n\n Ok(Self {\n order,\n cardholder,\n card_holder_name,\n credential_indicator,\n stored_on_file,\n })\n }\n}\n\nimpl TryFrom>\n for ArchipelCardAuthorizationRequest\n{\n type Error = error_stack::Report;\n\n fn try_from(\n item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,\n ) -> Result {\n let ArchipelRouterData {\n amount,\n tenant_id,\n router_data,\n } = item;\n\n let payment_information: ArchipelPaymentInformation =\n ArchipelPaymentInformation::try_from((amount, router_data))?;\n let payment_method_data = match &item.router_data.request.payment_method_data {\n PaymentMethodData::Card(ccard) => ArchipelCard::try_from((\n payment_information.card_holder_name,\n payment_information.cardholder.clone(),\n ccard,\n ))?,\n PaymentMethodData::CardDetailsForNetworkTransactionId(card_details) => {\n ArchipelCard::try_from((\n payment_information.card_holder_name,\n payment_information.cardholder.clone(),\n card_details,\n ))?\n }\n PaymentMethodData::CardRedirect(..)\n | PaymentMethodData::Wallet(..)\n | PaymentMethodData::PayLater(..)\n | PaymentMethodData::BankRedirect(..)\n | PaymentMethodData::BankDebit(..)\n | PaymentMethodData::BankTransfer(..)\n | PaymentMethodData::Crypto(..)\n | PaymentMethodData::MandatePayment\n | PaymentMethodData::Reward\n | PaymentMethodData::RealTimePayment(..)\n | PaymentMethodData::Upi(..)\n | PaymentMethodData::Voucher(..)\n | PaymentMethodData::GiftCard(..)\n | PaymentMethodData::CardToken(..)\n | PaymentMethodData::OpenBanking(..)\n | PaymentMethodData::NetworkToken(..)\n | PaymentMethodData::MobilePayment(..)\n | PaymentMethodData::CardWithLimitedDetails(..)\n | PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(..)\n | PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(..) => {\n Err(errors::ConnectorError::NotImplemented(\n utils::get_unimplemented_payment_method_error_message(\"Archipel\"),\n ))?\n }\n };\n\n let three_ds: Option = if item.router_data.is_three_ds() {\n let auth_data = item\n .router_data\n .request\n .get_authentication_data()\n .change_context(errors::ConnectorError::NotSupported {\n message: \"Selected 3DS authentication method\".to_string(),\n connector: \"archipel\",\n })?;\n Some(Archipel3DS::from(auth_data))\n } else {\n None\n };\n\n Ok(Self {\n order: payment_information.order,\n cardholder: payment_information.cardholder,\n card: payment_method_data,\n three_ds,\n credential_indicator: payment_information.credential_indicator,\n stored_on_file: payment_information.stored_on_file,\n tenant_id,\n })\n }\n}\n\nimpl TryFrom>\n for ArchipelWalletAuthorizationRequest\n{\n type Error = error_stack::Report;\n\n fn try_from(\n item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,\n ) -> Result {\n let ArchipelRouterData {\n amount,\n tenant_id,\n router_data,\n } = item;\n\n let payment_information = ArchipelPaymentInformation::try_from((amount, router_data))?;\n let payment_method_data = match &item.router_data.request.payment_method_data {\n PaymentMethodData::Wallet(wallet_data) => {\n TokenizedCardData::try_from((wallet_data, &item.router_data.payment_method_token))?\n }\n PaymentMethodData::Card(..)\n | PaymentMethodData::CardDetailsForNetworkTransactionId(..)\n | PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_)\n | PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)\n | PaymentMethodData::CardWithLimitedDetails(..)\n | PaymentMethodData::CardRedirect(..)\n | PaymentMethodData::PayLater(..)\n | PaymentMethodData::BankRedirect(..)\n | PaymentMethodData::BankDebit(..)\n | PaymentMethodData::BankTransfer(..)\n | PaymentMethodData::Crypto(..)\n | PaymentMethodData::MandatePayment\n | PaymentMethodData::Reward\n | PaymentMethodData::RealTimePayment(..)\n | PaymentMethodData::Upi(..)\n | PaymentMethodData::Voucher(..)\n | PaymentMethodData::GiftCard(..)\n | PaymentMethodData::CardToken(..)\n | PaymentMethodData::OpenBanking(..)\n | PaymentMethodData::NetworkToken(..)\n | PaymentMethodData::MobilePayment(..) => Err(errors::ConnectorError::NotImplemented(\n utils::get_unimplemented_payment_method_error_message(\"Archipel\"),\n ))?,\n };\n\n Ok(Self {\n order: payment_information.order,\n cardholder: payment_information.cardholder,\n card: payment_method_data.card_data.clone(),\n wallet: payment_method_data.wallet_information.clone(),\n three_ds: None,\n credential_indicator: payment_information.credential_indicator,\n stored_on_file: payment_information.stored_on_file,\n tenant_id,\n })\n }\n}\n\n// Responses for AUTHORIZATION FLOW\nimpl TryFrom> for PaymentsAuthorizeRouterData {\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsResponseRouterData,\n ) -> Result {\n if let Some(error) = item.response.error {\n return Ok(Self {\n response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),\n ..item.data\n });\n };\n\n let capture_method = item\n .data\n .request\n .capture_method\n .ok_or_else(|| errors::ConnectorError::CaptureMethodNotSupported)?;\n\n let (archipel_flow, is_incremental_allowed) = match capture_method {\n CaptureMethod::Automatic => (ArchipelPaymentFlow::Pay, false),\n _ => (\n ArchipelPaymentFlow::Authorize,\n item.data.request.request_incremental_authorization,\n ),\n };\n\n let connector_metadata: Option =\n ArchipelTransactionMetadata::from(&item.response)\n .encode_to_value()\n .ok();\n\n let status: AttemptStatus =\n ArchipelFlowStatus::new(item.response.transaction_result, archipel_flow).into();\n\n Ok(Self {\n status,\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),\n authentication_data: None,\n charges: None,\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata,\n // Save archipel initial transaction uuid for network transaction mit/cit\n network_txn_id: item\n .data\n .request\n .is_customer_initiated_mandate_payment()\n .then_some(item.response.transaction_id),\n connector_response_reference_id: None,\n incremental_authorization_allowed: Some(is_incremental_allowed),\n }),\n ..item.data\n })\n }\n}\n\n// PSYNC FLOW\nimpl TryFrom> for PaymentsSyncRouterData {\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsSyncResponseRouterData,\n ) -> Result {\n if let Some(error) = item.response.error {\n return Ok(Self {\n response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),\n ..item.data\n });\n };\n\n let connector_metadata: Option =\n ArchipelTransactionMetadata::from(&item.response)\n .encode_to_value()\n .ok();\n\n let capture_method = item\n .data\n .request\n .capture_method\n .ok_or_else(|| errors::ConnectorError::CaptureMethodNotSupported)?;\n\n let archipel_flow: ArchipelPaymentFlow = (item.data.status, capture_method).try_into()?;\n\n let status: AttemptStatus =\n ArchipelFlowStatus::new(item.response.transaction_result, archipel_flow).into();\n\n Ok(Self {\n status,\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),\n authentication_data: None,\n charges: None,\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n }),\n ..item.data\n })\n }\n}\n\n/* CAPTURE FLOW */\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\npub struct ArchipelCaptureRequest {\n order: ArchipelCaptureOrderRequest,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\npub struct ArchipelCaptureOrderRequest {\n amount: MinorUnit,\n}\n\nimpl From> for ArchipelCaptureRequest {\n fn from(item: ArchipelRouterData<&PaymentsCaptureRouterData>) -> Self {\n Self {\n order: ArchipelCaptureOrderRequest {\n amount: item.amount,\n },\n }\n }\n}\n\nimpl TryFrom>\n for PaymentsCaptureRouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsCaptureResponseRouterData,\n ) -> Result {\n if let Some(error) = item.response.error {\n return Ok(Self {\n response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),\n ..item.data\n });\n };\n\n let connector_metadata: Option =\n ArchipelTransactionMetadata::from(&item.response)\n .encode_to_value()\n .ok();\n\n let status: AttemptStatus = ArchipelFlowStatus::new(\n item.response.transaction_result,\n ArchipelPaymentFlow::Capture,\n )\n .into();\n\n Ok(Self {\n status,\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),\n authentication_data: None,\n charges: None,\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n }),\n ..item.data\n })\n }\n}\n\n// Setup Mandate FLow\nimpl TryFrom> for ArchipelCardAuthorizationRequest {\n type Error = error_stack::Report;\n fn try_from(item: ArchipelRouterData<&SetupMandateRouterData>) -> Result {\n let order = ArchipelOrderRequest {\n amount: item.amount,\n currency: item.router_data.request.currency.to_string(),\n certainty: ArchipelPaymentCertainty::Final,\n initiator: ArchipelPaymentInitiator::Customer,\n };\n\n let cardholder = Some(ArchipelCardHolder {\n billing_address: item\n .router_data\n .get_billing_address()\n .ok()\n .and_then(|address| address.to_archipel_billing_address()),\n });\n\n // NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.\n // So if `card_holder` is None, `card.card_holder_name` must also be None.\n // However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.\n let card_holder_name = cardholder.as_ref().and_then(|_| {\n item.router_data\n .get_billing()\n .ok()\n .and_then(|billing| billing.get_optional_full_name())\n });\n\n let stored_on_file = true;\n\n let credential_indicator = Some(ArchipelCredentialIndicator {\n status: ArchipelCredentialIndicatorStatus::Initial,\n recurring: Some(false),\n transaction_id: None,\n });\n\n let payment_information = ArchipelPaymentInformation {\n order,\n cardholder,\n card_holder_name,\n stored_on_file,\n credential_indicator,\n };\n\n let card_data = match &item.router_data.request.payment_method_data {\n PaymentMethodData::Card(ccard) => ArchipelCard::try_from((\n payment_information.card_holder_name,\n payment_information.cardholder.clone(),\n ccard,\n ))?,\n _ => Err(errors::ConnectorError::NotImplemented(\n utils::get_unimplemented_payment_method_error_message(\"Archipel\"),\n ))?,\n };\n\n Ok(Self {\n order: payment_information.order,\n cardholder: payment_information.cardholder.clone(),\n card: card_data,\n three_ds: None,\n credential_indicator: payment_information.credential_indicator,\n stored_on_file: payment_information.stored_on_file,\n tenant_id: item.tenant_id,\n })\n }\n}\n\nimpl\n TryFrom<\n ResponseRouterData<\n F,\n ArchipelPaymentsResponse,\n SetupMandateRequestData,\n PaymentsResponseData,\n >,\n > for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData<\n F,\n ArchipelPaymentsResponse,\n SetupMandateRequestData,\n PaymentsResponseData,\n >,\n ) -> Result {\n if let Some(error) = item.response.error {\n return Ok(Self {\n response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),\n ..item.data\n });\n };\n\n let connector_metadata: Option =\n ArchipelTransactionMetadata::from(&item.response)\n .encode_to_value()\n .ok();\n\n let status: AttemptStatus = ArchipelFlowStatus::new(\n item.response.transaction_result,\n ArchipelPaymentFlow::Verify,\n )\n .into();\n\n Ok(Self {\n status,\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),\n authentication_data: None,\n charges: None,\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata,\n network_txn_id: Some(item.response.transaction_id.clone()),\n connector_response_reference_id: Some(item.response.transaction_id),\n incremental_authorization_allowed: Some(false),\n }),\n ..item.data\n })\n }\n}\n\n// Void Flow => /cancel/{order_id}\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelPaymentsCancelRequest {\n tenant_id: ArchipelTenantId,\n}\n\nimpl From> for ArchipelPaymentsCancelRequest {\n fn from(item: ArchipelRouterData<&PaymentsCancelRouterData>) -> Self {\n Self {\n tenant_id: item.tenant_id,\n }\n }\n}\n\nimpl TryFrom>\n for PaymentsCancelRouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsCancelResponseRouterData,\n ) -> Result {\n if let Some(error) = item.response.error {\n return Ok(Self {\n response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),\n ..item.data\n });\n };\n\n let connector_metadata: Option =\n ArchipelTransactionMetadata::from(&item.response)\n .encode_to_value()\n .ok();\n\n let status: AttemptStatus = ArchipelFlowStatus::new(\n item.response.transaction_result,\n ArchipelPaymentFlow::Cancel,\n )\n .into();\n\n Ok(Self {\n status,\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),\n authentication_data: None,\n charges: None,\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n }),\n ..item.data\n })\n }\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelIncrementalAuthorizationRequest {\n order: ArchipelOrderRequest,\n tenant_id: ArchipelTenantId,\n}\n\n// Incremental Authorization status mapping\nimpl From for AuthorizationStatus {\n fn from(status: ArchipelPaymentStatus) -> Self {\n match status {\n ArchipelPaymentStatus::Succeeded => Self::Success,\n ArchipelPaymentStatus::Failed => Self::Failure,\n }\n }\n}\n\nimpl From>\n for ArchipelIncrementalAuthorizationRequest\n{\n fn from(item: ArchipelRouterData<&PaymentsIncrementalAuthorizationRouterData>) -> Self {\n Self {\n order: ArchipelOrderRequest {\n amount: item.amount,\n currency: item.router_data.request.currency.to_string(),\n certainty: ArchipelPaymentCertainty::Estimated,\n initiator: ArchipelPaymentInitiator::Customer,\n },\n tenant_id: item.tenant_id,\n }\n }\n}\n\nimpl\n TryFrom<\n ResponseRouterData<\n F,\n ArchipelPaymentsResponse,\n PaymentsIncrementalAuthorizationData,\n PaymentsResponseData,\n >,\n > for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData<\n F,\n ArchipelPaymentsResponse,\n PaymentsIncrementalAuthorizationData,\n PaymentsResponseData,\n >,\n ) -> Result {\n let status = AuthorizationStatus::from(item.response.transaction_result);\n\n let (error_code, error_message) = match (&status, item.response.error) {\n (AuthorizationStatus::Success, _) | (_, None) => (None, None),\n (_, Some(err)) => (Some(err.code), err.description),\n };\n\n Ok(Self {\n response: Ok(PaymentsResponseData::IncrementalAuthorizationResponse {\n status,\n error_code,\n error_message,\n connector_authorization_id: None,\n }),\n ..item.data\n })\n }\n}\n\n/* REFUND FLOW */\n#[derive(Debug, Serialize)]\npub struct ArchipelRefundOrder {\n pub amount: MinorUnit,\n pub currency: Currency,\n}\n\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelRefundRequest {\n pub order: ArchipelRefundOrder,\n pub tenant_id: ArchipelTenantId,\n}\n\nimpl From>> for ArchipelRefundRequest {\n fn from(item: ArchipelRouterData<&RefundsRouterData>) -> Self {\n Self {\n order: ArchipelRefundOrder {\n amount: item.amount,\n currency: item.router_data.request.currency,\n },\n tenant_id: item.tenant_id,\n }\n }\n}\n\n// Type definition for Refund Response\n#[derive(Debug, Serialize, Default, Deserialize, Clone)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum ArchipelRefundStatus {\n Accepted,\n Failed,\n #[default]\n Pending,\n}\n\nimpl From for RefundStatus {\n fn from(item: ArchipelPaymentStatus) -> Self {\n match item {\n ArchipelPaymentStatus::Succeeded => Self::Success,\n ArchipelPaymentStatus::Failed => Self::Failure,\n }\n }\n}\n\n#[derive(Default, Debug, Clone, Serialize, Deserialize)]\npub struct ArchipelRefundOrderResponse {\n id: String,\n}\n\n#[derive(Default, Debug, Clone, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct ArchipelRefundResponse {\n order: ArchipelRefundOrderResponse,\n status: ArchipelRefundStatus,\n transaction_result: ArchipelPaymentStatus,\n transaction_id: Option,\n transaction_date: Option,\n error: Option,\n}\n\nimpl TryFrom for RefundsResponseData {\n type Error = error_stack::Report;\n fn try_from(resp: ArchipelRefundResponse) -> Result {\n Ok(Self {\n connector_refund_id: resp\n .transaction_id\n .ok_or_else(|| errors::ConnectorError::ParsingFailed)?,\n refund_status: RefundStatus::from(resp.transaction_result),\n })\n }\n}\n\nimpl TryFrom>\n for RefundsRouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: RefundsResponseRouterData,\n ) -> Result {\n let response = match item.response.error {\n None => Ok(RefundsResponseData::try_from(item.response)?),\n Some(error) => Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),\n };\n\n Ok(Self {\n response,\n ..item.data\n })\n }\n}\n\nimpl TryFrom>\n for RefundsRouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: RefundsResponseRouterData,\n ) -> Result {\n let response = match item.response.error {\n None => Ok(RefundsResponseData::try_from(item.response)?),\n Some(error) => Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),\n };\n\n Ok(Self {\n response,\n ..item.data\n })\n }\n}\n\nimpl From for ErrorResponse {\n fn from(\n ArchipelErrorMessageWithHttpCode {\n error_message,\n http_code,\n }: ArchipelErrorMessageWithHttpCode,\n ) -> Self {\n Self {\n status_code: http_code,\n code: error_message.code,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n message: error_message\n .description\n .clone()\n .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),\n reason: error_message.description,\n network_decline_code: None,\n network_advice_code: None,\n network_error_message: None,\n connector_metadata: None,\n }\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__authipay.rs", "text": "pub mod transformers;\n\nuse std::sync::LazyLock;\n\nuse base64::Engine;\nuse common_enums::enums;\nuse common_utils::{\n errors::CustomResult,\n ext_traits::BytesExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n },\n router_request_types::{\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,\n PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, Response},\n webhooks,\n};\nuse masking::{ExposeInterface, Mask, PeekInterface};\nuse transformers as authipay;\n\nuse crate::{constants::headers, types::ResponseRouterData, utils};\n\n#[derive(Clone)]\npub struct Authipay {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Authipay {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &FloatMajorUnitForConnector,\n }\n }\n\n pub fn generate_authorization_signature(\n &self,\n auth: authipay::AuthipayAuthType,\n request_id: &str,\n payload: &str,\n timestamp: i128,\n ) -> CustomResult {\n let authipay::AuthipayAuthType {\n api_key,\n api_secret,\n } = auth;\n let raw_signature = format!(\"{}{request_id}{timestamp}{payload}\", api_key.peek());\n\n let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, api_secret.expose().as_bytes());\n let signature_value = common_utils::consts::BASE64_ENGINE\n .encode(ring::hmac::sign(&key, raw_signature.as_bytes()).as_ref());\n Ok(signature_value)\n }\n}\n\nimpl api::Payment for Authipay {}\nimpl api::PaymentSession for Authipay {}\nimpl api::ConnectorAccessToken for Authipay {}\nimpl api::MandateSetup for Authipay {}\nimpl api::PaymentAuthorize for Authipay {}\nimpl api::PaymentSync for Authipay {}\nimpl api::PaymentCapture for Authipay {}\nimpl api::PaymentVoid for Authipay {}\nimpl api::Refund for Authipay {}\nimpl api::RefundExecute for Authipay {}\nimpl api::RefundSync for Authipay {}\nimpl api::PaymentToken for Authipay {}\n\nimpl ConnectorIntegration\n for Authipay\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorCommonExt for Authipay\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let timestamp = time::OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;\n let auth: authipay::AuthipayAuthType =\n authipay::AuthipayAuthType::try_from(&req.connector_auth_type)?;\n let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;\n\n let authipay_req = self.get_request_body(req, connectors)?;\n\n let client_request_id = uuid::Uuid::new_v4().to_string();\n let hmac = self\n .generate_authorization_signature(\n auth,\n &client_request_id,\n authipay_req.get_inner_value().peek(),\n timestamp,\n )\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n let mut headers = vec![\n (\n headers::CONTENT_TYPE.to_string(),\n types::PaymentsAuthorizeType::get_content_type(self)\n .to_string()\n .into(),\n ),\n (\"Client-Request-Id\".to_string(), client_request_id.into()),\n (\"Auth-Token-Type\".to_string(), \"HMAC\".to_string().into()),\n (headers::TIMESTAMP.to_string(), timestamp.to_string().into()),\n (\"Message-Signature\".to_string(), hmac.into_masked()),\n ];\n headers.append(&mut auth_header);\n Ok(headers)\n }\n}\n\nimpl ConnectorCommon for Authipay {\n fn id(&self) -> &'static str {\n \"authipay\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.authipay.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, errors::ConnectorError> {\n let auth = authipay::AuthipayAuthType::try_from(auth_type)\n .change_context(errors::ConnectorError::FailedToObtainAuthType)?;\n Ok(vec![(\n headers::API_KEY.to_string(),\n auth.api_key.into_masked(),\n )])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: authipay::AuthipayErrorResponse = res\n .response\n .parse_struct(\"AuthipayErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_error_response_body(&response));\n\n let mut error_response = ErrorResponse::from(&response);\n\n // Set status code from the response, or 400 if error code is a \"404\"\n if let Some(error_code) = &response.error.code {\n if error_code == \"404\" {\n error_response.status_code = 404;\n } else {\n error_response.status_code = res.status_code;\n }\n } else {\n error_response.status_code = res.status_code;\n }\n\n Ok(error_response)\n }\n}\n\nimpl ConnectorValidation for Authipay {\n fn validate_connector_against_payment_request(\n &self,\n capture_method: Option,\n _payment_method: enums::PaymentMethod,\n _pmt: Option,\n ) -> CustomResult<(), errors::ConnectorError> {\n let capture_method = capture_method.unwrap_or_default();\n match capture_method {\n enums::CaptureMethod::Automatic\n | enums::CaptureMethod::Manual\n | enums::CaptureMethod::SequentialAutomatic => Ok(()),\n enums::CaptureMethod::Scheduled | enums::CaptureMethod::ManualMultiple => Err(\n utils::construct_not_implemented_error_report(capture_method, self.id()),\n ),\n }\n }\n}\n\nimpl ConnectorIntegration for Authipay {\n //TODO: implement sessions flow\n}\n\nimpl ConnectorIntegration for Authipay {}\n\nimpl ConnectorIntegration\n for Authipay\n{\n}\n\nimpl ConnectorIntegration for Authipay {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}payments\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = authipay::AuthipayRouterData::from((amount, req));\n let connector_req = authipay::AuthipayPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: authipay::AuthipayPaymentsResponse = res\n .response\n .parse_struct(\"Authipay PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Authipay {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_transaction_id = req\n .request\n .connector_transaction_id\n .get_connector_transaction_id()\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n Ok(format!(\n \"{}payments/{}\",\n self.base_url(connectors),\n connector_transaction_id\n ))\n }\n\n fn get_request_body(\n &self,\n _req: &PaymentsSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Ok(RequestContent::RawBytes(Vec::new()))\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: authipay::AuthipayPaymentsResponse = res\n .response\n .parse_struct(\"authipay PaymentsSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Authipay {\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_transaction_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}payments/{}\",\n self.base_url(connectors),\n connector_transaction_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount_to_capture,\n req.request.currency,\n )?;\n\n let connector_router_data = authipay::AuthipayRouterData::from((amount, req));\n let connector_req = authipay::AuthipayCaptureRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsCaptureType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: authipay::AuthipayPaymentsResponse = res\n .response\n .parse_struct(\"Authipay PaymentsCaptureResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Authipay {\n fn get_headers(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n // For void operations, Authipay requires using the /orders/{orderId} endpoint\n // The orderId should be stored in connector_meta from the authorization response\n let order_id = req\n .request\n .connector_meta\n .as_ref()\n .and_then(|meta| meta.get(\"order_id\"))\n .and_then(|v| v.as_str())\n .ok_or(errors::ConnectorError::RequestEncodingFailed)?;\n\n Ok(format!(\"{}orders/{}\", self.base_url(connectors), order_id))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCancelRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n // For void, we don't need amount conversion since it's always full amount\n let connector_router_data =\n authipay::AuthipayRouterData::from((FloatMajorUnit::zero(), req));\n let connector_req = authipay::AuthipayVoidRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)\n .set_body(types::PaymentsVoidType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCancelRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: authipay::AuthipayPaymentsResponse = res\n .response\n .parse_struct(\"Authipay PaymentsVoidResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Authipay {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}payments/{}\",\n self.base_url(connectors),\n connector_payment_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let refund_amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_refund_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = authipay::AuthipayRouterData::from((refund_amount, req));\n let connector_req = authipay::AuthipayRefundRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&types::RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundExecuteType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::RefundExecuteType::get_request_body(\n self, req, connectors,\n )?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: authipay::RefundResponse = res\n .response\n .parse_struct(\"authipay RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Authipay {\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let refund_id = req\n .request\n .connector_refund_id\n .clone()\n .ok_or(errors::ConnectorError::RequestEncodingFailed)?;\n Ok(format!(\n \"{}payments/{}\",\n self.base_url(connectors),\n refund_id\n ))\n }\n\n fn get_request_body(\n &self,\n _req: &RefundSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Ok(RequestContent::RawBytes(Vec::new()))\n }\n\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: authipay::RefundResponse = res\n .response\n .parse_struct(\"authipay RefundSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Authipay {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic AUTHIPAY_SUPPORTED_PAYMENT_METHODS: LazyLock =\n LazyLock::new(|| {\n let supported_capture_methods = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::SequentialAutomatic,\n enums::CaptureMethod::Manual,\n ];\n\n let supported_card_network = vec![\n common_enums::CardNetwork::Visa,\n common_enums::CardNetwork::Mastercard,\n ];\n\n let mut authipay_supported_payment_methods = SupportedPaymentMethods::new();\n\n authipay_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Credit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n authipay_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Debit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n authipay_supported_payment_methods\n });\n\nstatic AUTHIPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Authipay\",\n description: \"Authipay is a Fiserv-powered payment gateway for the EMEA region supporting Visa and Mastercard transactions. Features include flexible capture methods (automatic, manual, sequential), partial captures/refunds, payment tokenization, and secure HMAC SHA256 authentication.\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: enums::ConnectorIntegrationStatus::Sandbox,\n};\n\nstatic AUTHIPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];\n\nimpl ConnectorSpecifications for Authipay {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&AUTHIPAY_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*AUTHIPAY_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&AUTHIPAY_SUPPORTED_WEBHOOK_FLOWS)\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__elavon__transformers.rs", "text": "use cards::CardNumber;\nuse common_enums::{enums, Currency};\nuse common_utils::{pii::Email, types::StringMajorUnit};\nuse error_stack::ResultExt;\nuse hyperswitch_domain_models::{\n payment_method_data::PaymentMethodData,\n router_data::{ConnectorAuthType, ErrorResponse},\n router_flow_types::refunds::{Execute, RSync},\n router_request_types::ResponseId,\n router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},\n types::{\n PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,\n RefundSyncRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors};\nuse masking::{ExposeInterface, Secret};\nuse serde::{Deserialize, Deserializer, Serialize};\n\nuse crate::{\n types::{\n PaymentsCaptureResponseRouterData, PaymentsResponseRouterData,\n PaymentsSyncResponseRouterData, RefundsResponseRouterData,\n },\n utils::{CardData, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData as _},\n};\n\npub struct ElavonRouterData {\n pub amount: StringMajorUnit,\n pub router_data: T,\n}\n\nimpl From<(StringMajorUnit, T)> for ElavonRouterData {\n fn from((amount, item): (StringMajorUnit, T)) -> Self {\n Self {\n amount,\n router_data: item,\n }\n }\n}\n#[derive(Serialize, Deserialize, Debug)]\n#[serde(rename_all = \"lowercase\")]\npub enum TransactionType {\n CcSale,\n CcAuthOnly,\n CcComplete,\n CcReturn,\n TxnQuery,\n}\n#[derive(Serialize, Deserialize, Debug)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum SyncTransactionType {\n Sale,\n AuthOnly,\n Return,\n}\n\n#[derive(Debug, Serialize)]\n#[serde(untagged)]\npub enum ElavonPaymentsRequest {\n Card(CardPaymentRequest),\n MandatePayment(MandatePaymentRequest),\n}\n#[derive(Debug, Serialize)]\npub struct CardPaymentRequest {\n pub ssl_transaction_type: TransactionType,\n pub ssl_account_id: Secret,\n pub ssl_user_id: Secret,\n pub ssl_pin: Secret,\n pub ssl_amount: StringMajorUnit,\n pub ssl_card_number: CardNumber,\n pub ssl_exp_date: Secret,\n pub ssl_cvv2cvc2: Secret,\n pub ssl_email: Email,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub ssl_add_token: Option,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub ssl_get_token: Option,\n pub ssl_transaction_currency: Currency,\n}\n#[derive(Debug, Serialize)]\npub struct MandatePaymentRequest {\n pub ssl_transaction_type: TransactionType,\n pub ssl_account_id: Secret,\n pub ssl_user_id: Secret,\n pub ssl_pin: Secret,\n pub ssl_amount: StringMajorUnit,\n pub ssl_email: Email,\n pub ssl_token: Secret,\n}\n\nimpl TryFrom<&ElavonRouterData<&PaymentsAuthorizeRouterData>> for ElavonPaymentsRequest {\n type Error = error_stack::Report;\n fn try_from(\n item: &ElavonRouterData<&PaymentsAuthorizeRouterData>,\n ) -> Result {\n let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;\n\n match item.router_data.request.payment_method_data.clone() {\n PaymentMethodData::Card(req_card) => {\n if item.router_data.is_three_ds() {\n Err(errors::ConnectorError::NotSupported {\n message: \"Card 3DS\".to_string(),\n connector: \"Elavon\",\n })?\n };\n Ok(Self::Card(CardPaymentRequest {\n ssl_transaction_type: match item.router_data.request.is_auto_capture()? {\n true => TransactionType::CcSale,\n false => TransactionType::CcAuthOnly,\n },\n ssl_account_id: auth.account_id.clone(),\n ssl_user_id: auth.user_id.clone(),\n ssl_pin: auth.pin.clone(),\n ssl_amount: item.amount.clone(),\n ssl_card_number: req_card.card_number.clone(),\n ssl_exp_date: req_card.get_expiry_date_as_mmyy()?,\n ssl_cvv2cvc2: req_card.card_cvc,\n ssl_email: item.router_data.get_billing_email()?,\n ssl_add_token: match item.router_data.request.is_mandate_payment() {\n true => Some(\"Y\".to_string()),\n false => None,\n },\n ssl_get_token: match item.router_data.request.is_mandate_payment() {\n true => Some(\"Y\".to_string()),\n false => None,\n },\n ssl_transaction_currency: item.router_data.request.currency,\n }))\n }\n PaymentMethodData::MandatePayment => Ok(Self::MandatePayment(MandatePaymentRequest {\n ssl_transaction_type: match item.router_data.request.is_auto_capture()? {\n true => TransactionType::CcSale,\n false => TransactionType::CcAuthOnly,\n },\n ssl_account_id: auth.account_id.clone(),\n ssl_user_id: auth.user_id.clone(),\n ssl_pin: auth.pin.clone(),\n ssl_amount: item.amount.clone(),\n ssl_email: item.router_data.get_billing_email()?,\n ssl_token: Secret::new(item.router_data.request.get_connector_mandate_id()?),\n })),\n _ => Err(errors::ConnectorError::NotImplemented(\"Payment methods\".to_string()).into()),\n }\n }\n}\n\npub struct ElavonAuthType {\n pub(super) account_id: Secret,\n pub(super) user_id: Secret,\n pub(super) pin: Secret,\n}\n\nimpl TryFrom<&ConnectorAuthType> for ElavonAuthType {\n type Error = error_stack::Report;\n fn try_from(auth_type: &ConnectorAuthType) -> Result {\n match auth_type {\n ConnectorAuthType::SignatureKey {\n api_key,\n key1,\n api_secret,\n } => Ok(Self {\n account_id: api_key.to_owned(),\n user_id: key1.to_owned(),\n pin: api_secret.to_owned(),\n }),\n _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),\n }\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\nenum SslResult {\n #[serde(rename = \"0\")]\n ImportedBatchFile,\n #[serde(other)]\n DeclineOrUnauthorized,\n}\n\n#[derive(Debug, Clone, Serialize)]\npub struct ElavonPaymentsResponse {\n pub result: ElavonResult,\n}\n#[derive(Debug, Clone, Serialize)]\npub enum ElavonResult {\n Success(PaymentResponse),\n Error(ElavonErrorResponse),\n}\n#[derive(Debug, Clone, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct ElavonErrorResponse {\n error_code: Option,\n error_message: String,\n error_name: String,\n}\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct PaymentResponse {\n ssl_result: SslResult,\n ssl_txn_id: String,\n ssl_result_message: String,\n ssl_token: Option>,\n}\nimpl<'de> Deserialize<'de> for ElavonPaymentsResponse {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n #[derive(Deserialize, Debug)]\n #[serde(rename = \"txn\")]\n struct XmlResponse {\n // Error fields\n #[serde(rename = \"errorCode\", default)]\n error_code: Option,\n #[serde(rename = \"errorMessage\", default)]\n error_message: Option,\n #[serde(rename = \"errorName\", default)]\n error_name: Option,\n\n // Success fields\n #[serde(rename = \"ssl_result\", default)]\n ssl_result: Option,\n #[serde(rename = \"ssl_txn_id\", default)]\n ssl_txn_id: Option,\n #[serde(rename = \"ssl_result_message\", default)]\n ssl_result_message: Option,\n #[serde(rename = \"ssl_token\", default)]\n ssl_token: Option>,\n }\n\n let xml_res = XmlResponse::deserialize(deserializer)?;\n\n let result = match (xml_res.error_message.clone(), xml_res.error_name.clone()) {\n (Some(error_message), Some(error_name)) => ElavonResult::Error(ElavonErrorResponse {\n error_code: xml_res.error_code.clone(),\n error_message,\n error_name,\n }),\n _ => {\n if let (Some(ssl_result), Some(ssl_txn_id), Some(ssl_result_message)) = (\n xml_res.ssl_result.clone(),\n xml_res.ssl_txn_id.clone(),\n xml_res.ssl_result_message.clone(),\n ) {\n ElavonResult::Success(PaymentResponse {\n ssl_result,\n ssl_txn_id,\n ssl_result_message,\n ssl_token: xml_res.ssl_token.clone(),\n })\n } else {\n return Err(serde::de::Error::custom(\n \"Invalid Response XML structure - neither error nor success\",\n ));\n }\n }\n };\n\n Ok(Self { result })\n }\n}\nimpl TryFrom> for PaymentsAuthorizeRouterData {\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsResponseRouterData,\n ) -> Result {\n let status =\n get_payment_status(&item.response.result, item.data.request.is_auto_capture()?);\n let response = match &item.response.result {\n ElavonResult::Error(error) => Err(ErrorResponse {\n code: error\n .error_code\n .clone()\n .unwrap_or(NO_ERROR_CODE.to_string()),\n message: error.error_message.clone(),\n reason: Some(error.error_message.clone()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n status_code: item.http_code,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n }),\n ElavonResult::Success(response) => {\n if status == enums::AttemptStatus::Failure {\n Err(ErrorResponse {\n code: response.ssl_result_message.clone(),\n message: response.ssl_result_message.clone(),\n reason: Some(response.ssl_result_message.clone()),\n attempt_status: None,\n connector_transaction_id: Some(response.ssl_txn_id.clone()),\n connector_response_reference_id: None,\n status_code: item.http_code,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n } else {\n Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(\n response.ssl_txn_id.clone(),\n ),\n redirection_data: Box::new(None),\n mandate_reference: Box::new(Some(MandateReference {\n connector_mandate_id: response\n .ssl_token\n .as_ref()\n .map(|secret| secret.clone().expose()),\n payment_method_id: None,\n mandate_metadata: None,\n connector_mandate_request_reference_id: None,\n })),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: Some(response.ssl_txn_id.clone()),\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n })\n }\n }\n };\n Ok(Self {\n status,\n response,\n ..item.data\n })\n }\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub enum TransactionSyncStatus {\n PEN, // Pended\n OPN, // Unpended / release / open\n REV, // Review\n STL, // Settled\n PST, // Failed due to post-auth rule\n FPR, // Failed due to fraud prevention rules\n PRE, // Failed due to pre-auth rule\n}\n\n#[derive(Debug, Serialize)]\n#[serde(rename = \"txn\")]\npub struct PaymentsCaptureRequest {\n pub ssl_transaction_type: TransactionType,\n pub ssl_account_id: Secret,\n pub ssl_user_id: Secret,\n pub ssl_pin: Secret,\n pub ssl_amount: StringMajorUnit,\n pub ssl_txn_id: String,\n}\n#[derive(Debug, Serialize)]\n#[serde(rename = \"txn\")]\npub struct PaymentsVoidRequest {\n pub ssl_transaction_type: TransactionType,\n pub ssl_account_id: Secret,\n pub ssl_user_id: Secret,\n pub ssl_pin: Secret,\n pub ssl_txn_id: String,\n}\n\n#[derive(Debug, Serialize)]\n#[serde(rename = \"txn\")]\npub struct ElavonRefundRequest {\n pub ssl_transaction_type: TransactionType,\n pub ssl_account_id: Secret,\n pub ssl_user_id: Secret,\n pub ssl_pin: Secret,\n pub ssl_amount: StringMajorUnit,\n pub ssl_txn_id: String,\n}\n\n#[derive(Debug, Serialize)]\n#[serde(rename = \"txn\")]\npub struct SyncRequest {\n pub ssl_transaction_type: TransactionType,\n pub ssl_account_id: Secret,\n pub ssl_user_id: Secret,\n pub ssl_pin: Secret,\n pub ssl_txn_id: String,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(rename = \"txn\")]\npub struct ElavonSyncResponse {\n pub ssl_trans_status: TransactionSyncStatus,\n pub ssl_transaction_type: SyncTransactionType,\n pub ssl_txn_id: String,\n}\nimpl TryFrom<&RefundSyncRouterData> for SyncRequest {\n type Error = error_stack::Report;\n fn try_from(item: &RefundSyncRouterData) -> Result {\n let auth = ElavonAuthType::try_from(&item.connector_auth_type)?;\n Ok(Self {\n ssl_txn_id: item.request.get_connector_refund_id()?,\n ssl_transaction_type: TransactionType::TxnQuery,\n ssl_account_id: auth.account_id.clone(),\n ssl_user_id: auth.user_id.clone(),\n ssl_pin: auth.pin.clone(),\n })\n }\n}\nimpl TryFrom<&PaymentsSyncRouterData> for SyncRequest {\n type Error = error_stack::Report;\n fn try_from(item: &PaymentsSyncRouterData) -> Result {\n let auth = ElavonAuthType::try_from(&item.connector_auth_type)?;\n Ok(Self {\n ssl_txn_id: item\n .request\n .connector_transaction_id\n .get_connector_transaction_id()\n .change_context(errors::ConnectorError::MissingConnectorTransactionID)?,\n ssl_transaction_type: TransactionType::TxnQuery,\n ssl_account_id: auth.account_id.clone(),\n ssl_user_id: auth.user_id.clone(),\n ssl_pin: auth.pin.clone(),\n })\n }\n}\nimpl TryFrom<&ElavonRouterData<&RefundsRouterData>> for ElavonRefundRequest {\n type Error = error_stack::Report;\n fn try_from(item: &ElavonRouterData<&RefundsRouterData>) -> Result {\n let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;\n Ok(Self {\n ssl_txn_id: item.router_data.request.connector_transaction_id.clone(),\n ssl_amount: item.amount.clone(),\n ssl_transaction_type: TransactionType::CcReturn,\n ssl_account_id: auth.account_id.clone(),\n ssl_user_id: auth.user_id.clone(),\n ssl_pin: auth.pin.clone(),\n })\n }\n}\n\nimpl TryFrom<&ElavonRouterData<&PaymentsCaptureRouterData>> for PaymentsCaptureRequest {\n type Error = error_stack::Report;\n fn try_from(item: &ElavonRouterData<&PaymentsCaptureRouterData>) -> Result {\n let auth = ElavonAuthType::try_from(&item.router_data.connector_auth_type)?;\n Ok(Self {\n ssl_txn_id: item.router_data.request.connector_transaction_id.clone(),\n ssl_amount: item.amount.clone(),\n ssl_transaction_type: TransactionType::CcComplete,\n ssl_account_id: auth.account_id.clone(),\n ssl_user_id: auth.user_id.clone(),\n ssl_pin: auth.pin.clone(),\n })\n }\n}\n\nimpl TryFrom> for PaymentsSyncRouterData {\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsSyncResponseRouterData,\n ) -> Result {\n Ok(Self {\n status: get_sync_status(item.data.status, &item.response),\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.ssl_txn_id),\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n }),\n ..item.data\n })\n }\n}\nimpl TryFrom> for RefundsRouterData {\n type Error = error_stack::Report;\n fn try_from(\n item: RefundsResponseRouterData,\n ) -> Result {\n Ok(Self {\n response: Ok(RefundsResponseData {\n connector_refund_id: item.response.ssl_txn_id.clone(),\n refund_status: get_refund_status(item.data.request.refund_status, &item.response),\n }),\n ..item.data\n })\n }\n}\n\nimpl TryFrom>\n for PaymentsCaptureRouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsCaptureResponseRouterData,\n ) -> Result {\n let status = map_payment_status(&item.response.result, enums::AttemptStatus::Charged);\n let response = match &item.response.result {\n ElavonResult::Error(error) => Err(ErrorResponse {\n code: error\n .error_code\n .clone()\n .unwrap_or(NO_ERROR_CODE.to_string()),\n message: error.error_message.clone(),\n reason: Some(error.error_message.clone()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n status_code: item.http_code,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n }),\n ElavonResult::Success(response) => {\n if status == enums::AttemptStatus::Failure {\n Err(ErrorResponse {\n code: response.ssl_result_message.clone(),\n message: response.ssl_result_message.clone(),\n reason: Some(response.ssl_result_message.clone()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n status_code: item.http_code,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n } else {\n Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(\n response.ssl_txn_id.clone(),\n ),\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: Some(response.ssl_txn_id.clone()),\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n })\n }\n }\n };\n Ok(Self {\n status,\n response,\n ..item.data\n })\n }\n}\nimpl TryFrom>\n for RefundsRouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: RefundsResponseRouterData,\n ) -> Result {\n let status = enums::RefundStatus::from(&item.response.result);\n let response = match &item.response.result {\n ElavonResult::Error(error) => Err(ErrorResponse {\n code: error\n .error_code\n .clone()\n .unwrap_or(NO_ERROR_CODE.to_string()),\n message: error.error_message.clone(),\n reason: Some(error.error_message.clone()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n status_code: item.http_code,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n }),\n ElavonResult::Success(response) => {\n if status == enums::RefundStatus::Failure {\n Err(ErrorResponse {\n code: response.ssl_result_message.clone(),\n message: response.ssl_result_message.clone(),\n reason: Some(response.ssl_result_message.clone()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n status_code: item.http_code,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n } else {\n Ok(RefundsResponseData {\n connector_refund_id: response.ssl_txn_id.clone(),\n refund_status: enums::RefundStatus::from(&item.response.result),\n })\n }\n }\n };\n Ok(Self {\n response,\n ..item.data\n })\n }\n}\n\ntrait ElavonResponseValidator {\n fn is_successful(&self) -> bool;\n}\nimpl ElavonResponseValidator for ElavonResult {\n fn is_successful(&self) -> bool {\n matches!(self, Self::Success(response) if response.ssl_result == SslResult::ImportedBatchFile)\n }\n}\n\nfn map_payment_status(\n item: &ElavonResult,\n success_status: enums::AttemptStatus,\n) -> enums::AttemptStatus {\n if item.is_successful() {\n success_status\n } else {\n enums::AttemptStatus::Failure\n }\n}\n\nimpl From<&ElavonResult> for enums::RefundStatus {\n fn from(item: &ElavonResult) -> Self {\n if item.is_successful() {\n Self::Success\n } else {\n Self::Failure\n }\n }\n}\nfn get_refund_status(\n prev_status: enums::RefundStatus,\n item: &ElavonSyncResponse,\n) -> enums::RefundStatus {\n match item.ssl_trans_status {\n TransactionSyncStatus::REV | TransactionSyncStatus::OPN | TransactionSyncStatus::PEN => {\n prev_status\n }\n TransactionSyncStatus::STL => enums::RefundStatus::Success,\n TransactionSyncStatus::PST | TransactionSyncStatus::FPR | TransactionSyncStatus::PRE => {\n enums::RefundStatus::Failure\n }\n }\n}\nimpl From<&ElavonSyncResponse> for enums::AttemptStatus {\n fn from(item: &ElavonSyncResponse) -> Self {\n match item.ssl_trans_status {\n TransactionSyncStatus::REV\n | TransactionSyncStatus::OPN\n | TransactionSyncStatus::PEN => Self::Pending,\n TransactionSyncStatus::STL => match item.ssl_transaction_type {\n SyncTransactionType::Sale => Self::Charged,\n SyncTransactionType::AuthOnly => Self::Authorized,\n SyncTransactionType::Return => Self::Pending,\n },\n TransactionSyncStatus::PST\n | TransactionSyncStatus::FPR\n | TransactionSyncStatus::PRE => Self::Failure,\n }\n }\n}\nfn get_sync_status(\n prev_status: enums::AttemptStatus,\n item: &ElavonSyncResponse,\n) -> enums::AttemptStatus {\n match item.ssl_trans_status {\n TransactionSyncStatus::REV | TransactionSyncStatus::OPN | TransactionSyncStatus::PEN => {\n prev_status\n }\n TransactionSyncStatus::STL => match item.ssl_transaction_type {\n SyncTransactionType::Sale => enums::AttemptStatus::Charged,\n SyncTransactionType::AuthOnly => enums::AttemptStatus::Authorized,\n SyncTransactionType::Return => enums::AttemptStatus::Pending,\n },\n TransactionSyncStatus::PST | TransactionSyncStatus::FPR | TransactionSyncStatus::PRE => {\n enums::AttemptStatus::Failure\n }\n }\n}\n\nfn get_payment_status(item: &ElavonResult, is_auto_capture: bool) -> enums::AttemptStatus {\n if item.is_successful() {\n if is_auto_capture {\n enums::AttemptStatus::Charged\n } else {\n enums::AttemptStatus::Authorized\n }\n } else {\n enums::AttemptStatus::Failure\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__finix.rs", "text": "pub mod transformers;\n\nuse std::{collections::HashMap, sync::LazyLock};\n\nuse api_models::webhooks::IncomingWebhookEvent;\nuse base64::Engine;\nuse common_enums::{enums, CaptureMethod, ConnectorIntegrationStatus, PaymentMethodType};\nuse common_utils::{\n crypto::{HmacSha256, VerifySignature},\n errors::CustomResult,\n ext_traits::{ByteSliceExt, BytesExt},\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{\n AmountConvertor, MinorUnit, MinorUnitForConnector, StringMinorUnit,\n StringMinorUnitForConnector,\n },\n};\nuse error_stack::ResultExt;\nuse hyperswitch_domain_models::{\n payment_method_data::PaymentMethodData,\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n CreateConnectorCustomer,\n },\n router_request_types::{\n AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,\n PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,\n PaymentsSyncData, RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,\n PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n disputes::DisputePayload,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, Response},\n webhooks,\n};\nuse masking::{ExposeInterface, Mask};\nuse transformers as finix;\n\nuse crate::{\n connectors::finix::transformers::FinixWebhookSignature,\n constants::headers,\n types::ResponseRouterData,\n utils::{self, PaymentMethodDataType},\n};\n\n#[derive(Clone)]\npub struct Finix {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n amount_converter_webhooks: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Finix {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &MinorUnitForConnector,\n amount_converter_webhooks: &StringMinorUnitForConnector,\n }\n }\n}\n\nimpl api::Payment for Finix {}\nimpl api::PaymentSession for Finix {}\nimpl api::ConnectorAccessToken for Finix {}\nimpl api::MandateSetup for Finix {}\nimpl api::PaymentAuthorize for Finix {}\nimpl api::PaymentSync for Finix {}\nimpl api::PaymentCapture for Finix {}\nimpl api::PaymentVoid for Finix {}\nimpl api::Refund for Finix {}\nimpl api::RefundExecute for Finix {}\nimpl api::RefundSync for Finix {}\nimpl api::PaymentToken for Finix {}\nimpl api::ConnectorCustomer for Finix {}\n\nimpl ConnectorIntegration\n for Finix\n{\n fn get_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}/identities\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = finix::FinixRouterData::try_from((MinorUnit::zero(), req))?;\n let connector_req = finix::FinixCreateIdentityRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::ConnectorCustomerType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::ConnectorCustomerType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::ConnectorCustomerType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult<\n RouterData,\n errors::ConnectorError,\n > {\n let response: finix::FinixIdentityResponse = res\n .response\n .parse_struct(\"Finix IdentityResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Finix\n{\n fn get_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}/payment_instruments\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = finix::FinixRouterData::try_from((MinorUnit::zero(), req))?;\n let connector_req =\n finix::FinixCreatePaymentInstrumentRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::TokenizationType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::TokenizationType::get_headers(self, req, connectors)?)\n .set_body(types::TokenizationType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult<\n RouterData,\n errors::ConnectorError,\n > {\n let response: finix::FinixInstrumentResponse = res\n .response\n .parse_struct(\"Finix InstrumentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorCommonExt for Finix\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let mut header = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )];\n let mut api_key = self.get_auth_header(&req.connector_auth_type)?;\n header.append(&mut api_key);\n Ok(header)\n }\n}\n\nimpl ConnectorCommon for Finix {\n fn id(&self) -> &'static str {\n \"finix\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.finix.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, errors::ConnectorError> {\n let auth = finix::FinixAuthType::try_from(auth_type)\n .change_context(errors::ConnectorError::FailedToObtainAuthType)?;\n let credentials = format!(\n \"{}:{}\",\n auth.finix_user_name.clone().expose(),\n auth.finix_password.clone().expose()\n );\n let encoded = format!(\n \"Basic {:}\",\n base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes())\n );\n\n Ok(vec![(\n headers::AUTHORIZATION.to_string(),\n encoded.into_masked(),\n )])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: finix::FinixErrorResponse =\n res.response\n .parse_struct(\"FinixErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: response.get_code(),\n message: response.get_message(),\n reason: None,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Finix {\n fn validate_mandate_payment(\n &self,\n pm_type: Option,\n pm_data: PaymentMethodData,\n ) -> CustomResult<(), errors::ConnectorError> {\n let mandate_supported_pmd = std::collections::HashSet::from([\n PaymentMethodDataType::Card,\n PaymentMethodDataType::GooglePay,\n PaymentMethodDataType::ApplePay,\n ]);\n utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())\n }\n\n fn validate_psync_reference_id(\n &self,\n _data: &PaymentsSyncData,\n _is_three_ds: bool,\n _status: enums::AttemptStatus,\n _connector_meta_data: Option,\n ) -> CustomResult<(), errors::ConnectorError> {\n Ok(())\n }\n}\n\nimpl ConnectorIntegration for Finix {\n //TODO: implement sessions flow\n}\n\nimpl ConnectorIntegration for Finix {}\n\nimpl ConnectorIntegration for Finix {\n fn get_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}/payment_instruments\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = finix::FinixRouterData::try_from((MinorUnit::zero(), req))?;\n let connector_req =\n finix::FinixCreatePaymentInstrumentRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n fn build_request(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::SetupMandateType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::SetupMandateType::get_headers(self, req, connectors)?)\n .set_body(types::SetupMandateType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &RouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult<\n RouterData,\n errors::ConnectorError,\n >\n where\n SetupMandate: Clone,\n SetupMandateRequestData: Clone,\n PaymentsResponseData: Clone,\n {\n let response: finix::FinixInstrumentResponse = res\n .response\n .parse_struct(\"Finix InstrumentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n finix::get_setup_mandate_router_data(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Finix {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let flow = match req.request.capture_method.unwrap_or_default() {\n CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic => \"transfers\",\n CaptureMethod::Manual | CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => {\n \"authorizations\"\n }\n };\n Ok(format!(\"{}/{}\", self.base_url(connectors), flow))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = finix::FinixRouterData::try_from((amount, req))?;\n let connector_req = finix::FinixPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: finix::FinixPaymentsResponse = res\n .response\n .parse_struct(\"Finix PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n finix::get_finix_response(\n ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n },\n finix::FinixFlow::get_flow_for_auth(data.request.capture_method.unwrap_or_default()),\n )\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Finix {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_transaction_id = req\n .request\n .connector_transaction_id\n .get_connector_transaction_id()\n .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;\n match finix::FinixId::from(connector_transaction_id) {\n transformers::FinixId::Auth(id) => Ok(format!(\n \"{}/authorizations/{}\",\n self.base_url(connectors),\n id\n )),\n transformers::FinixId::Transfer(id) => {\n Ok(format!(\"{}/transfers/{}\", self.base_url(connectors), id))\n }\n }\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let combined_response: finix::FinixCombinedPaymentResponse = res\n .response\n .parse_struct(\"finix PaymentsSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n let response = combined_response.get_payment_response()?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n let response_id = response.id.clone();\n finix::get_finix_response(\n ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n },\n match finix::FinixId::from(response_id) {\n finix::FinixId::Auth(_) => finix::FinixFlow::Auth,\n finix::FinixId::Transfer(_) => finix::FinixFlow::Transfer,\n },\n )\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Finix {\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_transaction_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}/authorizations/{}\",\n self.base_url(connectors),\n connector_transaction_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount_to_capture,\n req.request.currency,\n )?;\n let connector_router_data = finix::FinixRouterData::try_from((amount, req))?;\n let connector_req = finix::FinixCaptureRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Put)\n .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsCaptureType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: finix::FinixPaymentsResponse = res\n .response\n .parse_struct(\"Finix PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n finix::get_finix_response(\n ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n },\n finix::FinixFlow::Capture,\n )\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Finix {\n fn get_headers(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_transaction_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}/authorizations/{}\",\n self.base_url(connectors),\n connector_transaction_id\n ))\n }\n\n fn get_request_body(\n &self,\n _req: &PaymentsCancelRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = finix::FinixCancelRequest { void_me: true };\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Put)\n .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)\n .set_body(types::PaymentsVoidType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCancelRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: finix::FinixPaymentsResponse = res\n .response\n .parse_struct(\"Finix PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n finix::get_finix_response(\n ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n },\n finix::FinixFlow::Transfer,\n )\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Finix {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}/transfers/{}/reversals\",\n self.base_url(connectors),\n req.request.connector_transaction_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let refund_amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_refund_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = finix::FinixRouterData::try_from((refund_amount, req))?;\n let connector_req = finix::FinixCreateRefundRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&types::RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundExecuteType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::RefundExecuteType::get_request_body(\n self, req, connectors,\n )?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let combined_response: finix::FinixCombinedPaymentResponse = res\n .response\n .parse_struct(\"FinixPaymentsResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n let response = combined_response.get_payment_response()?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Finix {\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let refund_id = req\n .request\n .connector_refund_id\n .clone()\n .ok_or(errors::ConnectorError::MissingConnectorRefundID)?;\n Ok(format!(\n \"{}/transfers/{}\",\n self.base_url(connectors),\n refund_id\n ))\n }\n\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundSyncType::get_headers(self, req, connectors)?)\n .set_body(types::RefundSyncType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: finix::FinixPaymentsResponse = res\n .response\n .parse_struct(\"FinixPaymentsResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nstatic FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock = LazyLock::new(|| {\n let default_capture_methods = vec![CaptureMethod::Automatic, CaptureMethod::Manual];\n\n let supported_card_network = vec![\n common_enums::CardNetwork::Visa,\n common_enums::CardNetwork::Mastercard,\n common_enums::CardNetwork::AmericanExpress,\n common_enums::CardNetwork::Discover,\n common_enums::CardNetwork::JCB,\n common_enums::CardNetwork::DinersClub,\n common_enums::CardNetwork::UnionPay,\n common_enums::CardNetwork::Interac,\n common_enums::CardNetwork::Maestro,\n ];\n\n let mut finix_supported_payment_methods = SupportedPaymentMethods::new();\n\n finix_supported_payment_methods.add(\n common_enums::PaymentMethod::Card,\n PaymentMethodType::Credit,\n PaymentMethodDetails {\n mandates: common_enums::FeatureStatus::Supported,\n refunds: common_enums::FeatureStatus::Supported,\n supported_capture_methods: default_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card(\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n },\n ),\n ),\n },\n );\n finix_supported_payment_methods.add(\n common_enums::PaymentMethod::Card,\n PaymentMethodType::Debit,\n PaymentMethodDetails {\n mandates: common_enums::FeatureStatus::Supported,\n refunds: common_enums::FeatureStatus::Supported,\n supported_capture_methods: default_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card(\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n },\n ),\n ),\n },\n );\n finix_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n PaymentMethodType::GooglePay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: default_capture_methods.clone(),\n specific_features: None,\n },\n );\n finix_supported_payment_methods.add(\n common_enums::PaymentMethod::Wallet,\n PaymentMethodType::ApplePay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: default_capture_methods.clone(),\n specific_features: None,\n },\n );\n finix_supported_payment_methods\n});\n\nstatic FINIX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Finix\",\n description: \"Finix is a payments technology provider enabling businesses to accept and send payments online or in person\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: ConnectorIntegrationStatus::Sandbox,\n};\n\nstatic FINIX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];\n\nimpl ConnectorSpecifications for Finix {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&FINIX_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*FINIX_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&FINIX_SUPPORTED_WEBHOOK_FLOWS)\n }\n\n fn should_call_connector_customer(\n &self,\n _payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,\n ) -> bool {\n true\n }\n fn should_call_tokenization_before_setup_mandate(&self) -> bool {\n false\n }\n}\nfn is_test_webhook(request: &webhooks::IncomingWebhookRequestDetails<'_>) -> bool {\n let req_data = String::from_utf8(request.body.to_vec());\n req_data == Ok(\"{}\".to_string())\n}\npub fn decode_finix_signature(\n header_value: &actix_web::http::header::HeaderMap,\n) -> Result {\n let security_header = header_value\n .get(\"Finix-Signature\")\n .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?\n .to_str()\n .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)?\n .to_owned();\n\n let map: HashMap<&str, &str> = security_header\n .split(',')\n .map(|kv| {\n let mut parts = kv.trim().splitn(2, '=');\n let key = parts\n .next()\n .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;\n let value = parts\n .next()\n .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;\n Ok((key, value))\n })\n .collect::>()?;\n\n let timestamp = map\n .get(\"timestamp\")\n .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?\n .to_string();\n\n let sig = map\n .get(\"sig\")\n .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?\n .as_bytes()\n .to_vec();\n\n Ok(FinixWebhookSignature { timestamp, sig })\n}\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Finix {\n fn get_webhook_source_verification_algorithm(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Box::new(HmacSha256))\n }\n\n fn get_webhook_source_verification_signature(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n let security_header_kvs = decode_finix_signature(request.headers)?;\n\n hex::decode(security_header_kvs.sig)\n .change_context(errors::ConnectorError::WebhookSignatureNotFound)\n }\n fn get_webhook_source_verification_message(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _merchant_id: &common_utils::id_type::MerchantId,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n let security_header_kvs = decode_finix_signature(request.headers)?;\n\n Ok(format!(\n \"{}:{}\",\n &security_header_kvs.timestamp,\n String::from_utf8_lossy(request.body)\n )\n .into_bytes())\n }\n fn get_webhook_object_reference_id(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n let webhook_body: finix::FinixWebhookBody =\n request\n .body\n .parse_struct(\"FinixWebhookBody\")\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n\n webhook_body.get_webhook_object_reference_id()\n }\n\n fn get_webhook_event_type(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n if is_test_webhook(request) {\n return Ok(IncomingWebhookEvent::SetupWebhook);\n }\n let webhook_body: finix::FinixWebhookBody =\n request\n .body\n .parse_struct(\"FinixWebhookBody\")\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n\n webhook_body.get_webhook_event_type()\n }\n fn get_dispute_details(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n let webhook_body: finix::FinixWebhookBody =\n request\n .body\n .parse_struct(\"FinixWebhookBody\")\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n webhook_body.get_dispute_details()\n }\n fn get_webhook_resource_object(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n let webhook_body: finix::FinixWebhookBody =\n request\n .body\n .parse_struct(\"FinixWebhookBody\")\n .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;\n Ok(Box::new(webhook_body))\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__globepay.rs", "text": "pub mod transformers;\nuse std::sync::LazyLock;\n\nuse common_enums::enums;\nuse common_utils::{\n crypto::{self, GenerateDigest},\n errors::CustomResult,\n ext_traits::BytesExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, MinorUnit, MinorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse hex::encode;\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n },\n router_request_types::{\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,\n RefundSyncRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n consts, errors,\n events::connector_api_logs::ConnectorEvent,\n types::{PaymentsAuthorizeType, PaymentsSyncType, RefundExecuteType, RefundSyncType, Response},\n webhooks,\n};\nuse masking::ExposeInterface;\nuse rand::distributions::DistString;\nuse time::OffsetDateTime;\nuse transformers as globepay;\n\nuse crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};\n\n#[derive(Clone)]\npub struct Globepay {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Globepay {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &MinorUnitForConnector,\n }\n }\n}\n\nimpl api::Payment for Globepay {}\nimpl api::PaymentSession for Globepay {}\nimpl api::ConnectorAccessToken for Globepay {}\nimpl api::MandateSetup for Globepay {}\nimpl api::PaymentAuthorize for Globepay {}\nimpl api::PaymentSync for Globepay {}\nimpl api::PaymentCapture for Globepay {}\nimpl api::PaymentVoid for Globepay {}\nimpl api::Refund for Globepay {}\nimpl api::RefundExecute for Globepay {}\nimpl api::RefundSync for Globepay {}\nimpl api::PaymentToken for Globepay {}\n\nimpl ConnectorIntegration\n for Globepay\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorCommonExt for Globepay\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let header = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )];\n Ok(header)\n }\n}\n\nfn get_globlepay_query_params(\n connector_auth_type: &ConnectorAuthType,\n) -> CustomResult {\n let auth_type = globepay::GlobepayAuthType::try_from(connector_auth_type)?;\n let time = (OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000).to_string();\n let nonce_str = rand::distributions::Alphanumeric.sample_string(&mut rand::thread_rng(), 12);\n let valid_string = format!(\n \"{}&{time}&{nonce_str}&{}\",\n auth_type.partner_code.expose(),\n auth_type.credential_code.expose()\n );\n let digest = crypto::Sha256\n .generate_digest(valid_string.as_bytes())\n .change_context(errors::ConnectorError::RequestEncodingFailed)\n .attach_printable(\"error encoding the query params\")?;\n let sign = encode(digest).to_lowercase();\n let param = format!(\"?sign={sign}&time={time}&nonce_str={nonce_str}\");\n Ok(param)\n}\n\nfn get_partner_code(\n connector_auth_type: &ConnectorAuthType,\n) -> CustomResult {\n let auth_type = globepay::GlobepayAuthType::try_from(connector_auth_type)?;\n Ok(auth_type.partner_code.expose())\n}\n\nimpl ConnectorCommon for Globepay {\n fn id(&self) -> &'static str {\n \"globepay\"\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.globepay.base_url.as_ref()\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: globepay::GlobepayErrorResponse = res\n .response\n .parse_struct(\"GlobepayErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_error_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: response.return_code.to_string(),\n message: consts::NO_ERROR_MESSAGE.to_string(),\n reason: Some(response.return_msg),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Globepay {}\n\nimpl ConnectorIntegration for Globepay {}\n\nimpl ConnectorIntegration for Globepay {}\n\nimpl ConnectorIntegration\n for Globepay\n{\n fn build_request(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(\n errors::ConnectorError::NotImplemented(\"Setup Mandate flow for Globepay\".to_string())\n .into(),\n )\n }\n}\n\nimpl ConnectorIntegration for Globepay {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let query_params = get_globlepay_query_params(&req.connector_auth_type)?;\n if matches!(\n req.request.capture_method,\n Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic)\n ) {\n Ok(format!(\n \"{}api/v1.0/gateway/partners/{}/orders/{}{query_params}\",\n self.base_url(connectors),\n get_partner_code(&req.connector_auth_type)?,\n req.payment_id\n ))\n } else {\n Err(errors::ConnectorError::FlowNotSupported {\n flow: \"Manual Capture\".to_owned(),\n connector: \"Globepay\".to_owned(),\n }\n .into())\n }\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = globepay::GlobepayRouterData::from((amount, req));\n let connector_req = globepay::GlobepayPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Put)\n .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)\n .set_body(PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: globepay::GlobepayPaymentsResponse = res\n .response\n .parse_struct(\"Globepay PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Globepay {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let query_params = get_globlepay_query_params(&req.connector_auth_type)?;\n Ok(format!(\n \"{}api/v1.0/gateway/partners/{}/orders/{}{query_params}\",\n self.base_url(connectors),\n get_partner_code(&req.connector_auth_type)?,\n req.payment_id\n ))\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: globepay::GlobepaySyncResponse = res\n .response\n .parse_struct(\"globepay PaymentsSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Globepay {\n fn build_request(\n &self,\n _req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(errors::ConnectorError::FlowNotSupported {\n flow: \"Manual Capture\".to_owned(),\n connector: \"Globepay\".to_owned(),\n }\n .into())\n }\n}\n\nimpl ConnectorIntegration for Globepay {}\n\nimpl ConnectorIntegration for Globepay {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let query_params = get_globlepay_query_params(&req.connector_auth_type)?;\n Ok(format!(\n \"{}api/v1.0/gateway/partners/{}/orders/{}/refunds/{}{query_params}\",\n self.base_url(connectors),\n get_partner_code(&req.connector_auth_type)?,\n req.payment_id,\n req.request.refund_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let refund_amount = convert_amount(\n self.amount_converter,\n req.request.minor_refund_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = globepay::GlobepayRouterData::from((refund_amount, req));\n let connector_req = globepay::GlobepayRefundRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Put)\n .url(&RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(RefundExecuteType::get_headers(self, req, connectors)?)\n .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: globepay::GlobepayRefundResponse = res\n .response\n .parse_struct(\"Globalpay RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Globepay {\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let query_params = get_globlepay_query_params(&req.connector_auth_type)?;\n Ok(format!(\n \"{}api/v1.0/gateway/partners/{}/orders/{}/refunds/{}{query_params}\",\n self.base_url(connectors),\n get_partner_code(&req.connector_auth_type)?,\n req.payment_id,\n req.request.refund_id\n ))\n }\n\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(RefundSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: globepay::GlobepayRefundResponse = res\n .response\n .parse_struct(\"Globalpay RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Globepay {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic GLOBEPAY_SUPPORTED_PAYMENT_METHODS: LazyLock =\n LazyLock::new(|| {\n let supported_capture_methods = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let mut globepay_supported_payment_methods = SupportedPaymentMethods::new();\n\n globepay_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n enums::PaymentMethodType::AliPay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n globepay_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n enums::PaymentMethodType::WeChatPay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n globepay_supported_payment_methods\n });\n\nstatic GLOBEPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Globepay\",\n description: \"GlobePay Limited is a professional cross-border payment solution provider (WeChat Pay & Alipay) in the UK\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: enums::ConnectorIntegrationStatus::Sandbox,\n };\n\nstatic GLOBEPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];\n\nimpl ConnectorSpecifications for Globepay {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&GLOBEPAY_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*GLOBEPAY_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&GLOBEPAY_SUPPORTED_WEBHOOK_FLOWS)\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__gpayments.rs", "text": "pub mod gpayments_types;\npub mod transformers;\n\nuse api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};\nuse common_utils::{\n errors::CustomResult,\n ext_traits::ByteSliceExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, MinorUnit, MinorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse gpayments_types::GpaymentsConnectorMetaData;\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n authentication::{\n Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,\n },\n AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,\n SetupMandate, Void,\n },\n router_request_types::{\n authentication::{\n ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData,\n PreAuthNRequestData,\n },\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n AuthenticationResponseData, ConnectorInfo, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self,\n authentication::{\n ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication,\n ConnectorPreAuthenticationVersionCall, ExternalAuthentication,\n },\n ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n errors::ConnectorError,\n events::connector_api_logs::ConnectorEvent,\n types::Response,\n webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},\n};\nuse masking::Maskable;\nuse transformers as gpayments;\n\nuse crate::{\n constants::headers,\n types::{\n ConnectorAuthenticationRouterData, ConnectorAuthenticationType,\n ConnectorPostAuthenticationRouterData, ConnectorPostAuthenticationType,\n ConnectorPreAuthenticationType, ConnectorPreAuthenticationVersionCallType,\n PreAuthNRouterData, PreAuthNVersionCallRouterData, ResponseRouterData,\n },\n utils::to_connector_meta,\n};\n\n#[derive(Clone)]\npub struct Gpayments {\n _amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Gpayments {\n pub fn new() -> &'static Self {\n &Self {\n _amount_converter: &MinorUnitForConnector,\n }\n }\n}\n\nimpl api::Payment for Gpayments {}\nimpl api::PaymentSession for Gpayments {}\nimpl api::ConnectorAccessToken for Gpayments {}\nimpl api::MandateSetup for Gpayments {}\nimpl api::PaymentAuthorize for Gpayments {}\nimpl api::PaymentSync for Gpayments {}\nimpl api::PaymentCapture for Gpayments {}\nimpl api::PaymentVoid for Gpayments {}\nimpl api::Refund for Gpayments {}\nimpl api::RefundExecute for Gpayments {}\nimpl api::RefundSync for Gpayments {}\nimpl api::PaymentToken for Gpayments {}\n\nimpl ConnectorIntegration\n for Gpayments\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorCommonExt for Gpayments\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n let header = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )];\n Ok(header)\n }\n}\n\nimpl ConnectorCommon for Gpayments {\n fn id(&self) -> &'static str {\n \"gpayments\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Minor\n // TODO! Check connector documentation, on which unit they are processing the currency.\n // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,\n // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.gpayments.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n _auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, ConnectorError> {\n Ok(vec![])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: gpayments_types::TDS2ApiError = res\n .response\n .parse_struct(\"gpayments_types TDS2ApiError\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: response.error_code,\n message: response.error_description,\n reason: response.error_detail,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Gpayments {\n //TODO: implement functions when support enabled\n}\n\nimpl ConnectorIntegration for Gpayments {}\n\nimpl ConnectorIntegration for Gpayments {}\n\nimpl ConnectorIntegration\n for Gpayments\n{\n}\n\nimpl ConnectorIntegration for Gpayments {}\n\nimpl ConnectorIntegration for Gpayments {}\n\nimpl ConnectorIntegration for Gpayments {}\n\nimpl ConnectorIntegration for Gpayments {}\n\nimpl ConnectorIntegration for Gpayments {}\n\nimpl ConnectorIntegration for Gpayments {}\n\n#[async_trait::async_trait]\nimpl IncomingWebhook for Gpayments {\n fn get_webhook_object_reference_id(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _context: Option<&WebhookContext>,\n ) -> CustomResult {\n Err(report!(ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, ConnectorError> {\n Err(report!(ConnectorError::WebhooksNotImplemented))\n }\n}\n\nimpl ExternalAuthentication for Gpayments {}\nimpl ConnectorAuthentication for Gpayments {}\nimpl ConnectorPreAuthentication for Gpayments {}\nimpl ConnectorPreAuthenticationVersionCall for Gpayments {}\nimpl ConnectorPostAuthentication for Gpayments {}\n\nfn build_endpoint(\n base_url: &str,\n connector_metadata: &Option,\n) -> CustomResult {\n let metadata = gpayments::GpaymentsMetaData::try_from(connector_metadata)?;\n let endpoint_prefix = metadata.endpoint_prefix;\n Ok(base_url.replace(\"{{merchant_endpoint_prefix}}\", &endpoint_prefix))\n}\n\nimpl\n ConnectorIntegration<\n Authentication,\n ConnectorAuthenticationRequestData,\n AuthenticationResponseData,\n > for Gpayments\n{\n fn get_headers(\n &self,\n req: &ConnectorAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &ConnectorAuthenticationRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_metadata: GpaymentsConnectorMetaData = to_connector_meta(\n req.request\n .pre_authentication_data\n .connector_metadata\n .clone(),\n )?;\n Ok(connector_metadata.authentication_url)\n }\n\n fn get_request_body(\n &self,\n req: &ConnectorAuthenticationRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req));\n let req_obj =\n gpayments_types::GpaymentsAuthenticationRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(req_obj)))\n }\n fn build_request(\n &self,\n req: &ConnectorAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult, ConnectorError> {\n let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&ConnectorAuthenticationType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(ConnectorAuthenticationType::get_headers(\n self, req, connectors,\n )?)\n .set_body(ConnectorAuthenticationType::get_request_body(\n self, req, connectors,\n )?)\n .add_certificate(Some(gpayments_auth_type.certificate))\n .add_certificate_key(Some(gpayments_auth_type.private_key))\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &ConnectorAuthenticationRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: gpayments_types::GpaymentsAuthenticationSuccessResponse = res\n .response\n .parse_struct(\"gpayments GpaymentsAuthenticationResponse\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\nimpl\n ConnectorIntegration<\n PostAuthentication,\n ConnectorPostAuthenticationRequestData,\n AuthenticationResponseData,\n > for Gpayments\n{\n fn get_headers(\n &self,\n req: &ConnectorPostAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &ConnectorPostAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;\n Ok(format!(\n \"{}/api/v2/auth/brw/result?threeDSServerTransID={}\",\n base_url, req.request.threeds_server_transaction_id,\n ))\n }\n\n fn build_request(\n &self,\n req: &ConnectorPostAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult, ConnectorError> {\n let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&ConnectorPostAuthenticationType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(ConnectorPostAuthenticationType::get_headers(\n self, req, connectors,\n )?)\n .add_certificate(Some(gpayments_auth_type.certificate))\n .add_certificate_key(Some(gpayments_auth_type.private_key))\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &ConnectorPostAuthenticationRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: gpayments_types::GpaymentsPostAuthenticationResponse = res\n .response\n .parse_struct(\"gpayments PaymentsSyncResponse\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n Ok(ConnectorPostAuthenticationRouterData {\n response: Ok(AuthenticationResponseData::PostAuthNResponse {\n trans_status: response.trans_status.into(),\n authentication_value: response.authentication_value,\n eci: response.eci,\n challenge_cancel: None,\n challenge_code_reason: None,\n }),\n ..data.clone()\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Gpayments\n{\n fn get_headers(\n &self,\n req: &PreAuthNRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PreAuthNRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;\n Ok(format!(\"{base_url}/api/v2/auth/brw/init?mode=custom\"))\n }\n\n fn get_request_body(\n &self,\n req: &PreAuthNRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req));\n let req_obj =\n gpayments_types::GpaymentsPreAuthenticationRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(req_obj)))\n }\n\n fn build_request(\n &self,\n req: &PreAuthNRouterData,\n connectors: &Connectors,\n ) -> CustomResult, ConnectorError> {\n let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&ConnectorPreAuthenticationType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(ConnectorPreAuthenticationType::get_headers(\n self, req, connectors,\n )?)\n .set_body(ConnectorPreAuthenticationType::get_request_body(\n self, req, connectors,\n )?)\n .add_certificate(Some(gpayments_auth_type.certificate))\n .add_certificate_key(Some(gpayments_auth_type.private_key))\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PreAuthNRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: gpayments_types::GpaymentsPreAuthenticationResponse = res\n .response\n .parse_struct(\"gpayments GpaymentsPreAuthenticationResponse\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\nimpl\n ConnectorIntegration<\n PreAuthenticationVersionCall,\n PreAuthNRequestData,\n AuthenticationResponseData,\n > for Gpayments\n{\n fn get_headers(\n &self,\n req: &PreAuthNVersionCallRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PreAuthNVersionCallRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;\n Ok(format!(\"{base_url}/api/v2/auth/enrol\"))\n }\n\n fn get_request_body(\n &self,\n req: &PreAuthNVersionCallRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req));\n let req_obj =\n gpayments_types::GpaymentsPreAuthVersionCallRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(req_obj)))\n }\n\n fn build_request(\n &self,\n req: &PreAuthNVersionCallRouterData,\n connectors: &Connectors,\n ) -> CustomResult, ConnectorError> {\n let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?;\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&ConnectorPreAuthenticationVersionCallType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(ConnectorPreAuthenticationVersionCallType::get_headers(\n self, req, connectors,\n )?)\n .set_body(ConnectorPreAuthenticationVersionCallType::get_request_body(\n self, req, connectors,\n )?)\n .add_certificate(Some(gpayments_auth_type.certificate))\n .add_certificate_key(Some(gpayments_auth_type.private_key))\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PreAuthNVersionCallRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: gpayments_types::GpaymentsPreAuthVersionCallResponse = res\n .response\n .parse_struct(\"gpayments GpaymentsPreAuthVersionCallResponse\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nstatic GPAYMENTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"GPayments\",\n description: \"GPayments authentication connector for 3D Secure MPI/ACS services supporting Visa Secure, Mastercard SecureCode, and global card authentication standards\",\n connector_type: common_enums::HyperswitchConnectorCategory::AuthenticationProvider,\n integration_status: common_enums::ConnectorIntegrationStatus::Alpha,\n};\n\nimpl ConnectorSpecifications for Gpayments {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&GPAYMENTS_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n None\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {\n None\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__juspaythreedsserver.rs", "text": "pub mod transformers;\n\nuse common_utils::{\n errors::CustomResult,\n ext_traits::BytesExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate,\n ProcessIncomingWebhook,\n },\n router_request_types::{\n unified_authentication_service::{\n UasAuthenticationRequestData, UasAuthenticationResponseData,\n UasConfirmationRequestData, UasPostAuthenticationRequestData,\n UasPreAuthenticationRequestData, UasWebhookRequestData,\n },\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,\n RefundSyncRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, Response},\n webhooks,\n};\nuse masking::{ExposeInterface, Mask};\nuse transformers as juspaythreedsserver;\n\nuse crate::{constants::headers, types::ResponseRouterData, utils};\n\n#[derive(Clone)]\npub struct Juspaythreedsserver {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Juspaythreedsserver {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &StringMinorUnitForConnector,\n }\n }\n}\n\nimpl api::Payment for Juspaythreedsserver {}\nimpl api::PaymentSession for Juspaythreedsserver {}\nimpl api::ConnectorAccessToken for Juspaythreedsserver {}\nimpl api::MandateSetup for Juspaythreedsserver {}\nimpl api::PaymentAuthorize for Juspaythreedsserver {}\nimpl api::PaymentSync for Juspaythreedsserver {}\nimpl api::PaymentCapture for Juspaythreedsserver {}\nimpl api::PaymentVoid for Juspaythreedsserver {}\nimpl api::Refund for Juspaythreedsserver {}\nimpl api::RefundExecute for Juspaythreedsserver {}\nimpl api::RefundSync for Juspaythreedsserver {}\nimpl api::PaymentToken for Juspaythreedsserver {}\nimpl api::UnifiedAuthenticationService for Juspaythreedsserver {}\nimpl api::UasPreAuthentication for Juspaythreedsserver {}\nimpl api::UasPostAuthentication for Juspaythreedsserver {}\nimpl api::UasAuthenticationConfirmation for Juspaythreedsserver {}\nimpl api::UasAuthentication for Juspaythreedsserver {}\nimpl api::UasProcessWebhook for Juspaythreedsserver {}\n\nimpl\n ConnectorIntegration<\n PreAuthenticate,\n UasPreAuthenticationRequestData,\n UasAuthenticationResponseData,\n > for Juspaythreedsserver\n{\n}\n\nimpl\n ConnectorIntegration<\n PostAuthenticate,\n UasPostAuthenticationRequestData,\n UasAuthenticationResponseData,\n > for Juspaythreedsserver\n{\n}\n\nimpl\n ConnectorIntegration<\n AuthenticationConfirmation,\n UasConfirmationRequestData,\n UasAuthenticationResponseData,\n > for Juspaythreedsserver\n{\n}\n\nimpl\n ConnectorIntegration<\n ProcessIncomingWebhook,\n UasWebhookRequestData,\n UasAuthenticationResponseData,\n > for Juspaythreedsserver\n{\n}\n\nimpl ConnectorIntegration\n for Juspaythreedsserver\n{\n}\n\nimpl ConnectorIntegration\n for Juspaythreedsserver\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorCommonExt for Juspaythreedsserver\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let mut header = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )];\n let mut api_key = self.get_auth_header(&req.connector_auth_type)?;\n header.append(&mut api_key);\n Ok(header)\n }\n}\n\nimpl ConnectorCommon for Juspaythreedsserver {\n fn id(&self) -> &'static str {\n \"juspaythreedsserver\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n // TODO! Check connector documentation, on which unit they are processing the currency.\n // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,\n // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.juspaythreedsserver.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, errors::ConnectorError> {\n let auth = juspaythreedsserver::JuspaythreedsserverAuthType::try_from(auth_type)\n .change_context(errors::ConnectorError::FailedToObtainAuthType)?;\n Ok(vec![(\n headers::AUTHORIZATION.to_string(),\n auth.api_key.expose().into_masked(),\n )])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: juspaythreedsserver::JuspaythreedsserverErrorResponse = res\n .response\n .parse_struct(\"JuspaythreedsserverErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: response.code,\n message: response.message,\n reason: response.reason,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Juspaythreedsserver {\n //TODO: implement functions when support enabled\n}\n\nimpl ConnectorIntegration\n for Juspaythreedsserver\n{\n //TODO: implement sessions flow\n}\n\nimpl ConnectorIntegration\n for Juspaythreedsserver\n{\n}\n\nimpl ConnectorIntegration\n for Juspaythreedsserver\n{\n}\n\nimpl ConnectorIntegration\n for Juspaythreedsserver\n{\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data =\n juspaythreedsserver::JuspaythreedsserverRouterData::from((amount, req));\n let connector_req = juspaythreedsserver::JuspaythreedsserverPaymentsRequest::try_from(\n &connector_router_data,\n )?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: juspaythreedsserver::JuspaythreedsserverPaymentsResponse = res\n .response\n .parse_struct(\"Juspaythreedsserver PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Juspaythreedsserver {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: juspaythreedsserver::JuspaythreedsserverPaymentsResponse = res\n .response\n .parse_struct(\"juspaythreedsserver PaymentsSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Juspaythreedsserver\n{\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn get_request_body(\n &self,\n _req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_request_body method\".to_string()).into())\n }\n\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsCaptureType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: juspaythreedsserver::JuspaythreedsserverPaymentsResponse = res\n .response\n .parse_struct(\"Juspaythreedsserver PaymentsCaptureResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Juspaythreedsserver {}\n\nimpl ConnectorIntegration for Juspaythreedsserver {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let refund_amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_refund_amount,\n req.request.currency,\n )?;\n\n let connector_router_data =\n juspaythreedsserver::JuspaythreedsserverRouterData::from((refund_amount, req));\n let connector_req = juspaythreedsserver::JuspaythreedsserverRefundRequest::try_from(\n &connector_router_data,\n )?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&types::RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundExecuteType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::RefundExecuteType::get_request_body(\n self, req, connectors,\n )?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: juspaythreedsserver::RefundResponse = res\n .response\n .parse_struct(\"juspaythreedsserver RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Juspaythreedsserver {\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RefundSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundSyncType::get_headers(self, req, connectors)?)\n .set_body(types::RefundSyncType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: juspaythreedsserver::RefundResponse = res\n .response\n .parse_struct(\"juspaythreedsserver RefundSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Juspaythreedsserver {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic JUSPAYTHREEDSSERVER_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Juspay 3Ds Server\",\n description: \"Juspay 3DS Server provider for comprehensive 3-Domain Secure authentication, cardholder verification, and fraud prevention across card networks\",\n connector_type: common_enums::HyperswitchConnectorCategory::AuthenticationProvider,\n integration_status: common_enums::ConnectorIntegrationStatus::Alpha,\n};\n\nimpl ConnectorSpecifications for Juspaythreedsserver {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&JUSPAYTHREEDSSERVER_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n None\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {\n None\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__netcetera.rs", "text": "pub mod netcetera_types;\npub mod transformers;\n\nuse std::fmt::Debug;\n\nuse api_models::webhooks::{AuthenticationIdType, IncomingWebhookEvent, ObjectReferenceId};\nuse common_utils::{\n errors::CustomResult,\n ext_traits::ByteSliceExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n};\nuse error_stack::ResultExt;\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n authentication::{\n Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,\n },\n AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,\n SetupMandate, Void,\n },\n router_request_types::{\n authentication::{\n ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData,\n PreAuthNRequestData,\n },\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n AuthenticationResponseData, ConnectorInfo, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n authentication::{\n ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication,\n ConnectorPreAuthenticationVersionCall, ExternalAuthentication,\n },\n *,\n },\n authentication::ExternalAuthenticationPayload,\n configs::Connectors,\n errors::ConnectorError,\n events::connector_api_logs::ConnectorEvent,\n types::Response,\n webhooks::{IncomingWebhook, IncomingWebhookRequestDetails, WebhookContext},\n};\nuse masking::Maskable;\nuse transformers as netcetera;\n\nuse crate::{\n constants::headers,\n types::{\n ConnectorAuthenticationRouterData, ConnectorAuthenticationType,\n ConnectorPreAuthenticationType, PreAuthNRouterData, ResponseRouterData,\n },\n};\n\n#[derive(Debug, Clone)]\npub struct Netcetera;\n\nimpl Payment for Netcetera {}\nimpl PaymentSession for Netcetera {}\nimpl ConnectorAccessToken for Netcetera {}\nimpl MandateSetup for Netcetera {}\nimpl PaymentAuthorize for Netcetera {}\nimpl PaymentSync for Netcetera {}\nimpl PaymentCapture for Netcetera {}\nimpl PaymentVoid for Netcetera {}\nimpl Refund for Netcetera {}\nimpl RefundExecute for Netcetera {}\nimpl RefundSync for Netcetera {}\nimpl PaymentToken for Netcetera {}\n\nimpl ConnectorIntegration\n for Netcetera\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorCommonExt for Netcetera\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n let mut header = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )];\n let mut api_key = self.get_auth_header(&req.connector_auth_type)?;\n header.append(&mut api_key);\n Ok(header)\n }\n}\n\nimpl ConnectorCommon for Netcetera {\n fn id(&self) -> &'static str {\n \"netcetera\"\n }\n\n fn get_currency_unit(&self) -> CurrencyUnit {\n CurrencyUnit::Minor\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.netcetera.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n _auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, ConnectorError> {\n Ok(vec![])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: netcetera::NetceteraErrorResponse = res\n .response\n .parse_struct(\"NetceteraErrorResponse\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: response.error_details.error_code,\n message: response.error_details.error_description,\n reason: response.error_details.error_detail,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Netcetera {}\n\nimpl ConnectorIntegration for Netcetera {}\n\nimpl ConnectorIntegration for Netcetera {}\n\nimpl ConnectorIntegration\n for Netcetera\n{\n}\n\nimpl ConnectorIntegration for Netcetera {}\n\nimpl ConnectorIntegration for Netcetera {}\n\nimpl ConnectorIntegration for Netcetera {}\n\nimpl ConnectorIntegration for Netcetera {}\n\nimpl ConnectorIntegration for Netcetera {}\n\nimpl ConnectorIntegration for Netcetera {}\n\n#[async_trait::async_trait]\nimpl IncomingWebhook for Netcetera {\n fn get_webhook_object_reference_id(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n let webhook_body: netcetera::ResultsResponseData = request\n .body\n .parse_struct(\"netcetera ResultsResponseData\")\n .change_context(ConnectorError::WebhookBodyDecodingFailed)?;\n Ok(ObjectReferenceId::ExternalAuthenticationID(\n AuthenticationIdType::ConnectorAuthenticationId(webhook_body.three_ds_server_trans_id),\n ))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &IncomingWebhookRequestDetails<'_>,\n _context: Option<&WebhookContext>,\n ) -> CustomResult {\n Ok(IncomingWebhookEvent::ExternalAuthenticationARes)\n }\n\n fn get_webhook_resource_object(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, ConnectorError> {\n let webhook_body_value: netcetera::ResultsResponseData = request\n .body\n .parse_struct(\"netcetera ResultsResponseDatae\")\n .change_context(ConnectorError::WebhookBodyDecodingFailed)?;\n Ok(Box::new(webhook_body_value))\n }\n\n fn get_external_authentication_details(\n &self,\n request: &IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n let webhook_body: netcetera::ResultsResponseData = request\n .body\n .parse_struct(\"netcetera ResultsResponseData\")\n .change_context(ConnectorError::WebhookBodyDecodingFailed)?;\n\n let challenge_cancel = webhook_body\n .results_request\n .as_ref()\n .and_then(|v| v.get(\"challengeCancel\").and_then(|v| v.as_str()))\n .map(|s| s.to_string());\n\n let challenge_code_reason = webhook_body\n .results_request\n .as_ref()\n .and_then(|v| v.get(\"transStatusReason\").and_then(|v| v.as_str()))\n .map(|s| s.to_string());\n\n Ok(ExternalAuthenticationPayload {\n trans_status: webhook_body\n .trans_status\n .unwrap_or(common_enums::TransactionStatus::InformationOnly),\n authentication_value: webhook_body.authentication_value,\n eci: webhook_body.eci,\n challenge_cancel,\n challenge_code_reason,\n })\n }\n}\n\nfn build_endpoint(\n base_url: &str,\n connector_metadata: &Option,\n) -> CustomResult {\n let metadata = netcetera::NetceteraMetaData::try_from(connector_metadata)?;\n let endpoint_prefix = metadata.endpoint_prefix;\n Ok(base_url.replace(\"{{merchant_endpoint_prefix}}\", &endpoint_prefix))\n}\n\nimpl ConnectorPreAuthentication for Netcetera {}\nimpl ConnectorPreAuthenticationVersionCall for Netcetera {}\nimpl ExternalAuthentication for Netcetera {}\nimpl ConnectorAuthentication for Netcetera {}\nimpl ConnectorPostAuthentication for Netcetera {}\n\nimpl ConnectorIntegration\n for Netcetera\n{\n fn get_headers(\n &self,\n req: &PreAuthNRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PreAuthNRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;\n Ok(format!(\"{base_url}/3ds/versioning\"))\n }\n\n fn get_request_body(\n &self,\n req: &PreAuthNRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = netcetera::NetceteraRouterData::try_from((0, req))?;\n let req_obj =\n netcetera::NetceteraPreAuthenticationRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(req_obj)))\n }\n\n fn build_request(\n &self,\n req: &PreAuthNRouterData,\n connectors: &Connectors,\n ) -> CustomResult, ConnectorError> {\n let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?;\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&ConnectorPreAuthenticationType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(ConnectorPreAuthenticationType::get_headers(\n self, req, connectors,\n )?)\n .set_body(ConnectorPreAuthenticationType::get_request_body(\n self, req, connectors,\n )?)\n .add_certificate(Some(netcetera_auth_type.certificate))\n .add_certificate_key(Some(netcetera_auth_type.private_key))\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PreAuthNRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: netcetera::NetceteraPreAuthenticationResponse = res\n .response\n .parse_struct(\"netcetera NetceteraPreAuthenticationResponse\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl\n ConnectorIntegration<\n Authentication,\n ConnectorAuthenticationRequestData,\n AuthenticationResponseData,\n > for Netcetera\n{\n fn get_headers(\n &self,\n req: &ConnectorAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &ConnectorAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;\n Ok(format!(\"{base_url}/3ds/authentication\"))\n }\n\n fn get_request_body(\n &self,\n req: &ConnectorAuthenticationRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = netcetera::NetceteraRouterData::try_from((\n &self.get_currency_unit(),\n req.request\n .currency\n .ok_or(ConnectorError::MissingRequiredField {\n field_name: \"currency\",\n })?,\n req.request\n .amount\n .ok_or(ConnectorError::MissingRequiredField {\n field_name: \"amount\",\n })?,\n req,\n ))?;\n let req_obj = netcetera::NetceteraAuthenticationRequest::try_from(&connector_router_data);\n Ok(RequestContent::Json(Box::new(req_obj?)))\n }\n\n fn build_request(\n &self,\n req: &ConnectorAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult, ConnectorError> {\n let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?;\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&ConnectorAuthenticationType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(ConnectorAuthenticationType::get_headers(\n self, req, connectors,\n )?)\n .set_body(ConnectorAuthenticationType::get_request_body(\n self, req, connectors,\n )?)\n .add_certificate(Some(netcetera_auth_type.certificate))\n .add_certificate_key(Some(netcetera_auth_type.private_key))\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &ConnectorAuthenticationRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: netcetera::NetceteraAuthenticationResponse = res\n .response\n .parse_struct(\"NetceteraAuthenticationResponse\")\n .change_context(ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl\n ConnectorIntegration<\n PostAuthentication,\n ConnectorPostAuthenticationRequestData,\n AuthenticationResponseData,\n > for Netcetera\n{\n}\n\nimpl\n ConnectorIntegration<\n PreAuthenticationVersionCall,\n PreAuthNRequestData,\n AuthenticationResponseData,\n > for Netcetera\n{\n}\n\nstatic NETCETERA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Netcetera\",\n description: \"Netcetera authentication provider for comprehensive 3D Secure solutions including certified ACS, Directory Server, and multi-protocol EMV 3DS supports\",\n connector_type: common_enums::HyperswitchConnectorCategory::AuthenticationProvider,\n integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,\n};\n\nimpl ConnectorSpecifications for Netcetera {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&NETCETERA_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n None\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {\n None\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__nordea.rs", "text": "mod requests;\nmod responses;\npub mod transformers;\n\nuse base64::Engine;\nuse common_enums::enums;\nuse common_utils::{\n consts, date_time,\n errors::CustomResult,\n ext_traits::BytesExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n payment_method_data,\n router_data::{AccessToken, AccessTokenAuthenticationResponse, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n AccessTokenAuthentication, CreateOrder, PreProcessing,\n },\n router_request_types::{\n AccessTokenAuthenticationRequestData, AccessTokenRequestData, CreateOrderRequestData,\n PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,\n PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n AccessTokenAuthenticationRouterData, CreateOrderRouterData, PaymentsAuthorizeRouterData,\n PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,\n RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, AuthenticationTokenType, RefreshTokenType, Response},\n webhooks,\n};\nuse lazy_static::lazy_static;\nuse masking::{ExposeInterface, Mask, PeekInterface, Secret};\nuse ring::{\n digest,\n signature::{RsaKeyPair, RSA_PKCS1_SHA256},\n};\nuse transformers::{get_error_data, NordeaAuthType};\nuse url::Url;\n\nuse crate::{\n connectors::nordea::{\n requests::{\n NordeaOAuthExchangeRequest, NordeaOAuthRequest, NordeaPaymentsConfirmRequest,\n NordeaPaymentsRequest, NordeaRouterData,\n },\n responses::{\n NordeaOAuthExchangeResponse, NordeaPaymentsConfirmResponse,\n NordeaPaymentsInitiateResponse,\n },\n },\n constants::headers,\n types::ResponseRouterData,\n utils::{self, RouterData as OtherRouterData},\n};\n\n#[derive(Clone)]\npub struct Nordea {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nstruct SignatureParams<'a> {\n content_type: &'a str,\n host: &'a str,\n path: &'a str,\n payload_digest: Option<&'a str>,\n date: &'a str,\n http_method: Method,\n}\n\nimpl Nordea {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &StringMajorUnitForConnector,\n }\n }\n\n pub fn generate_digest(&self, payload: &[u8]) -> String {\n let payload_digest = digest::digest(&digest::SHA256, payload);\n format!(\"sha-256={}\", consts::BASE64_ENGINE.encode(payload_digest))\n }\n\n pub fn generate_digest_from_request(&self, payload: &RequestContent) -> String {\n let payload_bytes = match payload {\n RequestContent::RawBytes(bytes) => bytes.clone(),\n _ => payload.get_inner_value().expose().as_bytes().to_vec(),\n };\n\n self.generate_digest(&payload_bytes)\n }\n\n fn format_private_key(\n &self,\n private_key_str: &str,\n ) -> CustomResult {\n let key = private_key_str.to_string();\n\n // Check if it already has PEM headers\n let pem_data =\n if key.contains(\"BEGIN\") && key.contains(\"END\") && key.contains(\"PRIVATE KEY\") {\n key\n } else {\n // Remove whitespace and format with 64-char lines\n let cleaned_key = key\n .chars()\n .filter(|c| !c.is_whitespace())\n .collect::();\n\n let formatted_key = cleaned_key\n .chars()\n .collect::>()\n .chunks(64)\n .map(|chunk| chunk.iter().collect::())\n .collect::>()\n .join(\"\\n\");\n\n format!(\n \"-----BEGIN RSA PRIVATE KEY-----\\n{formatted_key}\\n-----END RSA PRIVATE KEY-----\",\n )\n };\n\n Ok(pem_data)\n }\n\n // For non-production environments, signature generation can be skipped and instead `SKIP_SIGNATURE_VALIDATION_FOR_SANDBOX` can be passed.\n fn generate_signature(\n &self,\n auth: &NordeaAuthType,\n signature_params: SignatureParams<'_>,\n ) -> CustomResult {\n const REQUEST_WITHOUT_CONTENT_HEADERS: &str =\n \"(request-target) x-nordea-originating-host x-nordea-originating-date\";\n const REQUEST_WITH_CONTENT_HEADERS: &str = \"(request-target) x-nordea-originating-host x-nordea-originating-date content-type digest\";\n\n let method_string = signature_params.http_method.to_string().to_lowercase();\n let mut normalized_string = format!(\n \"(request-target): {} {}\\nx-nordea-originating-host: {}\\nx-nordea-originating-date: {}\",\n method_string, signature_params.path, signature_params.host, signature_params.date\n );\n\n let headers = if matches!(\n signature_params.http_method,\n Method::Post | Method::Put | Method::Patch\n ) {\n let digest = signature_params.payload_digest.unwrap_or(\"\");\n normalized_string.push_str(&format!(\n \"\\ncontent-type: {}\\ndigest: {}\",\n signature_params.content_type, digest\n ));\n REQUEST_WITH_CONTENT_HEADERS\n } else {\n REQUEST_WITHOUT_CONTENT_HEADERS\n };\n\n let signature_base64 = {\n let private_key_pem =\n self.format_private_key(&auth.eidas_private_key.clone().expose())?;\n\n let private_key_der = pem::parse(&private_key_pem).change_context(\n errors::ConnectorError::InvalidConnectorConfig {\n config: \"eIDAS Private Key\",\n },\n )?;\n let private_key_der_contents = private_key_der.contents();\n let key_pair = RsaKeyPair::from_der(private_key_der_contents).change_context(\n errors::ConnectorError::InvalidConnectorConfig {\n config: \"eIDAS Private Key\",\n },\n )?;\n\n let mut signature = vec![0u8; key_pair.public().modulus_len()];\n key_pair\n .sign(\n &RSA_PKCS1_SHA256,\n &ring::rand::SystemRandom::new(),\n normalized_string.as_bytes(),\n &mut signature,\n )\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n\n consts::BASE64_ENGINE.encode(signature)\n };\n\n Ok(format!(\n r#\"keyId=\"{}\",algorithm=\"rsa-sha256\",headers=\"{}\",signature=\"{}\"\"#,\n auth.client_id.peek(),\n headers,\n signature_base64\n ))\n }\n\n // This helper function correctly serializes a struct into the required\n // non-percent-encoded form URL string.\n fn get_form_urlencoded_payload(\n &self,\n form_data: &T,\n ) -> Result, error_stack::Report> {\n let json_value = serde_json::to_value(form_data)\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n\n let btree_map: std::collections::BTreeMap =\n serde_json::from_value(json_value)\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n\n Ok(btree_map\n .iter()\n .map(|(k, v)| {\n // Remove quotes from string values for proper form encoding\n let value = match v {\n serde_json::Value::String(s) => s.clone(),\n _ => v.to_string(),\n };\n format!(\"{k}={value}\")\n })\n .collect::>()\n .join(\"&\")\n .into_bytes())\n }\n}\n\nimpl api::Payment for Nordea {}\nimpl api::PaymentsCreateOrder for Nordea {}\nimpl api::PaymentSession for Nordea {}\nimpl api::ConnectorAuthenticationToken for Nordea {}\nimpl api::ConnectorAccessToken for Nordea {}\nimpl api::MandateSetup for Nordea {}\nimpl api::PaymentAuthorize for Nordea {}\nimpl api::PaymentSync for Nordea {}\nimpl api::PaymentCapture for Nordea {}\nimpl api::PaymentVoid for Nordea {}\nimpl api::Refund for Nordea {}\nimpl api::RefundExecute for Nordea {}\nimpl api::RefundSync for Nordea {}\nimpl api::PaymentToken for Nordea {}\nimpl api::PaymentsPreProcessing for Nordea {}\n\nimpl ConnectorIntegration\n for Nordea\n{\n}\n\nimpl ConnectorIntegration for Nordea {}\n\nimpl ConnectorCommonExt for Nordea\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let access_token = req\n .access_token\n .clone()\n .ok_or(errors::ConnectorError::FailedToObtainAuthType)?;\n let auth = NordeaAuthType::try_from(&req.connector_auth_type)?;\n let content_type = self.get_content_type().to_string();\n let http_method = self.get_http_method();\n\n // Extract host from base URL\n let nordea_host = Url::parse(self.base_url(connectors))\n .change_context(errors::ConnectorError::RequestEncodingFailed)?\n .host_str()\n .ok_or(errors::ConnectorError::RequestEncodingFailed)?\n .to_string();\n\n let nordea_origin_date = date_time::now_rfc7231_http_date()\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n\n let full_url = self.get_url(req, connectors)?;\n let url_parsed =\n Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;\n let path = url_parsed.path();\n let path_with_query = if let Some(query) = url_parsed.query() {\n format!(\"{path}?{query}\")\n } else {\n path.to_string()\n };\n\n let mut required_headers = vec![\n (\n headers::CONTENT_TYPE.to_string(),\n content_type.clone().into(),\n ),\n (\n headers::AUTHORIZATION.to_string(),\n format!(\"Bearer {}\", access_token.token.peek()).into_masked(),\n ),\n (\n \"X-IBM-Client-ID\".to_string(),\n auth.client_id.clone().expose().into_masked(),\n ),\n (\n \"X-IBM-Client-Secret\".to_string(),\n auth.client_secret.clone().expose().into_masked(),\n ),\n (\n \"X-Nordea-Originating-Date\".to_string(),\n nordea_origin_date.clone().into_masked(),\n ),\n (\n \"X-Nordea-Originating-Host\".to_string(),\n nordea_host.clone().into_masked(),\n ),\n ];\n\n if matches!(http_method, Method::Post | Method::Put | Method::Patch) {\n let nordea_request = self.get_request_body(req, connectors)?;\n\n let sha256_digest = self.generate_digest_from_request(&nordea_request);\n\n // Add Digest header\n required_headers.push((\n \"Digest\".to_string(),\n sha256_digest.to_string().into_masked(),\n ));\n\n let signature = self.generate_signature(\n &auth,\n SignatureParams {\n content_type: &content_type,\n host: &nordea_host,\n path,\n payload_digest: Some(&sha256_digest),\n date: &nordea_origin_date,\n http_method,\n },\n )?;\n\n required_headers.push((\"Signature\".to_string(), signature.into_masked()));\n } else {\n // Generate signature without digest for GET requests\n let signature = self.generate_signature(\n &auth,\n SignatureParams {\n content_type: &content_type,\n host: &nordea_host,\n path: &path_with_query,\n payload_digest: None,\n date: &nordea_origin_date,\n http_method,\n },\n )?;\n\n required_headers.push((\"Signature\".to_string(), signature.into_masked()));\n }\n\n Ok(required_headers)\n }\n}\n\nimpl ConnectorCommon for Nordea {\n fn id(&self) -> &'static str {\n \"nordea\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.nordea.base_url.as_ref()\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: responses::NordeaErrorResponse = res\n .response\n .parse_struct(\"NordeaErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: get_error_data(response.error.as_ref())\n .and_then(|failure| failure.code.clone())\n .unwrap_or(NO_ERROR_CODE.to_string()),\n message: get_error_data(response.error.as_ref())\n .and_then(|failure| failure.description.clone())\n .unwrap_or(NO_ERROR_MESSAGE.to_string()),\n reason: get_error_data(response.error.as_ref())\n .and_then(|failure| failure.failure_type.clone()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_decline_code: None,\n network_advice_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Nordea {}\n\nimpl\n ConnectorIntegration<\n AccessTokenAuthentication,\n AccessTokenAuthenticationRequestData,\n AccessTokenAuthenticationResponse,\n > for Nordea\n{\n fn get_url(\n &self,\n _req: &AccessTokenAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}/personal/v5/authorize\",\n self.base_url(connectors)\n ))\n }\n\n fn get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn get_request_body(\n &self,\n req: &AccessTokenAuthenticationRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = NordeaOAuthRequest::try_from(req)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &AccessTokenAuthenticationRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let auth = NordeaAuthType::try_from(&req.connector_auth_type)?;\n let content_type = self.common_get_content_type().to_string();\n let http_method = Method::Post;\n\n // Extract host from base URL\n let nordea_host = Url::parse(self.base_url(connectors))\n .change_context(errors::ConnectorError::RequestEncodingFailed)?\n .host_str()\n .ok_or(errors::ConnectorError::RequestEncodingFailed)?\n .to_string();\n\n let nordea_origin_date = date_time::now_rfc7231_http_date()\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n\n let full_url = self.get_url(req, connectors)?;\n let url_parsed =\n Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;\n let path = url_parsed.path();\n\n let request_body = self.get_request_body(req, connectors)?;\n\n let mut required_headers = vec![\n (\n headers::CONTENT_TYPE.to_string(),\n content_type.clone().into(),\n ),\n (\n \"X-IBM-Client-ID\".to_string(),\n auth.client_id.clone().expose().into_masked(),\n ),\n (\n \"X-IBM-Client-Secret\".to_string(),\n auth.client_secret.clone().expose().into_masked(),\n ),\n (\n \"X-Nordea-Originating-Date\".to_string(),\n nordea_origin_date.clone().into_masked(),\n ),\n (\n \"X-Nordea-Originating-Host\".to_string(),\n nordea_host.clone().into_masked(),\n ),\n ];\n\n let sha256_digest = self.generate_digest_from_request(&request_body);\n\n // Add Digest header\n required_headers.push((\n \"Digest\".to_string(),\n sha256_digest.to_string().into_masked(),\n ));\n\n let signature = self.generate_signature(\n &auth,\n SignatureParams {\n content_type: &content_type,\n host: &nordea_host,\n path,\n payload_digest: Some(&sha256_digest),\n date: &nordea_origin_date,\n http_method,\n },\n )?;\n\n required_headers.push((\"Signature\".to_string(), signature.into_masked()));\n\n let request = Some(\n RequestBuilder::new()\n .method(http_method)\n .attach_default_headers()\n .headers(required_headers)\n .url(&AuthenticationTokenType::get_url(self, req, connectors)?)\n .set_body(request_body)\n .build(),\n );\n Ok(request)\n }\n\n fn handle_response(\n &self,\n data: &AccessTokenAuthenticationRouterData,\n _event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n // Handle 302 redirect response\n if res.status_code == 302 {\n // Extract Location header\n let headers =\n res.headers\n .as_ref()\n .ok_or(errors::ConnectorError::MissingRequiredField {\n field_name: \"headers\",\n })?;\n let location_header = headers\n .get(\"Location\")\n .map(|value| value.to_str())\n .and_then(|location_value| location_value.ok())\n .ok_or(errors::ConnectorError::ParsingFailed)?;\n\n // Parse auth code from query params\n let url = Url::parse(location_header)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n let code = url\n .query_pairs()\n .find(|(key, _)| key == \"code\")\n .map(|(_, value)| value.to_string())\n .ok_or(errors::ConnectorError::MissingRequiredField { field_name: \"code\" })?;\n\n // Return auth code as \"token\" with short expiry\n Ok(RouterData {\n response: Ok(AccessTokenAuthenticationResponse {\n code: Secret::new(code),\n expires: 60, // 60 seconds - auth code validity\n }),\n ..data.clone()\n })\n } else {\n Err(\n errors::ConnectorError::UnexpectedResponseError(\"Expected 302 redirect\".into())\n .into(),\n )\n }\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn get_url(\n &self,\n _req: &RefreshTokenRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}/personal/v5/authorize/token\",\n self.base_url(connectors)\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RefreshTokenRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = NordeaOAuthExchangeRequest::try_from(req)?;\n let body_bytes = self.get_form_urlencoded_payload(&Box::new(connector_req))?;\n Ok(RequestContent::RawBytes(body_bytes))\n }\n\n fn build_request(\n &self,\n req: &RefreshTokenRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n // For the OAuth token exchange request, we don't have a bearer token yet\n // We're exchanging the auth code for an access token\n let auth = NordeaAuthType::try_from(&req.connector_auth_type)?;\n let content_type = \"application/x-www-form-urlencoded\".to_string();\n let http_method = Method::Post;\n\n // Extract host from base URL\n let nordea_host = Url::parse(self.base_url(connectors))\n .change_context(errors::ConnectorError::RequestEncodingFailed)?\n .host_str()\n .ok_or(errors::ConnectorError::RequestEncodingFailed)?\n .to_string();\n\n let nordea_origin_date = date_time::now_rfc7231_http_date()\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n\n let full_url = self.get_url(req, connectors)?;\n let url_parsed =\n Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;\n let path = url_parsed.path();\n\n let request_body = self.get_request_body(req, connectors)?;\n\n let mut required_headers = vec![\n (\n headers::CONTENT_TYPE.to_string(),\n content_type.clone().into(),\n ),\n (\n \"X-IBM-Client-ID\".to_string(),\n auth.client_id.clone().expose().into_masked(),\n ),\n (\n \"X-IBM-Client-Secret\".to_string(),\n auth.client_secret.clone().expose().into_masked(),\n ),\n (\n \"X-Nordea-Originating-Date\".to_string(),\n nordea_origin_date.clone().into_masked(),\n ),\n (\n \"X-Nordea-Originating-Host\".to_string(),\n nordea_host.clone().into_masked(),\n ),\n ];\n\n let sha256_digest = self.generate_digest_from_request(&request_body);\n\n // Add Digest header\n required_headers.push((\n \"Digest\".to_string(),\n sha256_digest.to_string().into_masked(),\n ));\n\n let signature = self.generate_signature(\n &auth,\n SignatureParams {\n content_type: &content_type,\n host: &nordea_host,\n path,\n payload_digest: Some(&sha256_digest),\n date: &nordea_origin_date,\n http_method,\n },\n )?;\n\n required_headers.push((\"Signature\".to_string(), signature.into_masked()));\n\n let request = Some(\n RequestBuilder::new()\n .method(http_method)\n .attach_default_headers()\n .headers(required_headers)\n .url(&RefreshTokenType::get_url(self, req, connectors)?)\n .set_body(request_body)\n .build(),\n );\n Ok(request)\n }\n\n fn handle_response(\n &self,\n data: &RefreshTokenRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: NordeaOAuthExchangeResponse = res\n .response\n .parse_struct(\"NordeaOAuthExchangeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn build_request(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(\n errors::ConnectorError::NotImplemented(\"Setup Mandate flow for Nordea\".to_string())\n .into(),\n )\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn get_headers(\n &self,\n req: &CreateOrderRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &CreateOrderRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n // Determine the payment endpoint based on country and currency\n let country = req.get_billing_country()?;\n\n let currency = req.request.currency;\n\n let endpoint = match (country, currency) {\n (api_models::enums::CountryAlpha2::FI, api_models::enums::Currency::EUR) => {\n \"/personal/v5/payments/sepa-credit-transfers\"\n }\n (api_models::enums::CountryAlpha2::DK, api_models::enums::Currency::DKK) => {\n \"/personal/v5/payments/domestic-credit-transfers\"\n }\n (\n api_models::enums::CountryAlpha2::FI\n | api_models::enums::CountryAlpha2::DK\n | api_models::enums::CountryAlpha2::SE\n | api_models::enums::CountryAlpha2::NO,\n _,\n ) => \"/personal/v5/payments/cross-border-credit-transfers\",\n _ => {\n return Err(errors::ConnectorError::NotSupported {\n message: format!(\"Country {country:?} is not supported by Nordea\"),\n connector: \"Nordea\",\n }\n .into())\n }\n };\n\n Ok(format!(\"{}{}\", self.base_url(connectors), endpoint))\n }\n\n fn get_request_body(\n &self,\n req: &CreateOrderRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let minor_amount = req.request.minor_amount;\n let currency = req.request.currency;\n\n let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?;\n let connector_router_data = NordeaRouterData::from((amount, req));\n let connector_req = NordeaPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &CreateOrderRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::CreateOrderType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::CreateOrderType::get_headers(self, req, connectors)?)\n .set_body(types::CreateOrderType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &CreateOrderRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: NordeaPaymentsInitiateResponse = res\n .response\n .parse_struct(\"NordeaPaymentsInitiateResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Nordea\n{\n fn get_headers(\n &self,\n req: &PaymentsPreProcessingRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsPreProcessingRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n // Determine the payment endpoint based on country and currency\n let country = req.get_billing_country()?;\n\n let currency =\n req.request\n .currency\n .ok_or(errors::ConnectorError::MissingRequiredField {\n field_name: \"currency\",\n })?;\n\n let endpoint = match (country, currency) {\n (api_models::enums::CountryAlpha2::FI, api_models::enums::Currency::EUR) => {\n \"/personal/v5/payments/sepa-credit-transfers\"\n }\n (api_models::enums::CountryAlpha2::DK, api_models::enums::Currency::DKK) => {\n \"/personal/v5/payments/domestic-credit-transfers\"\n }\n (\n api_models::enums::CountryAlpha2::FI\n | api_models::enums::CountryAlpha2::DK\n | api_models::enums::CountryAlpha2::SE\n | api_models::enums::CountryAlpha2::NO,\n _,\n ) => \"/personal/v5/payments/cross-border-credit-transfers\",\n _ => {\n return Err(errors::ConnectorError::NotSupported {\n message: format!(\"Country {country:?} is not supported by Nordea\"),\n connector: \"Nordea\",\n }\n .into())\n }\n };\n\n Ok(format!(\"{}{}\", self.base_url(connectors), endpoint))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsPreProcessingRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let minor_amount = req.request.minor_amount;\n let currency =\n req.request\n .currency\n .ok_or(errors::ConnectorError::MissingRequiredField {\n field_name: \"currency\",\n })?;\n\n let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?;\n let connector_router_data = NordeaRouterData::from((amount, req));\n let connector_req = NordeaPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsPreProcessingRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsPreProcessingType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsPreProcessingType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsPreProcessingType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsPreProcessingRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: NordeaPaymentsInitiateResponse = res\n .response\n .parse_struct(\"NordeaPaymentsInitiateResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_http_method(&self) -> Method {\n Method::Put\n }\n\n fn get_url(\n &self,\n _req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}{}\",\n self.base_url(_connectors),\n \"/personal/v5/payments\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = NordeaRouterData::from((amount, req));\n let connector_req = NordeaPaymentsConfirmRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(types::PaymentsAuthorizeType::get_http_method(self))\n .url(&types::PaymentsAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: NordeaPaymentsConfirmResponse = res\n .response\n .parse_struct(\"NordeaPaymentsConfirmResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_http_method(&self) -> Method {\n Method::Get\n }\n\n fn get_url(\n &self,\n req: &PaymentsSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let id = req.request.connector_transaction_id.clone();\n let connector_transaction_id = id\n .get_connector_transaction_id()\n .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;\n\n Ok(format!(\n \"{}{}{}\",\n self.base_url(_connectors),\n \"/personal/v5/payments/\",\n connector_transaction_id\n ))\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(types::PaymentsSyncType::get_http_method(self))\n .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: NordeaPaymentsInitiateResponse = res\n .response\n .parse_struct(\"NordeaPaymentsSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn build_request(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(errors::ConnectorError::NotSupported {\n message: \"Capture\".to_string(),\n connector: \"Nordea\",\n }\n .into())\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn build_request(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(errors::ConnectorError::NotSupported {\n message: \"Payments Cancel\".to_string(),\n connector: \"Nordea\",\n }\n .into())\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n fn build_request(\n &self,\n _req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(errors::ConnectorError::NotSupported {\n message: \"Personal API Refunds flow\".to_string(),\n connector: \"Nordea\",\n }\n .into())\n }\n}\n\nimpl ConnectorIntegration for Nordea {\n // Default impl gets executed\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Nordea {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nlazy_static! {\n static ref NORDEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name:\n \"Nordea\",\n description:\n \"Nordea is one of the leading financial services group in the Nordics and the preferred choice for millions across the region.\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: common_enums::ConnectorIntegrationStatus::Beta,\n };\n static ref NORDEA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {\n let nordea_supported_capture_methods = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let mut nordea_supported_payment_methods = SupportedPaymentMethods::new();\n\n nordea_supported_payment_methods.add(\n enums::PaymentMethod::BankDebit,\n enums::PaymentMethodType::Sepa,\n PaymentMethodDetails {\n mandates: common_enums::FeatureStatus::NotSupported,\n // Supported only in corporate API (corporate accounts)\n refunds: common_enums::FeatureStatus::NotSupported,\n supported_capture_methods: nordea_supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n nordea_supported_payment_methods\n };\n static ref NORDEA_SUPPORTED_WEBHOOK_FLOWS: Vec = Vec::new();\n}\n\nimpl ConnectorSpecifications for Nordea {\n fn is_order_create_flow_required(&self, current_flow: api::CurrentFlowInfo<'_>) -> bool {\n match current_flow {\n api::CurrentFlowInfo::Authorize {\n auth_type: _,\n request_data,\n } => matches!(\n &request_data.payment_method_data,\n payment_method_data::PaymentMethodData::BankDebit(_)\n ),\n api::CurrentFlowInfo::CompleteAuthorize { .. } => false,\n api::CurrentFlowInfo::SetupMandate { .. } => false,\n }\n }\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&*NORDEA_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*NORDEA_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&*NORDEA_SUPPORTED_WEBHOOK_FLOWS)\n }\n\n fn authentication_token_for_token_creation(&self) -> bool {\n // Nordea requires authentication token for access token creation\n true\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__payme__transformers.rs", "text": "use std::collections::HashMap;\n\nuse api_models::enums::{AuthenticationType, PaymentMethod};\nuse common_enums::enums;\nuse common_utils::{\n ext_traits::OptionExt,\n pii,\n types::{MinorUnit, StringMajorUnit},\n};\nuse error_stack::ResultExt;\nuse hyperswitch_domain_models::{\n payment_method_data::{PaymentMethodData, WalletData},\n router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},\n router_flow_types::{Execute, Void},\n router_request_types::{\n CreateOrderRequestData, PaymentsCancelData, PaymentsPreProcessingData, ResponseId,\n },\n router_response_types::{\n MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm,\n RefundsResponseData,\n },\n types::{\n CreateOrderRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,\n PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,\n PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,\n RefundsRouterData, TokenizationRouterData,\n },\n};\nuse hyperswitch_interfaces::{consts, errors};\nuse masking::{ExposeInterface, Secret};\nuse serde::{Deserialize, Serialize};\nuse url::Url;\n\nuse crate::{\n types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},\n unimplemented_payment_method,\n utils::{\n self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,\n PaymentsCancelRequestData, PaymentsCompleteAuthorizeRequestData,\n PaymentsPreProcessingRequestData, PaymentsSyncRequestData, RouterData as OtherRouterData,\n },\n};\n\nconst LANGUAGE: &str = \"en\";\n\n#[derive(Debug, Serialize)]\npub struct PaymeRouterData {\n pub amount: MinorUnit,\n pub router_data: T,\n}\n\nimpl TryFrom<(MinorUnit, T)> for PaymeRouterData {\n type Error = error_stack::Report;\n fn try_from((amount, item): (MinorUnit, T)) -> Result {\n Ok(Self {\n amount,\n router_data: item,\n })\n }\n}\n\n#[derive(Debug, Serialize)]\npub struct PayRequest {\n buyer_name: Secret,\n buyer_email: pii::Email,\n payme_sale_id: String,\n #[serde(flatten)]\n card: PaymeCard,\n language: String,\n}\n\n#[derive(Debug, Serialize)]\npub struct MandateRequest {\n currency: enums::Currency,\n sale_price: MinorUnit,\n transaction_id: String,\n product_name: String,\n sale_return_url: String,\n seller_payme_id: Secret,\n sale_callback_url: String,\n buyer_key: Secret,\n language: String,\n}\n\n#[derive(Debug, Serialize)]\npub struct Pay3dsRequest {\n buyer_name: Secret,\n buyer_email: pii::Email,\n buyer_key: Secret,\n payme_sale_id: String,\n meta_data_jwt: Secret,\n}\n\n#[derive(Debug, Serialize)]\n#[serde(untagged)]\npub enum PaymePaymentRequest {\n MandateRequest(MandateRequest),\n PayRequest(PayRequest),\n}\n\n#[derive(Debug, Serialize)]\npub struct PaymeQuerySaleRequest {\n sale_payme_id: String,\n seller_payme_id: Secret,\n}\n\n#[derive(Debug, Serialize)]\npub struct PaymeQueryTransactionRequest {\n payme_transaction_id: String,\n seller_payme_id: Secret,\n}\n\n#[derive(Debug, Serialize)]\npub struct PaymeCard {\n credit_card_cvv: Secret,\n credit_card_exp: Secret,\n credit_card_number: cards::CardNumber,\n}\n\n#[derive(Debug, Serialize)]\npub struct CaptureBuyerRequest {\n seller_payme_id: Secret,\n #[serde(flatten)]\n card: PaymeCard,\n}\n\n#[derive(Debug, Deserialize, Serialize)]\npub struct CaptureBuyerResponse {\n buyer_key: Secret,\n}\n\n#[derive(Debug, Serialize)]\npub struct GenerateSaleRequest {\n currency: enums::Currency,\n sale_type: SaleType,\n sale_price: MinorUnit,\n transaction_id: String,\n product_name: String,\n sale_return_url: String,\n seller_payme_id: Secret,\n sale_callback_url: String,\n sale_payment_method: SalePaymentMethod,\n services: Option,\n language: String,\n}\n\n#[derive(Debug, Serialize)]\npub struct ThreeDs {\n name: ThreeDsType,\n settings: ThreeDsSettings,\n}\n\n#[derive(Debug, Serialize)]\npub enum ThreeDsType {\n #[serde(rename = \"3D Secure\")]\n ThreeDs,\n}\n\n#[derive(Debug, Serialize)]\npub struct ThreeDsSettings {\n active: bool,\n}\n\n#[derive(Debug, Deserialize, Serialize)]\npub struct GenerateSaleResponse {\n payme_sale_id: String,\n}\n\nimpl TryFrom>\n for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData,\n ) -> Result {\n match item.response {\n // To handle webhook response\n PaymePaymentsResponse::PaymePaySaleResponse(response) => {\n Self::try_from(ResponseRouterData {\n response,\n data: item.data,\n http_code: item.http_code,\n })\n }\n // To handle PSync response\n PaymePaymentsResponse::SaleQueryResponse(response) => {\n Self::try_from(ResponseRouterData {\n response,\n data: item.data,\n http_code: item.http_code,\n })\n }\n }\n }\n}\n\nimpl TryFrom>\n for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData,\n ) -> Result {\n let status = enums::AttemptStatus::from(item.response.sale_status.clone());\n let response = if utils::is_payment_failure(status) {\n // To populate error message in case of failure\n Err(get_pay_sale_error_response((\n &item.response,\n item.http_code,\n )))\n } else {\n Ok(PaymentsResponseData::try_from(&item.response)?)\n };\n Ok(Self {\n status,\n response,\n ..item.data\n })\n }\n}\n\nfn get_pay_sale_error_response(\n (pay_sale_response, http_code): (&PaymePaySaleResponse, u16),\n) -> ErrorResponse {\n let code = pay_sale_response\n .status_error_code\n .map(|error_code| error_code.to_string())\n .unwrap_or(consts::NO_ERROR_CODE.to_string());\n ErrorResponse {\n code,\n message: pay_sale_response\n .status_error_details\n .clone()\n .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),\n reason: pay_sale_response.status_error_details.to_owned(),\n status_code: http_code,\n attempt_status: None,\n connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()),\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n }\n}\n\nimpl TryFrom<&PaymePaySaleResponse> for PaymentsResponseData {\n type Error = error_stack::Report;\n fn try_from(value: &PaymePaySaleResponse) -> Result {\n let redirection_data = match value.sale_3ds {\n Some(true) => value.redirect_url.clone().map(|url| RedirectForm::Form {\n endpoint: url.to_string(),\n method: common_utils::request::Method::Get,\n form_fields: HashMap::::new(),\n }),\n _ => None,\n };\n Ok(Self::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(value.payme_sale_id.clone()),\n redirection_data: Box::new(redirection_data),\n mandate_reference: Box::new(value.buyer_key.clone().map(|buyer_key| {\n MandateReference {\n connector_mandate_id: Some(buyer_key.expose()),\n payment_method_id: None,\n mandate_metadata: None,\n connector_mandate_request_reference_id: None,\n }\n })),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n })\n }\n}\n\nimpl TryFrom>\n for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData,\n ) -> Result {\n // Only one element would be present since we are passing one transaction id in the PSync request\n let transaction_response = item\n .response\n .items\n .first()\n .cloned()\n .ok_or(errors::ConnectorError::ResponseHandlingFailed)?;\n let status = enums::AttemptStatus::from(transaction_response.sale_status.clone());\n let response = if utils::is_payment_failure(status) {\n // To populate error message in case of failure\n Err(get_sale_query_error_response((\n &transaction_response,\n item.http_code,\n )))\n } else {\n Ok(PaymentsResponseData::from(&transaction_response))\n };\n Ok(Self {\n status,\n response,\n ..item.data\n })\n }\n}\n\nfn get_sale_query_error_response(\n (sale_query_response, http_code): (&SaleQuery, u16),\n) -> ErrorResponse {\n ErrorResponse {\n code: sale_query_response\n .sale_error_code\n .clone()\n .unwrap_or(consts::NO_ERROR_CODE.to_string()),\n message: sale_query_response\n .sale_error_text\n .clone()\n .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),\n reason: sale_query_response.sale_error_text.clone(),\n status_code: http_code,\n attempt_status: None,\n connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()),\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n }\n}\n\nimpl From<&SaleQuery> for PaymentsResponseData {\n fn from(value: &SaleQuery) -> Self {\n Self::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(value.sale_payme_id.clone()),\n redirection_data: Box::new(None),\n // mandate reference will be updated with webhooks only. That has been handled with PaymePaySaleResponse struct\n mandate_reference: Box::new(None),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n }\n }\n}\n\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"lowercase\")]\npub enum SaleType {\n Sale,\n Authorize,\n Token,\n}\n\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"kebab-case\")]\npub enum SalePaymentMethod {\n CreditCard,\n ApplePay,\n}\n\nimpl TryFrom<&PaymeRouterData<&CreateOrderRouterData>> for GenerateSaleRequest {\n type Error = error_stack::Report;\n fn try_from(item: &PaymeRouterData<&CreateOrderRouterData>) -> Result {\n let sale_type = SaleType::try_from(item.router_data)?;\n let seller_payme_id =\n PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;\n let order_details = item\n .router_data\n .request\n .order_details\n .clone()\n .get_required_value(\"order_details\")\n .change_context(errors::ConnectorError::MissingRequiredField {\n field_name: \"order_details\",\n })?;\n let services = get_services(item.router_data.auth_type);\n let product_name = order_details\n .first()\n .ok_or_else(utils::missing_field_err(\"order_details\"))?\n .product_name\n .clone();\n let pmd = item\n .router_data\n .request\n .payment_method_data\n .to_owned()\n .ok_or_else(utils::missing_field_err(\"payment_method_data\"))?;\n let sale_return_url = item\n .router_data\n .request\n .router_return_url\n .clone()\n .get_required_value(\"router_return_url\")\n .change_context(errors::ConnectorError::MissingRequiredField {\n field_name: \"router_return_url\",\n })?;\n let sale_callback_url = item\n .router_data\n .request\n .webhook_url\n .clone()\n .get_required_value(\"webhook_url\")\n .change_context(errors::ConnectorError::MissingRequiredField {\n field_name: \"webhook_url\",\n })?;\n Ok(Self {\n seller_payme_id,\n sale_price: item.amount.to_owned(),\n currency: item.router_data.request.currency,\n product_name,\n sale_payment_method: SalePaymentMethod::try_from(&pmd)?,\n sale_type,\n transaction_id: item.router_data.payment_id.clone(),\n sale_return_url,\n sale_callback_url,\n language: LANGUAGE.to_string(),\n services,\n })\n }\n}\n\nimpl TryFrom<&PaymeRouterData<&PaymentsPreProcessingRouterData>> for GenerateSaleRequest {\n type Error = error_stack::Report;\n fn try_from(\n item: &PaymeRouterData<&PaymentsPreProcessingRouterData>,\n ) -> Result {\n let sale_type = SaleType::try_from(item.router_data)?;\n let seller_payme_id =\n PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;\n let order_details = item.router_data.request.get_order_details()?;\n let services = get_services(item.router_data.auth_type);\n let product_name = order_details\n .first()\n .ok_or_else(utils::missing_field_err(\"order_details\"))?\n .product_name\n .clone();\n let pmd = item\n .router_data\n .request\n .payment_method_data\n .to_owned()\n .ok_or_else(utils::missing_field_err(\"payment_method_data\"))?;\n Ok(Self {\n seller_payme_id,\n sale_price: item.amount.to_owned(),\n currency: item.router_data.request.get_currency()?,\n product_name,\n sale_payment_method: SalePaymentMethod::try_from(&pmd)?,\n sale_type,\n transaction_id: item.router_data.payment_id.clone(),\n sale_return_url: item.router_data.request.get_router_return_url()?,\n sale_callback_url: item.router_data.request.get_webhook_url()?,\n language: LANGUAGE.to_string(),\n services,\n })\n }\n}\n\nimpl TryFrom<&PaymentMethodData> for SalePaymentMethod {\n type Error = error_stack::Report;\n fn try_from(item: &PaymentMethodData) -> Result {\n match item {\n PaymentMethodData::Card(_) => Ok(Self::CreditCard),\n PaymentMethodData::Wallet(wallet_data) => match wallet_data {\n WalletData::ApplePayThirdPartySdk(_) => Ok(Self::ApplePay),\n WalletData::AliPayQr(_)\n | WalletData::AliPayRedirect(_)\n | WalletData::BluecodeRedirect {}\n | WalletData::AliPayHkRedirect(_)\n | WalletData::AmazonPay(_)\n | WalletData::AmazonPayRedirect(_)\n | WalletData::Paysera(_)\n | WalletData::Skrill(_)\n | WalletData::MomoRedirect(_)\n | WalletData::KakaoPayRedirect(_)\n | WalletData::GoPayRedirect(_)\n | WalletData::GcashRedirect(_)\n | WalletData::ApplePayRedirect(_)\n | WalletData::DanaRedirect {}\n | WalletData::GooglePay(_)\n | WalletData::GooglePayRedirect(_)\n | WalletData::GooglePayThirdPartySdk(_)\n | WalletData::MbWayRedirect(_)\n | WalletData::MobilePayRedirect(_)\n | WalletData::PaypalRedirect(_)\n | WalletData::PaypalSdk(_)\n | WalletData::Paze(_)\n | WalletData::SamsungPay(_)\n | WalletData::TwintRedirect {}\n | WalletData::VippsRedirect {}\n | WalletData::TouchNGoRedirect(_)\n | WalletData::WeChatPayRedirect(_)\n | WalletData::WeChatPayQr(_)\n | WalletData::CashappQr(_)\n | WalletData::ApplePay(_)\n | WalletData::SwishQr(_)\n | WalletData::Mifinity(_)\n | WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotSupported {\n message: \"Wallet\".to_string(),\n connector: \"payme\",\n }\n .into()),\n },\n PaymentMethodData::PayLater(_)\n | PaymentMethodData::BankRedirect(_)\n | PaymentMethodData::BankDebit(_)\n | PaymentMethodData::BankTransfer(_)\n | PaymentMethodData::Crypto(_)\n | PaymentMethodData::MandatePayment\n | PaymentMethodData::Reward\n | PaymentMethodData::RealTimePayment(_)\n | PaymentMethodData::MobilePayment(_)\n | PaymentMethodData::GiftCard(_)\n | PaymentMethodData::CardRedirect(_)\n | PaymentMethodData::Upi(_)\n | PaymentMethodData::Voucher(_)\n | PaymentMethodData::OpenBanking(_)\n | PaymentMethodData::CardToken(_)\n | PaymentMethodData::NetworkToken(_)\n | PaymentMethodData::CardDetailsForNetworkTransactionId(_)\n | PaymentMethodData::CardWithLimitedDetails(_)\n | PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)\n | PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {\n Err(errors::ConnectorError::NotImplemented(\"Payment methods\".to_string()).into())\n }\n }\n }\n}\n\nimpl TryFrom<&PaymeRouterData<&PaymentsAuthorizeRouterData>> for PaymePaymentRequest {\n type Error = error_stack::Report;\n fn try_from(\n value: &PaymeRouterData<&PaymentsAuthorizeRouterData>,\n ) -> Result {\n let payme_request = if value.router_data.request.mandate_id.is_some() {\n Self::MandateRequest(MandateRequest::try_from(value)?)\n } else {\n Self::PayRequest(PayRequest::try_from(value.router_data)?)\n };\n Ok(payme_request)\n }\n}\n\nimpl TryFrom<&PaymentsSyncRouterData> for PaymeQuerySaleRequest {\n type Error = error_stack::Report;\n fn try_from(value: &PaymentsSyncRouterData) -> Result {\n let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;\n Ok(Self {\n sale_payme_id: value.request.get_connector_transaction_id()?,\n seller_payme_id,\n })\n }\n}\n\nimpl TryFrom<&RefundSyncRouterData> for PaymeQueryTransactionRequest {\n type Error = error_stack::Report;\n fn try_from(value: &RefundSyncRouterData) -> Result {\n let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;\n Ok(Self {\n payme_transaction_id: value\n .request\n .connector_refund_id\n .clone()\n .ok_or(errors::ConnectorError::MissingConnectorRefundID)?,\n seller_payme_id,\n })\n }\n}\n\nimpl\n utils::ForeignTryFrom<(\n ResponseRouterData<\n F,\n GenerateSaleResponse,\n PaymentsPreProcessingData,\n PaymentsResponseData,\n >,\n StringMajorUnit,\n )> for RouterData\n{\n type Error = error_stack::Report;\n fn foreign_try_from(\n (item, apple_pay_amount): (\n ResponseRouterData<\n F,\n GenerateSaleResponse,\n PaymentsPreProcessingData,\n PaymentsResponseData,\n >,\n StringMajorUnit,\n ),\n ) -> Result {\n match item.data.payment_method {\n PaymentMethod::Card => {\n match item.data.auth_type {\n AuthenticationType::NoThreeDs => {\n Ok(Self {\n // We don't get any status from payme, so defaulting it to pending\n // then move to authorize flow\n status: enums::AttemptStatus::Pending,\n preprocessing_id: Some(item.response.payme_sale_id.to_owned()),\n response: Ok(PaymentsResponseData::PreProcessingResponse {\n pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(\n item.response.payme_sale_id,\n ),\n connector_metadata: None,\n session_token: None,\n connector_response_reference_id: None,\n }),\n ..item.data\n })\n }\n AuthenticationType::ThreeDs => Ok(Self {\n // We don't go to authorize flow in 3ds,\n // Response is send directly after preprocessing flow\n // redirection data is send to run script along\n // status is made authentication_pending to show redirection\n status: enums::AttemptStatus::AuthenticationPending,\n preprocessing_id: Some(item.response.payme_sale_id.to_owned()),\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(\n item.response.payme_sale_id.to_owned(),\n ),\n redirection_data: Box::new(Some(RedirectForm::Payme)),\n mandate_reference: Box::new(None),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n }),\n ..item.data\n }),\n }\n }\n _ => {\n let currency_code = item.data.request.get_currency()?;\n let pmd = item.data.request.payment_method_data.to_owned();\n let payme_auth_type = PaymeAuthType::try_from(&item.data.connector_auth_type)?;\n\n let session_token = match pmd {\n Some(PaymentMethodData::Wallet(WalletData::ApplePayThirdPartySdk(\n _,\n ))) => Some(api_models::payments::SessionToken::ApplePay(Box::new(\n api_models::payments::ApplepaySessionTokenResponse {\n session_token_data: Some(\n api_models::payments::ApplePaySessionResponse::NoSessionResponse(api_models::payments::NullObject),\n ),\n payment_request_data: Some(\n api_models::payments::ApplePayPaymentRequest {\n country_code: item.data.get_billing_country()?,\n currency_code,\n total: api_models::payments::AmountInfo {\n label: \"Apple Pay\".to_string(),\n total_type: None,\n amount: apple_pay_amount,\n },\n merchant_capabilities: None,\n supported_networks: None,\n merchant_identifier: None,\n required_billing_contact_fields: None,\n required_shipping_contact_fields: None,\n recurring_payment_request: None,\n },\n ),\n connector: \"payme\".to_string(),\n delayed_session_token: true,\n sdk_next_action: api_models::payments::SdkNextAction {\n next_action: api_models::payments::NextActionCall::Sync,\n },\n connector_reference_id: Some(item.response.payme_sale_id.to_owned()),\n connector_sdk_public_key: Some(\n payme_auth_type.payme_public_key.expose(),\n ),\n connector_merchant_id: payme_auth_type\n .payme_merchant_id\n .map(|mid| mid.expose()),\n },\n ))),\n _ => None,\n };\n Ok(Self {\n // We don't get any status from payme, so defaulting it to pending\n status: enums::AttemptStatus::Pending,\n preprocessing_id: Some(item.response.payme_sale_id.to_owned()),\n response: Ok(PaymentsResponseData::PreProcessingResponse {\n pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(\n item.response.payme_sale_id,\n ),\n connector_metadata: None,\n session_token,\n connector_response_reference_id: None,\n }),\n ..item.data\n })\n }\n }\n }\n}\n\nimpl\n utils::ForeignTryFrom<(\n ResponseRouterData,\n StringMajorUnit,\n )> for RouterData\n{\n type Error = error_stack::Report;\n fn foreign_try_from(\n (item, apple_pay_amount): (\n ResponseRouterData<\n F,\n GenerateSaleResponse,\n CreateOrderRequestData,\n PaymentsResponseData,\n >,\n StringMajorUnit,\n ),\n ) -> Result {\n match item.data.payment_method {\n PaymentMethod::Card => {\n match item.data.auth_type {\n AuthenticationType::NoThreeDs => {\n Ok(Self {\n // We don't get any status from payme, so defaulting it to pending\n // then move to authorize flow\n status: enums::AttemptStatus::Pending,\n preprocessing_id: Some(item.response.payme_sale_id.to_owned()),\n response: Ok(PaymentsResponseData::PreProcessingResponse {\n pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(\n item.response.payme_sale_id,\n ),\n connector_metadata: None,\n session_token: None,\n connector_response_reference_id: None,\n }),\n ..item.data\n })\n }\n AuthenticationType::ThreeDs => Ok(Self {\n // We don't go to authorize flow in 3ds,\n // Response is send directly after preprocessing flow\n // redirection data is send to run script along\n // status is made authentication_pending to show redirection\n status: enums::AttemptStatus::AuthenticationPending,\n preprocessing_id: Some(item.response.payme_sale_id.to_owned()),\n response: Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(\n item.response.payme_sale_id.to_owned(),\n ),\n redirection_data: Box::new(Some(RedirectForm::Payme)),\n mandate_reference: Box::new(None),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n }),\n ..item.data\n }),\n }\n }\n _ => {\n let currency_code = item.data.request.currency;\n let pmd = item.data.request.payment_method_data.to_owned();\n let payme_auth_type = PaymeAuthType::try_from(&item.data.connector_auth_type)?;\n\n let session_token = match pmd {\n Some(PaymentMethodData::Wallet(WalletData::ApplePayThirdPartySdk(\n _,\n ))) => Some(api_models::payments::SessionToken::ApplePay(Box::new(\n api_models::payments::ApplepaySessionTokenResponse {\n session_token_data: Some(\n api_models::payments::ApplePaySessionResponse::NoSessionResponse(api_models::payments::NullObject),\n ),\n payment_request_data: Some(\n api_models::payments::ApplePayPaymentRequest {\n country_code: item.data.get_billing_country()?,\n currency_code,\n total: api_models::payments::AmountInfo {\n label: \"Apple Pay\".to_string(),\n total_type: None,\n amount: apple_pay_amount,\n },\n merchant_capabilities: None,\n supported_networks: None,\n merchant_identifier: None,\n required_billing_contact_fields: None,\n required_shipping_contact_fields: None,\n recurring_payment_request: None,\n },\n ),\n connector: \"payme\".to_string(),\n delayed_session_token: true,\n sdk_next_action: api_models::payments::SdkNextAction {\n next_action: api_models::payments::NextActionCall::Sync,\n },\n connector_reference_id: Some(item.response.payme_sale_id.to_owned()),\n connector_sdk_public_key: Some(\n payme_auth_type.payme_public_key.expose(),\n ),\n connector_merchant_id: payme_auth_type\n .payme_merchant_id\n .map(|mid| mid.expose()),\n },\n ))),\n _ => None,\n };\n Ok(Self {\n // We don't get any status from payme, so defaulting it to pending\n status: enums::AttemptStatus::Pending,\n preprocessing_id: Some(item.response.payme_sale_id.to_owned()),\n response: Ok(PaymentsResponseData::PreProcessingResponse {\n pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(\n item.response.payme_sale_id,\n ),\n connector_metadata: None,\n session_token,\n connector_response_reference_id: None,\n }),\n ..item.data\n })\n }\n }\n }\n}\n\nimpl TryFrom<&PaymeRouterData<&PaymentsAuthorizeRouterData>> for MandateRequest {\n type Error = error_stack::Report;\n fn try_from(item: &PaymeRouterData<&PaymentsAuthorizeRouterData>) -> Result {\n let seller_payme_id =\n PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;\n let order_details = item.router_data.request.get_order_details()?;\n let product_name = order_details\n .first()\n .ok_or_else(utils::missing_field_err(\"order_details\"))?\n .product_name\n .clone();\n Ok(Self {\n currency: item.router_data.request.currency,\n sale_price: item.amount.to_owned(),\n transaction_id: item.router_data.payment_id.clone(),\n product_name,\n sale_return_url: item.router_data.request.get_router_return_url()?,\n seller_payme_id,\n sale_callback_url: item.router_data.request.get_webhook_url()?,\n buyer_key: Secret::new(item.router_data.request.get_connector_mandate_id()?),\n language: LANGUAGE.to_string(),\n })\n }\n}\n\nimpl TryFrom<&PaymentsAuthorizeRouterData> for PayRequest {\n type Error = error_stack::Report;\n fn try_from(item: &PaymentsAuthorizeRouterData) -> Result {\n match item.request.payment_method_data.clone() {\n PaymentMethodData::Card(req_card) => {\n let card = PaymeCard {\n credit_card_cvv: req_card.card_cvc.clone(),\n credit_card_exp: req_card\n .get_card_expiry_month_year_2_digit_with_delimiter(\"\".to_string())?,\n credit_card_number: req_card.card_number,\n };\n let buyer_email = item.request.get_email()?;\n let buyer_name = item.get_billing_address()?.get_full_name()?;\n let payme_sale_id = item.preprocessing_id.to_owned().ok_or(\n errors::ConnectorError::MissingConnectorRelatedTransactionID {\n id: \"payme_sale_id\".to_string(),\n },\n )?;\n Ok(Self {\n card,\n buyer_email,\n buyer_name,\n payme_sale_id,\n language: LANGUAGE.to_string(),\n })\n }\n PaymentMethodData::CardRedirect(_)\n | PaymentMethodData::Wallet(_)\n | PaymentMethodData::PayLater(_)\n | PaymentMethodData::BankRedirect(_)\n | PaymentMethodData::BankDebit(_)\n | PaymentMethodData::BankTransfer(_)\n | PaymentMethodData::Crypto(_)\n | PaymentMethodData::MandatePayment\n | PaymentMethodData::Reward\n | PaymentMethodData::RealTimePayment(_)\n | PaymentMethodData::MobilePayment(_)\n | PaymentMethodData::Upi(_)\n | PaymentMethodData::Voucher(_)\n | PaymentMethodData::GiftCard(_)\n | PaymentMethodData::OpenBanking(_)\n | PaymentMethodData::CardToken(_)\n | PaymentMethodData::NetworkToken(_)\n | PaymentMethodData::CardDetailsForNetworkTransactionId(_)\n | PaymentMethodData::CardWithLimitedDetails(_)\n | PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)\n | PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {\n Err(errors::ConnectorError::NotImplemented(\n utils::get_unimplemented_payment_method_error_message(\"payme\"),\n ))?\n }\n }\n }\n}\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct PaymeRedirectResponseData {\n meta_data: String,\n}\n\nimpl TryFrom<&PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {\n type Error = error_stack::Report;\n fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result {\n match item.request.payment_method_data.clone() {\n Some(PaymentMethodData::Card(_)) => {\n let buyer_email = item.request.get_email()?;\n let buyer_name = item.get_billing_address()?.get_full_name()?;\n\n let payload_data = item.request.get_redirect_response_payload()?.expose();\n\n let jwt_data: PaymeRedirectResponseData = serde_json::from_value(payload_data)\n .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {\n field_name: \"meta_data_jwt\",\n })?;\n\n let payme_sale_id = item\n .request\n .connector_transaction_id\n .clone()\n .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;\n let pm_token = item.get_payment_method_token()?;\n let buyer_key =\n match pm_token {\n PaymentMethodToken::Token(token) => token,\n PaymentMethodToken::ApplePayDecrypt(_) => Err(\n unimplemented_payment_method!(\"Apple Pay\", \"Simplified\", \"Payme\"),\n )?,\n PaymentMethodToken::PazeDecrypt(_) => {\n Err(unimplemented_payment_method!(\"Paze\", \"Payme\"))?\n }\n PaymentMethodToken::GooglePayDecrypt(_) => {\n Err(unimplemented_payment_method!(\"Google Pay\", \"Payme\"))?\n }\n };\n Ok(Self {\n buyer_email,\n buyer_key,\n buyer_name,\n payme_sale_id,\n meta_data_jwt: Secret::new(jwt_data.meta_data),\n })\n }\n Some(PaymentMethodData::CardRedirect(_))\n | Some(PaymentMethodData::Wallet(_))\n | Some(PaymentMethodData::PayLater(_))\n | Some(PaymentMethodData::BankRedirect(_))\n | Some(PaymentMethodData::BankDebit(_))\n | Some(PaymentMethodData::BankTransfer(_))\n | Some(PaymentMethodData::Crypto(_))\n | Some(PaymentMethodData::MandatePayment)\n | Some(PaymentMethodData::Reward)\n | Some(PaymentMethodData::RealTimePayment(_))\n | Some(PaymentMethodData::MobilePayment(_))\n | Some(PaymentMethodData::Upi(_))\n | Some(PaymentMethodData::Voucher(_))\n | Some(PaymentMethodData::GiftCard(_))\n | Some(PaymentMethodData::OpenBanking(_))\n | Some(PaymentMethodData::CardToken(_))\n | Some(PaymentMethodData::NetworkToken(_))\n | Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))\n | Some(PaymentMethodData::CardWithLimitedDetails(_))\n | Some(PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_))\n | Some(PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_))\n | None => {\n Err(errors::ConnectorError::NotImplemented(\"Tokenize Flow\".to_string()).into())\n }\n }\n }\n}\n\nimpl TryFrom<&TokenizationRouterData> for CaptureBuyerRequest {\n type Error = error_stack::Report;\n fn try_from(item: &TokenizationRouterData) -> Result {\n match item.request.payment_method_data.clone() {\n PaymentMethodData::Card(req_card) => {\n let seller_payme_id =\n PaymeAuthType::try_from(&item.connector_auth_type)?.seller_payme_id;\n let card = PaymeCard {\n credit_card_cvv: req_card.card_cvc.clone(),\n credit_card_exp: req_card\n .get_card_expiry_month_year_2_digit_with_delimiter(\"\".to_string())?,\n credit_card_number: req_card.card_number,\n };\n Ok(Self {\n card,\n seller_payme_id,\n })\n }\n PaymentMethodData::Wallet(_)\n | PaymentMethodData::CardRedirect(_)\n | PaymentMethodData::PayLater(_)\n | PaymentMethodData::BankRedirect(_)\n | PaymentMethodData::BankDebit(_)\n | PaymentMethodData::BankTransfer(_)\n | PaymentMethodData::Crypto(_)\n | PaymentMethodData::MandatePayment\n | PaymentMethodData::Reward\n | PaymentMethodData::RealTimePayment(_)\n | PaymentMethodData::MobilePayment(_)\n | PaymentMethodData::Upi(_)\n | PaymentMethodData::Voucher(_)\n | PaymentMethodData::GiftCard(_)\n | PaymentMethodData::OpenBanking(_)\n | PaymentMethodData::CardToken(_)\n | PaymentMethodData::NetworkToken(_)\n | PaymentMethodData::CardDetailsForNetworkTransactionId(_)\n | PaymentMethodData::CardWithLimitedDetails(_)\n | PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(_)\n | PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(_) => {\n Err(errors::ConnectorError::NotImplemented(\"Tokenize Flow\".to_string()).into())\n }\n }\n }\n}\n\n// Auth Struct\npub struct PaymeAuthType {\n #[allow(dead_code)]\n pub(super) payme_public_key: Secret,\n pub(super) seller_payme_id: Secret,\n pub(super) payme_merchant_id: Option>,\n}\n\nimpl TryFrom<&ConnectorAuthType> for PaymeAuthType {\n type Error = error_stack::Report;\n fn try_from(auth_type: &ConnectorAuthType) -> Result {\n match auth_type {\n ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {\n seller_payme_id: api_key.to_owned(),\n payme_public_key: key1.to_owned(),\n payme_merchant_id: None,\n }),\n ConnectorAuthType::SignatureKey {\n api_key,\n key1,\n api_secret,\n } => Ok(Self {\n seller_payme_id: api_key.to_owned(),\n payme_public_key: key1.to_owned(),\n payme_merchant_id: Some(api_secret.to_owned()),\n }),\n _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),\n }\n }\n}\n\nimpl TryFrom<&CreateOrderRouterData> for SaleType {\n type Error = error_stack::Report;\n fn try_from(value: &CreateOrderRouterData) -> Result {\n let sale_type = if value.request.setup_mandate_details.is_some() {\n // First mandate\n Self::Token\n } else {\n // Normal payments\n match value.request.is_auto_capture() {\n true => Self::Sale,\n false => Self::Authorize,\n }\n };\n Ok(sale_type)\n }\n}\n\nimpl TryFrom<&PaymentsPreProcessingRouterData> for SaleType {\n type Error = error_stack::Report;\n fn try_from(value: &PaymentsPreProcessingRouterData) -> Result {\n let sale_type = if value.request.setup_mandate_details.is_some() {\n // First mandate\n Self::Token\n } else {\n // Normal payments\n match value.request.is_auto_capture()? {\n true => Self::Sale,\n false => Self::Authorize,\n }\n };\n Ok(sale_type)\n }\n}\n\n#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, strum::Display)]\n#[serde(rename_all = \"kebab-case\")]\npub enum SaleStatus {\n Initial,\n Completed,\n Refunded,\n PartialRefund,\n Authorized,\n Voided,\n PartialVoid,\n Failed,\n Chargeback,\n}\n\nimpl From for enums::AttemptStatus {\n fn from(item: SaleStatus) -> Self {\n match item {\n SaleStatus::Initial => Self::Authorizing,\n SaleStatus::Completed => Self::Charged,\n SaleStatus::Refunded | SaleStatus::PartialRefund => Self::AutoRefunded,\n SaleStatus::Authorized => Self::Authorized,\n SaleStatus::Voided | SaleStatus::PartialVoid => Self::Voided,\n SaleStatus::Failed => Self::Failure,\n SaleStatus::Chargeback => Self::AutoRefunded,\n }\n }\n}\n\n#[derive(Debug, Deserialize, Serialize)]\n#[serde(untagged)]\npub enum PaymePaymentsResponse {\n PaymePaySaleResponse(PaymePaySaleResponse),\n SaleQueryResponse(SaleQueryResponse),\n}\n\n#[derive(Clone, Debug, Deserialize, Serialize)]\npub struct SaleQueryResponse {\n items: Vec,\n}\n\n#[derive(Clone, Debug, Deserialize, Serialize)]\npub struct SaleQuery {\n sale_status: SaleStatus,\n sale_payme_id: String,\n sale_error_text: Option,\n sale_error_code: Option,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub struct PaymePaySaleResponse {\n sale_status: SaleStatus,\n payme_sale_id: String,\n payme_transaction_id: Option,\n buyer_key: Option>,\n status_error_details: Option,\n status_error_code: Option,\n sale_3ds: Option,\n redirect_url: Option,\n}\n\n#[derive(Serialize, Deserialize)]\npub struct PaymeMetadata {\n payme_transaction_id: Option,\n}\n\nimpl TryFrom>\n for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData,\n ) -> Result {\n Ok(Self {\n payment_method_token: Some(PaymentMethodToken::Token(item.response.buyer_key.clone())),\n response: Ok(PaymentsResponseData::TokenizationResponse {\n token: item.response.buyer_key.expose(),\n }),\n ..item.data\n })\n }\n}\n\n#[derive(Debug, Serialize)]\npub struct PaymentCaptureRequest {\n payme_sale_id: String,\n sale_price: MinorUnit,\n}\n\nimpl TryFrom<&PaymeRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {\n type Error = error_stack::Report;\n fn try_from(item: &PaymeRouterData<&PaymentsCaptureRouterData>) -> Result {\n if item.router_data.request.minor_amount_to_capture\n != item.router_data.request.minor_payment_amount\n {\n Err(errors::ConnectorError::NotSupported {\n message: \"Partial Capture\".to_string(),\n connector: \"Payme\",\n })?\n }\n Ok(Self {\n payme_sale_id: item.router_data.request.connector_transaction_id.clone(),\n sale_price: item.amount,\n })\n }\n}\n\n// REFUND :\n// Type definition for RefundRequest\n#[derive(Debug, Serialize)]\npub struct PaymeRefundRequest {\n sale_refund_amount: MinorUnit,\n payme_sale_id: String,\n seller_payme_id: Secret,\n language: String,\n}\n\nimpl TryFrom<&PaymeRouterData<&RefundsRouterData>> for PaymeRefundRequest {\n type Error = error_stack::Report;\n fn try_from(item: &PaymeRouterData<&RefundsRouterData>) -> Result {\n let auth_type = PaymeAuthType::try_from(&item.router_data.connector_auth_type)?;\n Ok(Self {\n payme_sale_id: item.router_data.request.connector_transaction_id.clone(),\n seller_payme_id: auth_type.seller_payme_id,\n sale_refund_amount: item.amount.to_owned(),\n language: LANGUAGE.to_string(),\n })\n }\n}\n\nimpl TryFrom for enums::RefundStatus {\n type Error = error_stack::Report;\n fn try_from(sale_status: SaleStatus) -> Result {\n match sale_status {\n SaleStatus::Refunded | SaleStatus::PartialRefund => Ok(Self::Success),\n SaleStatus::Failed => Ok(Self::Failure),\n SaleStatus::Initial\n | SaleStatus::Completed\n | SaleStatus::Authorized\n | SaleStatus::Voided\n | SaleStatus::PartialVoid\n | SaleStatus::Chargeback => Err(errors::ConnectorError::ResponseHandlingFailed)?,\n }\n }\n}\n\n#[derive(Debug, Deserialize, Serialize)]\npub struct PaymeRefundResponse {\n sale_status: SaleStatus,\n payme_transaction_id: Option,\n status_error_code: Option,\n}\n\nimpl TryFrom>\n for RefundsRouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: RefundsResponseRouterData,\n ) -> Result {\n let refund_status = enums::RefundStatus::try_from(item.response.sale_status.clone())?;\n let response = if utils::is_refund_failure(refund_status) {\n let payme_response = &item.response;\n let status_error_code = payme_response\n .status_error_code\n .map(|error_code| error_code.to_string());\n Err(ErrorResponse {\n code: status_error_code\n .clone()\n .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),\n message: status_error_code\n .clone()\n .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),\n reason: status_error_code,\n status_code: item.http_code,\n attempt_status: None,\n connector_transaction_id: payme_response.payme_transaction_id.clone(),\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n } else {\n Ok(RefundsResponseData {\n connector_refund_id: item\n .response\n .payme_transaction_id\n .ok_or(errors::ConnectorError::MissingConnectorRefundID)?,\n refund_status,\n })\n };\n Ok(Self {\n response,\n ..item.data\n })\n }\n}\n\n#[derive(Debug, Serialize)]\npub struct PaymeVoidRequest {\n sale_currency: enums::Currency,\n payme_sale_id: String,\n seller_payme_id: Secret,\n language: String,\n}\n\nimpl TryFrom<&PaymeRouterData<&RouterData>>\n for PaymeVoidRequest\n{\n type Error = error_stack::Report;\n fn try_from(\n item: &PaymeRouterData<&RouterData>,\n ) -> Result {\n let auth_type = PaymeAuthType::try_from(&item.router_data.connector_auth_type)?;\n Ok(Self {\n payme_sale_id: item.router_data.request.connector_transaction_id.clone(),\n seller_payme_id: auth_type.seller_payme_id,\n sale_currency: item.router_data.request.get_currency()?,\n language: LANGUAGE.to_string(),\n })\n }\n}\n\n#[derive(Debug, Deserialize, Serialize)]\npub struct PaymeVoidResponse {\n sale_status: SaleStatus,\n payme_transaction_id: Option,\n status_error_code: Option,\n}\n\nimpl TryFrom> for PaymentsCancelRouterData {\n type Error = error_stack::Report;\n fn try_from(\n item: PaymentsCancelResponseRouterData,\n ) -> Result {\n let status = enums::AttemptStatus::from(item.response.sale_status.clone());\n let response = if utils::is_payment_failure(status) {\n let payme_response = &item.response;\n let status_error_code = payme_response\n .status_error_code\n .map(|error_code| error_code.to_string());\n Err(ErrorResponse {\n code: status_error_code\n .clone()\n .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),\n message: status_error_code\n .clone()\n .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),\n reason: status_error_code,\n status_code: item.http_code,\n attempt_status: None,\n connector_transaction_id: payme_response.payme_transaction_id.clone(),\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n } else {\n // Since we are not receiving payme_sale_id, we are not populating the transaction response\n Ok(PaymentsResponseData::TransactionResponse {\n resource_id: ResponseId::NoResponseId,\n redirection_data: Box::new(None),\n mandate_reference: Box::new(None),\n connector_metadata: None,\n network_txn_id: None,\n connector_response_reference_id: None,\n incremental_authorization_allowed: None,\n authentication_data: None,\n charges: None,\n })\n };\n Ok(Self {\n status,\n response,\n ..item.data\n })\n }\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub struct PaymeQueryTransactionResponse {\n items: Vec,\n}\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\npub struct TransactionQuery {\n sale_status: SaleStatus,\n payme_transaction_id: String,\n}\n\nimpl TryFrom>\n for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData,\n ) -> Result {\n let pay_sale_response = item\n .response\n .items\n .first()\n .ok_or(errors::ConnectorError::ResponseHandlingFailed)?;\n let refund_status = enums::RefundStatus::try_from(pay_sale_response.sale_status.clone())?;\n let response = if utils::is_refund_failure(refund_status) {\n Err(ErrorResponse {\n code: consts::NO_ERROR_CODE.to_string(),\n message: consts::NO_ERROR_CODE.to_string(),\n reason: None,\n status_code: item.http_code,\n attempt_status: None,\n connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()),\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n } else {\n Ok(RefundsResponseData {\n refund_status,\n connector_refund_id: pay_sale_response.payme_transaction_id.clone(),\n })\n };\n Ok(Self {\n response,\n ..item.data\n })\n }\n}\n\nfn get_services(auth_type: AuthenticationType) -> Option {\n match auth_type {\n AuthenticationType::ThreeDs => {\n let settings = ThreeDsSettings { active: true };\n Some(ThreeDs {\n name: ThreeDsType::ThreeDs,\n settings,\n })\n }\n AuthenticationType::NoThreeDs => None,\n }\n}\n\n#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]\npub struct PaymeErrorResponse {\n pub status_code: u16,\n pub status_error_details: String,\n pub status_additional_info: serde_json::Value,\n pub status_error_code: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(rename_all = \"kebab-case\")]\npub enum NotifyType {\n SaleComplete,\n SaleAuthorized,\n Refund,\n SaleFailure,\n SaleChargeback,\n SaleChargebackRefund,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub struct WebhookEventDataResource {\n pub sale_status: SaleStatus,\n pub payme_signature: Secret,\n pub buyer_key: Option>,\n pub notify_type: NotifyType,\n pub payme_sale_id: String,\n pub payme_transaction_id: String,\n pub status_error_details: Option,\n pub status_error_code: Option,\n pub price: MinorUnit,\n pub currency: enums::Currency,\n}\n\n#[derive(Debug, Deserialize)]\npub struct WebhookEventDataResourceEvent {\n pub notify_type: NotifyType,\n}\n\n#[derive(Debug, Deserialize)]\npub struct WebhookEventDataResourceSignature {\n pub payme_signature: Secret,\n}\n\n/// This try_from will ensure that webhook body would be properly parsed into PSync response\nimpl From for PaymePaySaleResponse {\n fn from(value: WebhookEventDataResource) -> Self {\n Self {\n sale_status: value.sale_status,\n payme_sale_id: value.payme_sale_id,\n payme_transaction_id: Some(value.payme_transaction_id),\n buyer_key: value.buyer_key,\n sale_3ds: None,\n redirect_url: None,\n status_error_code: value.status_error_code,\n status_error_details: value.status_error_details,\n }\n }\n}\n\n/// This try_from will ensure that webhook body would be properly parsed into RSync response\nimpl From for PaymeQueryTransactionResponse {\n fn from(value: WebhookEventDataResource) -> Self {\n let item = TransactionQuery {\n sale_status: value.sale_status,\n payme_transaction_id: value.payme_transaction_id,\n };\n Self { items: vec![item] }\n }\n}\n\nimpl From for api_models::webhooks::IncomingWebhookEvent {\n fn from(value: NotifyType) -> Self {\n match value {\n NotifyType::SaleComplete => Self::PaymentIntentSuccess,\n NotifyType::Refund => Self::RefundSuccess,\n NotifyType::SaleFailure => Self::PaymentIntentFailure,\n NotifyType::SaleChargeback => Self::DisputeOpened,\n NotifyType::SaleChargebackRefund => Self::DisputeWon,\n NotifyType::SaleAuthorized => Self::EventNotSupported,\n }\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__powertranz.rs", "text": "pub mod transformers;\n\nuse std::sync::LazyLock;\n\nuse api_models::enums::AuthenticationType;\nuse common_enums::enums;\nuse common_utils::{\n errors::CustomResult,\n ext_traits::{BytesExt, ValueExt},\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n CompleteAuthorize,\n },\n router_request_types::{\n AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,\n PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,\n PaymentsSyncData, RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,\n PaymentsCompleteAuthorizeRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n consts, errors,\n events::connector_api_logs::ConnectorEvent,\n types::{\n PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,\n PaymentsVoidType, RefundExecuteType, Response,\n },\n webhooks,\n};\nuse masking::{ExposeInterface, Mask};\nuse transformers as powertranz;\n\nuse crate::{\n constants::headers,\n types::ResponseRouterData,\n utils::{\n convert_amount, PaymentsAuthorizeRequestData as _,\n PaymentsCompleteAuthorizeRequestData as _,\n },\n};\n\n#[derive(Clone)]\npub struct Powertranz {\n amount_convertor: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Powertranz {\n pub fn new() -> &'static Self {\n &Self {\n amount_convertor: &FloatMajorUnitForConnector,\n }\n }\n}\n\nimpl api::Payment for Powertranz {}\nimpl api::PaymentSession for Powertranz {}\nimpl api::ConnectorAccessToken for Powertranz {}\nimpl api::MandateSetup for Powertranz {}\nimpl api::PaymentAuthorize for Powertranz {}\nimpl api::PaymentsCompleteAuthorize for Powertranz {}\nimpl api::PaymentSync for Powertranz {}\nimpl api::PaymentCapture for Powertranz {}\nimpl api::PaymentVoid for Powertranz {}\nimpl api::Refund for Powertranz {}\nimpl api::RefundExecute for Powertranz {}\nimpl api::RefundSync for Powertranz {}\nimpl api::PaymentToken for Powertranz {}\n\nconst POWER_TRANZ_ID: &str = \"PowerTranz-PowerTranzId\";\nconst POWER_TRANZ_PASSWORD: &str = \"PowerTranz-PowerTranzPassword\";\n\nimpl ConnectorIntegration\n for Powertranz\n{\n}\n\nimpl ConnectorCommonExt for Powertranz\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let mut header = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.common_get_content_type().to_string().into(),\n )];\n let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;\n header.append(&mut auth_header);\n Ok(header)\n }\n}\n\nimpl ConnectorCommon for Powertranz {\n fn id(&self) -> &'static str {\n \"powertranz\"\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.powertranz.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, errors::ConnectorError> {\n let auth = powertranz::PowertranzAuthType::try_from(auth_type)\n .change_context(errors::ConnectorError::FailedToObtainAuthType)?;\n Ok(vec![\n (\n POWER_TRANZ_ID.to_string(),\n auth.power_tranz_id.expose().into_masked(),\n ),\n (\n POWER_TRANZ_PASSWORD.to_string(),\n auth.power_tranz_password.expose().into_masked(),\n ),\n ])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n // For error scenarios connector respond with 200 http status code and error response object in response\n // For http status code other than 200 they send empty response back\n event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&serde_json::json!({\"error_response\": std::str::from_utf8(&res.response).unwrap_or(\"\")})));\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: consts::NO_ERROR_CODE.to_string(),\n message: consts::NO_ERROR_MESSAGE.to_string(),\n reason: None,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Powertranz {}\n\nimpl ConnectorIntegration for Powertranz {}\n\nimpl ConnectorIntegration for Powertranz {}\n\nimpl ConnectorIntegration\n for Powertranz\n{\n fn build_request(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(\n errors::ConnectorError::NotImplemented(\"Setup Mandate flow for Powertranz\".to_string())\n .into(),\n )\n }\n}\n\nimpl ConnectorIntegration for Powertranz {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let mut endpoint = match req.request.is_auto_capture()? {\n true => \"sale\",\n false => \"auth\",\n }\n .to_string();\n // 3ds payments uses different endpoints\n if req.auth_type == AuthenticationType::ThreeDs {\n endpoint.insert_str(0, \"spi/\")\n };\n Ok(format!(\"{}{endpoint}\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_convertor,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = powertranz::PowertranzRouterData::try_from((amount, req))?;\n let connector_req =\n powertranz::PowertranzPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)\n .set_body(PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: powertranz::PowertranzBaseResponse = res\n .response\n .parse_struct(\"Powertranz PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Powertranz\n{\n fn get_headers(\n &self,\n req: &PaymentsCompleteAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n \"application/json-patch+json\"\n }\n\n fn get_url(\n &self,\n _req: &PaymentsCompleteAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}spi/payment\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCompleteAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let redirect_payload: powertranz::RedirectResponsePayload = req\n .request\n .get_redirect_response_payload()?\n .parse_value(\"PowerTranz RedirectResponsePayload\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n let spi_token = format!(r#\"\"{}\"\"#, redirect_payload.spi_token.expose());\n Ok(RequestContent::Json(Box::new(spi_token)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCompleteAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&PaymentsCompleteAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(PaymentsCompleteAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(PaymentsCompleteAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCompleteAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: powertranz::PowertranzBaseResponse = res\n .response\n .parse_struct(\"Powertranz PaymentsCompleteAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Powertranz {\n // default implementation of build_request method will be executed\n}\n\nimpl ConnectorIntegration for Powertranz {\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}capture\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_convertor,\n req.request.minor_amount_to_capture,\n req.request.currency,\n )?;\n\n let connector_router_data = powertranz::PowertranzRouterData::try_from((amount, req))?;\n let connector_req = powertranz::PowertranzBaseRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)\n .set_body(PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: powertranz::PowertranzBaseResponse = res\n .response\n .parse_struct(\"Powertranz PaymentsCaptureResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Powertranz {\n fn get_headers(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n _req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}void\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = powertranz::PowertranzBaseRequest::try_from(&req.request)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn handle_response(\n &self,\n data: &RouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: powertranz::PowertranzBaseResponse = res\n .response\n .parse_struct(\"powertranz CancelResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn build_request(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&PaymentsVoidType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsVoidType::get_headers(self, req, connectors)?)\n .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Powertranz {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}refund\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_convertor,\n req.request.minor_refund_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = powertranz::PowertranzRouterData::try_from((amount, req))?;\n let connector_req = powertranz::PowertranzBaseRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(RefundExecuteType::get_headers(self, req, connectors)?)\n .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: powertranz::PowertranzBaseResponse = res\n .response\n .parse_struct(\"powertranz RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Powertranz {\n // default implementation of build_request method will be executed\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Powertranz {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic POWERTRANZ_SUPPORTED_PAYMENT_METHODS: LazyLock =\n LazyLock::new(|| {\n let supported_capture_methods = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::Manual,\n enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let supported_card_network = vec![\n common_enums::CardNetwork::Visa,\n common_enums::CardNetwork::Mastercard,\n common_enums::CardNetwork::AmericanExpress,\n ];\n\n let mut powertranz_supported_payment_methods = SupportedPaymentMethods::new();\n\n powertranz_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Credit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::Supported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n powertranz_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Debit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::Supported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n powertranz_supported_payment_methods\n });\n\nstatic POWERTRANZ_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Powertranz\",\n description: \"Powertranz is a leading payment gateway serving the Caribbean and parts of Central America \",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: enums::ConnectorIntegrationStatus::Alpha,\n};\n\nstatic POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];\n\nimpl ConnectorSpecifications for Powertranz {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&POWERTRANZ_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*POWERTRANZ_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&POWERTRANZ_SUPPORTED_WEBHOOK_FLOWS)\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__signifyd__transformers__api.rs", "text": "use api_models::webhooks::IncomingWebhookEvent;\nuse common_enums::{AttemptStatus, Currency, FraudCheckStatus, PaymentMethod};\nuse common_utils::{ext_traits::ValueExt, pii::Email};\nuse error_stack::{self, ResultExt};\npub use hyperswitch_domain_models::router_request_types::fraud_check::RefundMethod;\nuse hyperswitch_domain_models::{\n router_data::RouterData,\n router_flow_types::Fulfillment,\n router_request_types::{\n fraud_check::{self, FraudCheckFulfillmentData, FrmFulfillmentRequest},\n ResponseId,\n },\n router_response_types::fraud_check::FraudCheckResponseData,\n};\nuse hyperswitch_interfaces::errors::ConnectorError;\nuse masking::Secret;\nuse num_traits::ToPrimitive;\nuse serde::{Deserialize, Serialize};\nuse time::PrimitiveDateTime;\nuse utoipa::ToSchema;\n\nuse crate::{\n types::{\n FrmCheckoutRouterData, FrmFulfillmentRouterData, FrmRecordReturnRouterData,\n FrmSaleRouterData, FrmTransactionRouterData, ResponseRouterData,\n },\n utils::{\n AddressDetailsData as _, FraudCheckCheckoutRequest, FraudCheckRecordReturnRequest as _,\n FraudCheckSaleRequest as _, FraudCheckTransactionRequest as _, RouterData as _,\n },\n};\n#[allow(dead_code)]\n#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum DecisionDelivery {\n Sync,\n AsyncOnly,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct Purchase {\n #[serde(with = \"common_utils::custom_serde::iso8601\")]\n created_at: PrimitiveDateTime,\n order_channel: OrderChannel,\n total_price: i64,\n products: Vec,\n shipments: Shipments,\n currency: Option,\n total_shipping_cost: Option,\n confirmation_email: Option,\n confirmation_phone: Option>,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]\n#[serde(rename_all(serialize = \"SCREAMING_SNAKE_CASE\", deserialize = \"snake_case\"))]\npub enum OrderChannel {\n Web,\n Phone,\n MobileApp,\n Social,\n Marketplace,\n InStoreKiosk,\n ScanAndGo,\n SmartTv,\n Mit,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]\n#[serde(rename_all(serialize = \"SCREAMING_SNAKE_CASE\", deserialize = \"snake_case\"))]\npub enum FulfillmentMethod {\n Delivery,\n CounterPickup,\n CubsidePickup,\n LockerPickup,\n StandardShipping,\n ExpeditedShipping,\n GasPickup,\n ScheduledDelivery,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Products {\n item_name: String,\n item_price: i64,\n item_quantity: i32,\n item_id: Option,\n item_category: Option,\n item_sub_category: Option,\n item_is_digital: Option,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Shipments {\n destination: Destination,\n fulfillment_method: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Destination {\n full_name: Secret,\n organization: Option,\n email: Option,\n address: Address,\n}\n\n#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Address {\n street_address: Secret,\n unit: Option>,\n postal_code: Secret,\n city: String,\n province_code: Secret,\n country_code: common_enums::CountryAlpha2,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]\n#[serde(rename_all(serialize = \"SCREAMING_SNAKE_CASE\", deserialize = \"snake_case\"))]\npub enum CoverageRequests {\n Fraud, // use when you need a financial guarantee for Payment Fraud.\n Inr, // use when you need a financial guarantee for Item Not Received.\n Snad, // use when you need a financial guarantee for fraud alleging items are Significantly Not As Described.\n All, // use when you need a financial guarantee on all chargebacks.\n None, // use when you do not need a financial guarantee. Suggested actions in decision.checkpointAction are recommendations.\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydPaymentsSaleRequest {\n order_id: String,\n purchase: Purchase,\n decision_delivery: DecisionDelivery,\n coverage_requests: Option,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]\n#[serde(rename_all(serialize = \"camelCase\", deserialize = \"snake_case\"))]\npub struct SignifydFrmMetadata {\n pub total_shipping_cost: Option,\n pub fulfillment_method: Option,\n pub coverage_request: Option,\n pub order_channel: OrderChannel,\n}\n\nimpl TryFrom<&FrmSaleRouterData> for SignifydPaymentsSaleRequest {\n type Error = error_stack::Report;\n fn try_from(item: &FrmSaleRouterData) -> Result {\n let products = item\n .request\n .get_order_details()?\n .iter()\n .map(|order_detail| Products {\n item_name: order_detail.product_name.clone(),\n item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.\n item_quantity: i32::from(order_detail.quantity),\n item_id: order_detail.product_id.clone(),\n item_category: order_detail.category.clone(),\n item_sub_category: order_detail.sub_category.clone(),\n item_is_digital: order_detail\n .product_type\n .as_ref()\n .map(|product| product == &common_enums::ProductType::Digital),\n })\n .collect::>();\n let metadata: SignifydFrmMetadata = item\n .frm_metadata\n .clone()\n .ok_or(ConnectorError::MissingRequiredField {\n field_name: \"frm_metadata\",\n })?\n .parse_value(\"Signifyd Frm Metadata\")\n .change_context(ConnectorError::InvalidDataFormat {\n field_name: \"frm_metadata\",\n })?;\n let ship_address = item.get_shipping_address()?;\n let billing_address = item.get_billing()?;\n let street_addr = ship_address.get_line1()?;\n let city_addr = ship_address.get_city()?;\n let zip_code_addr = ship_address.get_zip()?;\n let country_code_addr = ship_address.get_country()?;\n let _first_name_addr = ship_address.get_first_name()?;\n let _last_name_addr = ship_address.get_last_name()?;\n let address: Address = Address {\n street_address: street_addr.clone(),\n unit: None,\n postal_code: zip_code_addr.clone(),\n city: city_addr.clone(),\n province_code: zip_code_addr.clone(),\n country_code: country_code_addr.to_owned(),\n };\n let destination: Destination = Destination {\n full_name: ship_address.get_full_name().unwrap_or_default(),\n organization: None,\n email: None,\n address,\n };\n\n let created_at = common_utils::date_time::now();\n let order_channel = metadata.order_channel;\n let shipments = Shipments {\n destination,\n fulfillment_method: metadata.fulfillment_method,\n };\n let purchase = Purchase {\n created_at,\n order_channel,\n total_price: item.request.amount,\n products,\n shipments,\n currency: item.request.currency,\n total_shipping_cost: metadata.total_shipping_cost,\n confirmation_email: item.request.email.clone(),\n confirmation_phone: billing_address\n .clone()\n .phone\n .and_then(|phone_data| phone_data.number),\n };\n Ok(Self {\n order_id: item.attempt_id.clone(),\n purchase,\n decision_delivery: DecisionDelivery::Sync, // Specify SYNC if you require the Response to contain a decision field. If you have registered for a webhook associated with this checkpoint, then the webhook will also be sent when SYNC is specified. If ASYNC_ONLY is specified, then the decision field in the response will be null, and you will require a Webhook integration to receive Signifyd's final decision\n coverage_requests: metadata.coverage_request,\n })\n }\n}\n\n#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Decision {\n #[serde(with = \"common_utils::custom_serde::iso8601\")]\n created_at: PrimitiveDateTime,\n checkpoint_action: SignifydPaymentStatus,\n checkpoint_action_reason: Option,\n checkpoint_action_policy: Option,\n score: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum SignifydPaymentStatus {\n Accept,\n Challenge,\n Credit,\n Hold,\n Reject,\n}\n\nimpl From for FraudCheckStatus {\n fn from(item: SignifydPaymentStatus) -> Self {\n match item {\n SignifydPaymentStatus::Accept => Self::Legit,\n SignifydPaymentStatus::Reject => Self::Fraud,\n SignifydPaymentStatus::Hold => Self::ManualReview,\n SignifydPaymentStatus::Challenge | SignifydPaymentStatus::Credit => Self::Pending,\n }\n }\n}\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydPaymentsResponse {\n signifyd_id: i64,\n order_id: String,\n decision: Decision,\n}\n\nimpl TryFrom>\n for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData,\n ) -> Result {\n Ok(Self {\n response: Ok(FraudCheckResponseData::TransactionResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),\n status: FraudCheckStatus::from(item.response.decision.checkpoint_action),\n connector_metadata: None,\n score: item.response.decision.score.and_then(|data| data.to_i32()),\n reason: item\n .response\n .decision\n .checkpoint_action_reason\n .map(serde_json::Value::from),\n }),\n ..item.data\n })\n }\n}\n\n#[derive(Debug, Deserialize, PartialEq, Serialize)]\npub struct SignifydErrorResponse {\n pub messages: Vec,\n pub errors: serde_json::Value,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde(rename_all = \"camelCase\")]\npub struct Transactions {\n transaction_id: String,\n gateway_status_code: String,\n payment_method: PaymentMethod,\n amount: i64,\n currency: Currency,\n gateway: Option,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydPaymentsTransactionRequest {\n order_id: String,\n checkout_id: String,\n transactions: Transactions,\n}\n\nimpl From for GatewayStatusCode {\n fn from(item: AttemptStatus) -> Self {\n match item {\n AttemptStatus::Pending => Self::Pending,\n AttemptStatus::Failure => Self::Failure,\n AttemptStatus::Charged => Self::Success,\n _ => Self::Pending,\n }\n }\n}\n\nimpl TryFrom<&FrmTransactionRouterData> for SignifydPaymentsTransactionRequest {\n type Error = error_stack::Report;\n fn try_from(item: &FrmTransactionRouterData) -> Result {\n let currency = item.request.get_currency()?;\n let transactions = Transactions {\n amount: item.request.amount,\n transaction_id: item.clone().payment_id,\n gateway_status_code: GatewayStatusCode::from(item.status).to_string(),\n payment_method: item.payment_method,\n currency,\n gateway: item.request.connector.clone(),\n };\n Ok(Self {\n order_id: item.attempt_id.clone(),\n checkout_id: item.payment_id.clone(),\n transactions,\n })\n }\n}\n\n#[derive(\n Clone,\n Copy,\n Debug,\n Default,\n Eq,\n PartialEq,\n serde::Serialize,\n serde::Deserialize,\n strum::Display,\n strum::EnumString,\n)]\n#[strum(serialize_all = \"SCREAMING_SNAKE_CASE\")]\npub enum GatewayStatusCode {\n Success,\n Failure,\n #[default]\n Pending,\n Error,\n Cancelled,\n Expired,\n SoftDecline,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydPaymentsCheckoutRequest {\n checkout_id: String,\n order_id: String,\n purchase: Purchase,\n coverage_requests: Option,\n}\n\nimpl TryFrom<&FrmCheckoutRouterData> for SignifydPaymentsCheckoutRequest {\n type Error = error_stack::Report;\n fn try_from(item: &FrmCheckoutRouterData) -> Result {\n let products = item\n .request\n .get_order_details()?\n .iter()\n .map(|order_detail| Products {\n item_name: order_detail.product_name.clone(),\n item_price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future.\n item_quantity: i32::from(order_detail.quantity),\n item_id: order_detail.product_id.clone(),\n item_category: order_detail.category.clone(),\n item_sub_category: order_detail.sub_category.clone(),\n item_is_digital: order_detail\n .product_type\n .as_ref()\n .map(|product| product == &common_enums::ProductType::Digital),\n })\n .collect::>();\n let metadata: SignifydFrmMetadata = item\n .frm_metadata\n .clone()\n .ok_or(ConnectorError::MissingRequiredField {\n field_name: \"frm_metadata\",\n })?\n .parse_value(\"Signifyd Frm Metadata\")\n .change_context(ConnectorError::InvalidDataFormat {\n field_name: \"frm_metadata\",\n })?;\n let ship_address = item.get_shipping_address()?;\n let street_addr = ship_address.get_line1()?;\n let city_addr = ship_address.get_city()?;\n let zip_code_addr = ship_address.get_zip()?;\n let country_code_addr = ship_address.get_country()?;\n let _first_name_addr = ship_address.get_first_name()?;\n let _last_name_addr = ship_address.get_last_name()?;\n let billing_address = item.get_billing()?;\n let address: Address = Address {\n street_address: street_addr.clone(),\n unit: None,\n postal_code: zip_code_addr.clone(),\n city: city_addr.clone(),\n province_code: zip_code_addr.clone(),\n country_code: country_code_addr.to_owned(),\n };\n let destination: Destination = Destination {\n full_name: ship_address.get_full_name().unwrap_or_default(),\n organization: None,\n email: None,\n address,\n };\n let created_at = common_utils::date_time::now();\n let order_channel = metadata.order_channel;\n let shipments: Shipments = Shipments {\n destination,\n fulfillment_method: metadata.fulfillment_method,\n };\n let purchase = Purchase {\n created_at,\n order_channel,\n total_price: item.request.amount,\n products,\n shipments,\n currency: item.request.currency,\n total_shipping_cost: metadata.total_shipping_cost,\n confirmation_email: item.request.email.clone(),\n confirmation_phone: billing_address\n .clone()\n .phone\n .and_then(|phone_data| phone_data.number),\n };\n Ok(Self {\n checkout_id: item.payment_id.clone(),\n order_id: item.attempt_id.clone(),\n purchase,\n coverage_requests: metadata.coverage_request,\n })\n }\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]\n#[serde(deny_unknown_fields)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub struct FrmFulfillmentSignifydRequest {\n pub order_id: String,\n pub fulfillment_status: Option,\n pub fulfillments: Vec,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]\n#[serde(untagged)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub enum FulfillmentStatus {\n PARTIAL,\n COMPLETE,\n REPLACEMENT,\n CANCELED,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub struct Fulfillments {\n pub shipment_id: String,\n pub products: Option>,\n pub destination: Destination,\n pub fulfillment_method: Option,\n pub carrier: Option,\n pub shipment_status: Option,\n pub tracking_urls: Option>,\n pub tracking_numbers: Option>,\n pub shipped_at: Option,\n}\n\n#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub struct Product {\n pub item_name: String,\n pub item_quantity: i64,\n pub item_id: String,\n}\n\nimpl TryFrom<&FrmFulfillmentRouterData> for FrmFulfillmentSignifydRequest {\n type Error = error_stack::Report;\n fn try_from(item: &FrmFulfillmentRouterData) -> Result {\n Ok(Self {\n order_id: item.request.fulfillment_req.order_id.clone(),\n fulfillment_status: item\n .request\n .fulfillment_req\n .fulfillment_status\n .as_ref()\n .map(|fulfillment_status| FulfillmentStatus::from(&fulfillment_status.clone())),\n fulfillments: get_signifyd_fulfillments_from_frm_fulfillment_request(\n &item.request.fulfillment_req,\n ),\n })\n }\n}\n\nimpl From<&fraud_check::FulfillmentStatus> for FulfillmentStatus {\n fn from(status: &fraud_check::FulfillmentStatus) -> Self {\n match status {\n fraud_check::FulfillmentStatus::PARTIAL => Self::PARTIAL,\n fraud_check::FulfillmentStatus::COMPLETE => Self::COMPLETE,\n fraud_check::FulfillmentStatus::REPLACEMENT => Self::REPLACEMENT,\n fraud_check::FulfillmentStatus::CANCELED => Self::CANCELED,\n }\n }\n}\npub(crate) fn get_signifyd_fulfillments_from_frm_fulfillment_request(\n fulfillment_req: &FrmFulfillmentRequest,\n) -> Vec {\n fulfillment_req\n .fulfillments\n .iter()\n .map(|fulfillment| Fulfillments {\n shipment_id: fulfillment.shipment_id.clone(),\n products: fulfillment\n .products\n .as_ref()\n .map(|products| products.iter().map(|p| Product::from(p.clone())).collect()),\n destination: Destination::from(fulfillment.destination.clone()),\n tracking_urls: fulfillment_req.tracking_urls.clone(),\n tracking_numbers: fulfillment_req.tracking_numbers.clone(),\n fulfillment_method: fulfillment_req.fulfillment_method.clone(),\n carrier: fulfillment_req.carrier.clone(),\n shipment_status: fulfillment_req.shipment_status.clone(),\n shipped_at: fulfillment_req.shipped_at.clone(),\n })\n .collect()\n}\n\nimpl From for Product {\n fn from(product: fraud_check::Product) -> Self {\n Self {\n item_name: product.item_name,\n item_quantity: product.item_quantity,\n item_id: product.item_id,\n }\n }\n}\n\nimpl From for Destination {\n fn from(destination: fraud_check::Destination) -> Self {\n Self {\n full_name: destination.full_name,\n organization: destination.organization,\n email: destination.email,\n address: Address::from(destination.address),\n }\n }\n}\n\nimpl From for Address {\n fn from(address: fraud_check::Address) -> Self {\n Self {\n street_address: address.street_address,\n unit: address.unit,\n postal_code: address.postal_code,\n city: address.city,\n province_code: address.province_code,\n country_code: address.country_code,\n }\n }\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub struct FrmFulfillmentSignifydApiResponse {\n pub order_id: String,\n pub shipment_ids: Vec,\n}\n\nimpl\n TryFrom<\n ResponseRouterData<\n Fulfillment,\n FrmFulfillmentSignifydApiResponse,\n FraudCheckFulfillmentData,\n FraudCheckResponseData,\n >,\n > for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData<\n Fulfillment,\n FrmFulfillmentSignifydApiResponse,\n FraudCheckFulfillmentData,\n FraudCheckResponseData,\n >,\n ) -> Result {\n Ok(Self {\n response: Ok(FraudCheckResponseData::FulfillmentResponse {\n order_id: item.response.order_id,\n shipment_ids: item.response.shipment_ids,\n }),\n ..item.data\n })\n }\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq, Clone)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydRefund {\n method: RefundMethod,\n amount: String,\n currency: Currency,\n}\n\n#[derive(Debug, Serialize, Eq, PartialEq)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydPaymentsRecordReturnRequest {\n order_id: String,\n return_id: String,\n refund_transaction_id: Option,\n refund: SignifydRefund,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n#[serde_with::skip_serializing_none]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydPaymentsRecordReturnResponse {\n return_id: String,\n order_id: String,\n}\n\nimpl\n TryFrom>\n for RouterData\n{\n type Error = error_stack::Report;\n fn try_from(\n item: ResponseRouterData<\n F,\n SignifydPaymentsRecordReturnResponse,\n T,\n FraudCheckResponseData,\n >,\n ) -> Result {\n Ok(Self {\n response: Ok(FraudCheckResponseData::RecordReturnResponse {\n resource_id: ResponseId::ConnectorTransactionId(item.response.order_id),\n return_id: Some(item.response.return_id.to_string()),\n connector_metadata: None,\n }),\n ..item.data\n })\n }\n}\n\nimpl TryFrom<&FrmRecordReturnRouterData> for SignifydPaymentsRecordReturnRequest {\n type Error = error_stack::Report;\n fn try_from(item: &FrmRecordReturnRouterData) -> Result {\n let currency = item.request.get_currency()?;\n let refund = SignifydRefund {\n method: item.request.refund_method.clone(),\n amount: item.request.amount.to_string(),\n currency,\n };\n Ok(Self {\n return_id: uuid::Uuid::new_v4().to_string(),\n refund_transaction_id: item.request.refund_transaction_id.clone(),\n refund,\n order_id: item.attempt_id.clone(),\n })\n }\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct SignifydWebhookBody {\n pub order_id: String,\n pub review_disposition: ReviewDisposition,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum ReviewDisposition {\n Fraudulent,\n Good,\n}\n\nimpl From for IncomingWebhookEvent {\n fn from(value: ReviewDisposition) -> Self {\n match value {\n ReviewDisposition::Fraudulent => Self::FrmRejected,\n ReviewDisposition::Good => Self::FrmApproved,\n }\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__thunes.rs", "text": "pub mod transformers;\n\nuse common_utils::{\n errors::CustomResult,\n ext_traits::BytesExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n },\n router_request_types::{\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,\n RefundSyncRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, Response},\n webhooks,\n};\nuse masking::{ExposeInterface, Mask};\nuse transformers as thunes;\n\nuse crate::{constants::headers, types::ResponseRouterData, utils};\n\n#[derive(Clone)]\npub struct Thunes {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Thunes {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &StringMinorUnitForConnector,\n }\n }\n}\n\nimpl api::Payment for Thunes {}\nimpl api::PaymentSession for Thunes {}\nimpl api::ConnectorAccessToken for Thunes {}\nimpl api::MandateSetup for Thunes {}\nimpl api::PaymentAuthorize for Thunes {}\nimpl api::PaymentSync for Thunes {}\nimpl api::PaymentCapture for Thunes {}\nimpl api::PaymentVoid for Thunes {}\nimpl api::Refund for Thunes {}\nimpl api::RefundExecute for Thunes {}\nimpl api::RefundSync for Thunes {}\nimpl api::PaymentToken for Thunes {}\n\nimpl ConnectorIntegration\n for Thunes\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorCommonExt for Thunes\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let mut header = vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )];\n let mut api_key = self.get_auth_header(&req.connector_auth_type)?;\n header.append(&mut api_key);\n Ok(header)\n }\n}\n\nimpl ConnectorCommon for Thunes {\n fn id(&self) -> &'static str {\n \"thunes\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n // TODO! Check connector documentation, on which unit they are processing the currency.\n // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,\n // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.thunes.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, errors::ConnectorError> {\n let auth = thunes::ThunesAuthType::try_from(auth_type)\n .change_context(errors::ConnectorError::FailedToObtainAuthType)?;\n Ok(vec![(\n headers::AUTHORIZATION.to_string(),\n auth.api_key.expose().into_masked(),\n )])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: thunes::ThunesErrorResponse = res\n .response\n .parse_struct(\"ThunesErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: response.code,\n message: response.message,\n reason: response.reason,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Thunes {\n //TODO: implement functions when support enabled\n}\n\nimpl ConnectorIntegration for Thunes {\n //TODO: implement sessions flow\n}\n\nimpl ConnectorIntegration for Thunes {}\n\nimpl ConnectorIntegration for Thunes {}\n\nimpl ConnectorIntegration for Thunes {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = thunes::ThunesRouterData::from((amount, req));\n let connector_req = thunes::ThunesPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: thunes::ThunesPaymentsResponse = res\n .response\n .parse_struct(\"Thunes PaymentsAuthorizeResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Thunes {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: thunes::ThunesPaymentsResponse = res\n .response\n .parse_struct(\"thunes PaymentsSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Thunes {\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn get_request_body(\n &self,\n _req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_request_body method\".to_string()).into())\n }\n\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsCaptureType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: thunes::ThunesPaymentsResponse = res\n .response\n .parse_struct(\"Thunes PaymentsCaptureResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Thunes {}\n\nimpl ConnectorIntegration for Thunes {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let refund_amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_refund_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = thunes::ThunesRouterData::from((refund_amount, req));\n let connector_req = thunes::ThunesRefundRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&types::RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundExecuteType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::RefundExecuteType::get_request_body(\n self, req, connectors,\n )?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: thunes::RefundResponse =\n res.response\n .parse_struct(\"thunes RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Thunes {\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RefundSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n Err(errors::ConnectorError::NotImplemented(\"get_url method\".to_string()).into())\n }\n\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&types::RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundSyncType::get_headers(self, req, connectors)?)\n .set_body(types::RefundSyncType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: thunes::RefundResponse = res\n .response\n .parse_struct(\"thunes RefundSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Thunes {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic THUNES_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Thunes\",\n description: \"Thunes Payouts is a global payment solution that enables businesses to send instant, secure, and cost-effective cross-border payments to bank accounts, mobile wallets, and cards in over 130 countries using a single API\",\n connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,\n integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,\n};\n\nimpl ConnectorSpecifications for Thunes {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&THUNES_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n None\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {\n None\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__tokenex.rs", "text": "pub mod transformers;\n\nuse std::sync::LazyLock;\n\nuse common_enums::enums;\nuse common_utils::{\n errors::CustomResult,\n ext_traits::BytesExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n ExternalVaultInsertFlow, ExternalVaultRetrieveFlow,\n },\n router_request_types::{\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData, VaultRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,\n VaultResponseData,\n },\n types::VaultRouterData,\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, Response},\n webhooks,\n};\nuse masking::{ExposeInterface, Mask};\nuse transformers as tokenex;\n\nuse crate::{constants::headers, types::ResponseRouterData};\n\n#[derive(Clone)]\npub struct Tokenex;\n\nimpl api::Payment for Tokenex {}\nimpl api::PaymentSession for Tokenex {}\nimpl api::ConnectorAccessToken for Tokenex {}\nimpl api::MandateSetup for Tokenex {}\nimpl api::PaymentAuthorize for Tokenex {}\nimpl api::PaymentSync for Tokenex {}\nimpl api::PaymentCapture for Tokenex {}\nimpl api::PaymentVoid for Tokenex {}\nimpl api::Refund for Tokenex {}\nimpl api::RefundExecute for Tokenex {}\nimpl api::RefundSync for Tokenex {}\nimpl api::PaymentToken for Tokenex {}\nimpl api::ExternalVaultInsert for Tokenex {}\nimpl api::ExternalVault for Tokenex {}\nimpl api::ExternalVaultRetrieve for Tokenex {}\n\nimpl ConnectorIntegration\n for Tokenex\n{\n // Not Implemented (R)\n}\n\npub mod auth_headers {\n pub const TOKENEX_ID: &str = \"tx-tokenex-id\";\n pub const TOKENEX_API_KEY: &str = \"tx-apikey\";\n pub const TOKENEX_SCHEME: &str = \"tx-token-scheme\";\n pub const TOKENEX_SCHEME_VALUE: &str = \"PCI\";\n}\n\nimpl ConnectorCommonExt for Tokenex\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let auth = tokenex::TokenexAuthType::try_from(&req.connector_auth_type)\n .change_context(errors::ConnectorError::FailedToObtainAuthType)?;\n let header = vec![\n (\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n ),\n (\n auth_headers::TOKENEX_ID.to_string(),\n auth.tokenex_id.expose().into_masked(),\n ),\n (\n auth_headers::TOKENEX_API_KEY.to_string(),\n auth.api_key.expose().into_masked(),\n ),\n (\n auth_headers::TOKENEX_SCHEME.to_string(),\n auth_headers::TOKENEX_SCHEME_VALUE.to_string().into(),\n ),\n ];\n Ok(header)\n }\n}\n\nimpl ConnectorCommon for Tokenex {\n fn id(&self) -> &'static str {\n \"tokenex\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.tokenex.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, errors::ConnectorError> {\n let auth = tokenex::TokenexAuthType::try_from(auth_type)\n .change_context(errors::ConnectorError::FailedToObtainAuthType)?;\n Ok(vec![(\n headers::AUTHORIZATION.to_string(),\n auth.api_key.expose().into_masked(),\n )])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: tokenex::TokenexErrorResponse = res\n .response\n .parse_struct(\"TokenexErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n let (code, message) = response.error.split_once(':').unwrap_or((\"\", \"\"));\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: code.to_string(),\n message: message.to_string(),\n reason: Some(response.message),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {\n //TODO: implement sessions flow\n}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration for Tokenex {}\n\nimpl ConnectorIntegration\n for Tokenex\n{\n fn get_url(\n &self,\n _req: &VaultRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}/v2/Pci/Tokenize\", self.base_url(connectors)))\n }\n\n fn get_headers(\n &self,\n req: &VaultRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_request_body(\n &self,\n req: &VaultRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = tokenex::TokenexInsertRequest::try_from(req)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &VaultRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::ExternalVaultInsertType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::ExternalVaultInsertType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::ExternalVaultInsertType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &VaultRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: tokenex::TokenexInsertResponse = res\n .response\n .parse_struct(\"TokenexInsertResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Tokenex\n{\n fn get_url(\n &self,\n _req: &VaultRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}/v2/Pci/DetokenizeWithCvv\",\n self.base_url(connectors)\n ))\n }\n\n fn get_headers(\n &self,\n req: &VaultRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_request_body(\n &self,\n req: &VaultRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = tokenex::TokenexRetrieveRequest::try_from(req)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &VaultRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::ExternalVaultRetrieveType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::ExternalVaultRetrieveType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::ExternalVaultRetrieveType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &VaultRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: tokenex::TokenexRetrieveResponse = res\n .response\n .parse_struct(\"TokenexRetrieveResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Tokenex {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic TOKENEX_SUPPORTED_PAYMENT_METHODS: LazyLock =\n LazyLock::new(SupportedPaymentMethods::new);\n\nstatic TOKENEX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Tokenex\",\n description: \"Tokenex connector\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: enums::ConnectorIntegrationStatus::Alpha,\n};\n\nstatic TOKENEX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];\n\nimpl ConnectorSpecifications for Tokenex {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&TOKENEX_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*TOKENEX_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&TOKENEX_SUPPORTED_WEBHOOK_FLOWS)\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__wellsfargo.rs", "text": "pub mod transformers;\n\nuse std::sync::LazyLock;\n\nuse base64::Engine;\nuse common_enums::enums;\nuse common_utils::{\n consts,\n errors::CustomResult,\n ext_traits::BytesExt,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},\n};\nuse error_stack::{report, Report, ResultExt};\nuse hyperswitch_domain_models::{\n payment_method_data::PaymentMethodData,\n router_data::{AccessToken, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n mandate_revoke::MandateRevoke,\n payments::{\n Authorize, Capture, IncrementalAuthorization, PSync, PaymentMethodToken, Session,\n SetupMandate, Void,\n },\n refunds::{Execute, RSync},\n },\n router_request_types::{\n AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData,\n PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,\n PaymentsIncrementalAuthorizationData, PaymentsSessionData, PaymentsSyncData, RefundsData,\n SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,\n RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,\n PaymentsCaptureRouterData, PaymentsIncrementalAuthorizationRouterData,\n PaymentsSyncRouterData, RefundExecuteRouterData, RefundSyncRouterData,\n SetupMandateRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self,\n refunds::{Refund, RefundExecute, RefundSync},\n ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{\n IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType,\n PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType,\n Response, SetupMandateType,\n },\n webhooks,\n};\nuse masking::{ExposeInterface, Mask, Maskable, PeekInterface};\nuse ring::{digest, hmac};\nuse time::OffsetDateTime;\nuse transformers as wellsfargo;\nuse url::Url;\n\nuse crate::{\n constants::{self, headers},\n types::ResponseRouterData,\n utils::{self, convert_amount, PaymentMethodDataType, RefundsRequestData},\n};\n#[derive(Clone)]\npub struct Wellsfargo {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Wellsfargo {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &StringMajorUnitForConnector,\n }\n }\n\n pub fn generate_digest(&self, payload: &[u8]) -> String {\n let payload_digest = digest::digest(&digest::SHA256, payload);\n consts::BASE64_ENGINE.encode(payload_digest)\n }\n\n pub fn generate_signature(\n &self,\n auth: wellsfargo::WellsfargoAuthType,\n host: String,\n resource: &str,\n payload: &String,\n date: OffsetDateTime,\n http_method: Method,\n ) -> CustomResult {\n let wellsfargo::WellsfargoAuthType {\n api_key,\n merchant_account,\n api_secret,\n } = auth;\n let is_post_method = matches!(http_method, Method::Post);\n let is_patch_method = matches!(http_method, Method::Patch);\n let is_delete_method = matches!(http_method, Method::Delete);\n let digest_str = if is_post_method || is_patch_method {\n \"digest \"\n } else {\n \"\"\n };\n let headers = format!(\"host date (request-target) {digest_str}v-c-merchant-id\");\n let request_target = if is_post_method {\n format!(\"(request-target): post {resource}\\ndigest: SHA-256={payload}\\n\")\n } else if is_patch_method {\n format!(\"(request-target): patch {resource}\\ndigest: SHA-256={payload}\\n\")\n } else if is_delete_method {\n format!(\"(request-target): delete {resource}\\n\")\n } else {\n format!(\"(request-target): get {resource}\\n\")\n };\n let signature_string = format!(\n \"host: {host}\\ndate: {date}\\n{request_target}v-c-merchant-id: {}\",\n merchant_account.peek()\n );\n let key_value = consts::BASE64_ENGINE\n .decode(api_secret.expose())\n .change_context(errors::ConnectorError::InvalidConnectorConfig {\n config: \"connector_account_details.api_secret\",\n })?;\n let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);\n let signature_value =\n consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());\n let signature_header = format!(\n r#\"keyid=\"{}\", algorithm=\"HmacSHA256\", headers=\"{headers}\", signature=\"{signature_value}\"\"#,\n api_key.peek()\n );\n\n Ok(signature_header)\n }\n}\n\nimpl ConnectorCommon for Wellsfargo {\n fn id(&self) -> &'static str {\n \"wellsfargo\"\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/json;charset=utf-8\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.wellsfargo.base_url.as_ref()\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Base\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: Result<\n wellsfargo::WellsfargoErrorResponse,\n Report,\n > = res.response.parse_struct(\"Wellsfargo ErrorResponse\");\n\n let error_message = if res.status_code == 401 {\n constants::CONNECTOR_UNAUTHORIZED_ERROR\n } else {\n hyperswitch_interfaces::consts::NO_ERROR_MESSAGE\n };\n match response {\n Ok(transformers::WellsfargoErrorResponse::StandardError(response)) => {\n event_builder.map(|i| i.set_error_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n let (code, message, reason) = match response.error_information {\n Some(ref error_info) => {\n let detailed_error_info = error_info.details.as_ref().map(|details| {\n details\n .iter()\n .map(|det| format!(\"{} : {}\", det.field, det.reason))\n .collect::>()\n .join(\", \")\n });\n (\n error_info.reason.clone(),\n error_info.reason.clone(),\n transformers::get_error_reason(\n Some(error_info.message.clone()),\n detailed_error_info,\n None,\n ),\n )\n }\n None => {\n let detailed_error_info = response.details.map(|details| {\n details\n .iter()\n .map(|det| format!(\"{} : {}\", det.field, det.reason))\n .collect::>()\n .join(\", \")\n });\n (\n response.reason.clone().map_or(\n hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),\n |reason| reason.to_string(),\n ),\n response\n .reason\n .map_or(error_message.to_string(), |reason| reason.to_string()),\n transformers::get_error_reason(\n response.message,\n detailed_error_info,\n None,\n ),\n )\n }\n };\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code,\n message,\n reason,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n Ok(transformers::WellsfargoErrorResponse::AuthenticationError(response)) => {\n event_builder.map(|i| i.set_error_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),\n message: response.response.rmsg.clone(),\n reason: Some(response.response.rmsg),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n Ok(transformers::WellsfargoErrorResponse::NotAvailableError(response)) => {\n event_builder.map(|i| i.set_error_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n let error_response = response\n .errors\n .iter()\n .map(|error_info| {\n format!(\n \"{}: {}\",\n error_info.error_type.clone().unwrap_or(\"\".to_string()),\n error_info.message.clone().unwrap_or(\"\".to_string())\n )\n })\n .collect::>()\n .join(\" & \");\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),\n message: error_response.clone(),\n reason: Some(error_response),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n Err(error_msg) => {\n event_builder.map(|event| event.set_error(serde_json::json!({\"error\": res.response.escape_ascii().to_string(), \"status_code\": res.status_code})));\n router_env::logger::error!(deserialization_error =? error_msg);\n utils::handle_json_response_deserialization_failure(res, \"wellsfargo\")\n }\n }\n }\n}\n\nimpl ConnectorValidation for Wellsfargo {\n fn validate_mandate_payment(\n &self,\n pm_type: Option,\n pm_data: PaymentMethodData,\n ) -> CustomResult<(), errors::ConnectorError> {\n let mandate_supported_pmd = std::collections::HashSet::from([\n PaymentMethodDataType::Card,\n PaymentMethodDataType::ApplePay,\n PaymentMethodDataType::GooglePay,\n ]);\n utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())\n }\n}\n\nimpl ConnectorCommonExt for Wellsfargo\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let date = OffsetDateTime::now_utc();\n let wellsfargo_req = self.get_request_body(req, connectors)?;\n let auth = wellsfargo::WellsfargoAuthType::try_from(&req.connector_auth_type)?;\n let merchant_account = auth.merchant_account.clone();\n let base_url = connectors.wellsfargo.base_url.as_str();\n let wellsfargo_host =\n Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;\n let host = wellsfargo_host\n .host_str()\n .ok_or(errors::ConnectorError::RequestEncodingFailed)?;\n let path: String = self\n .get_url(req, connectors)?\n .chars()\n .skip(base_url.len() - 1)\n .collect();\n let sha256 = self.generate_digest(wellsfargo_req.get_inner_value().expose().as_bytes());\n let http_method = self.get_http_method();\n let signature = self.generate_signature(\n auth,\n host.to_string(),\n path.as_str(),\n &sha256,\n date,\n http_method,\n )?;\n\n let mut headers = vec![\n (\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n ),\n (\n headers::ACCEPT.to_string(),\n \"application/hal+json;charset=utf-8\".to_string().into(),\n ),\n (\n \"v-c-merchant-id\".to_string(),\n merchant_account.into_masked(),\n ),\n (\"Date\".to_string(), date.to_string().into()),\n (\"Host\".to_string(), host.to_string().into()),\n (\"Signature\".to_string(), signature.into_masked()),\n ];\n if matches!(http_method, Method::Post | Method::Put | Method::Patch) {\n headers.push((\n \"Digest\".to_string(),\n format!(\"SHA-256={sha256}\").into_masked(),\n ));\n }\n Ok(headers)\n }\n}\n\nimpl api::Payment for Wellsfargo {}\nimpl api::PaymentAuthorize for Wellsfargo {}\nimpl api::PaymentSync for Wellsfargo {}\nimpl api::PaymentVoid for Wellsfargo {}\nimpl api::PaymentCapture for Wellsfargo {}\nimpl api::PaymentIncrementalAuthorization for Wellsfargo {}\nimpl api::MandateSetup for Wellsfargo {}\nimpl api::ConnectorAccessToken for Wellsfargo {}\nimpl api::PaymentToken for Wellsfargo {}\nimpl api::ConnectorMandateRevoke for Wellsfargo {}\n\nimpl ConnectorIntegration\n for Wellsfargo\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorIntegration\n for Wellsfargo\n{\n fn get_headers(\n &self,\n req: &SetupMandateRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n fn get_url(\n &self,\n _req: &SetupMandateRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}pts/v2/payments/\", self.base_url(connectors)))\n }\n fn get_request_body(\n &self,\n req: &SetupMandateRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = wellsfargo::WellsfargoZeroMandateRequest::try_from(req)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &SetupMandateRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&SetupMandateType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(SetupMandateType::get_headers(self, req, connectors)?)\n .set_body(SetupMandateType::get_request_body(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &SetupMandateRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoPaymentsResponse = res\n .response\n .parse_struct(\"WellsfargoSetupMandatesResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n\n fn get_5xx_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoServerErrorResponse = res\n .response\n .parse_struct(\"WellsfargoServerErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|event| event.set_response_body(&response));\n router_env::logger::info!(error_response=?response);\n\n let attempt_status = match response.reason {\n Some(reason) => match reason {\n transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),\n transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,\n },\n None => None,\n };\n Ok(ErrorResponse {\n status_code: res.status_code,\n reason: response.status.clone(),\n code: response\n .status\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),\n message: response\n .message\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),\n attempt_status,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorIntegration\n for Wellsfargo\n{\n fn get_headers(\n &self,\n req: &MandateRevokeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n fn get_http_method(&self) -> Method {\n Method::Delete\n }\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n fn get_url(\n &self,\n req: &MandateRevokeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}tms/v1/paymentinstruments/{}\",\n self.base_url(connectors),\n utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)?\n ))\n }\n fn build_request(\n &self,\n req: &MandateRevokeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Delete)\n .url(&MandateRevokeType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(MandateRevokeType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &MandateRevokeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n if matches!(res.status_code, 204) {\n event_builder.map(|i| i.set_response_body(&serde_json::json!({\"mandate_status\": common_enums::MandateStatus::Revoked.to_string()})));\n Ok(MandateRevokeRouterData {\n response: Ok(MandateRevokeResponseData {\n mandate_status: common_enums::MandateStatus::Revoked,\n }),\n ..data.clone()\n })\n } else {\n // If http_code != 204 || http_code != 4xx, we dont know any other response scenario yet.\n let response_value: serde_json::Value = serde_json::from_slice(&res.response)\n .change_context(errors::ConnectorError::ResponseHandlingFailed)?;\n let response_string = response_value.to_string();\n\n event_builder.map(|i| {\n i.set_response_body(\n &serde_json::json!({\"response_string\": response_string.clone()}),\n )\n });\n router_env::logger::info!(connector_response=?response_string);\n\n Ok(MandateRevokeRouterData {\n response: Err(ErrorResponse {\n code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),\n message: response_string.clone(),\n reason: Some(response_string),\n status_code: res.status_code,\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n }),\n ..data.clone()\n })\n }\n }\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\nimpl ConnectorIntegration for Wellsfargo {\n // Not Implemented (R)\n}\n\nimpl api::PaymentSession for Wellsfargo {}\n\nimpl ConnectorIntegration for Wellsfargo {}\n\nimpl ConnectorIntegration for Wellsfargo {\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}pts/v2/payments/{}/captures\",\n self.base_url(connectors),\n connector_payment_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_converter,\n MinorUnit::new(req.request.amount_to_capture),\n req.request.currency,\n )?;\n\n let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));\n\n let connector_req =\n wellsfargo::WellsfargoPaymentsCaptureRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)\n .set_body(PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult<\n RouterData,\n errors::ConnectorError,\n > {\n let response: wellsfargo::WellsfargoPaymentsResponse = res\n .response\n .parse_struct(\"Wellsfargo PaymentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n\n fn get_5xx_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoServerErrorResponse = res\n .response\n .parse_struct(\"WellsfargoServerErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|event| event.set_response_body(&response));\n router_env::logger::info!(error_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n reason: response.status.clone(),\n code: response\n .status\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),\n message: response\n .message\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorIntegration for Wellsfargo {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_http_method(&self) -> Method {\n Method::Get\n }\n\n fn get_url(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req\n .request\n .connector_transaction_id\n .get_connector_transaction_id()\n .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;\n Ok(format!(\n \"{}tss/v2/transactions/{}\",\n self.base_url(connectors),\n connector_payment_id\n ))\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoTransactionResponse = res\n .response\n .parse_struct(\"Wellsfargo PaymentSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Wellsfargo {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\n \"{}pts/v2/payments/\",\n ConnectorCommon::base_url(self, connectors)\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_converter,\n MinorUnit::new(req.request.amount),\n req.request.currency,\n )?;\n\n let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));\n let connector_req =\n wellsfargo::WellsfargoPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)\n .set_body(self.get_request_body(req, connectors)?)\n .build();\n\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoPaymentsResponse = res\n .response\n .parse_struct(\"Wellsfargo PaymentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n\n fn get_5xx_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoServerErrorResponse = res\n .response\n .parse_struct(\"WellsfargoServerErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|event| event.set_response_body(&response));\n router_env::logger::info!(error_response=?response);\n\n let attempt_status = match response.reason {\n Some(reason) => match reason {\n transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),\n transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,\n },\n None => None,\n };\n Ok(ErrorResponse {\n status_code: res.status_code,\n reason: response.status.clone(),\n code: response\n .status\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),\n message: response\n .message\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),\n attempt_status,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorIntegration for Wellsfargo {\n fn get_headers(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}pts/v2/payments/{connector_payment_id}/reversals\",\n self.base_url(connectors)\n ))\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCancelRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_converter,\n MinorUnit::new(req.request.amount.ok_or(\n errors::ConnectorError::MissingRequiredField {\n field_name: \"Amount\",\n },\n )?),\n req.request\n .currency\n .ok_or(errors::ConnectorError::MissingRequiredField {\n field_name: \"Currency\",\n })?,\n )?;\n\n let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));\n let connector_req = wellsfargo::WellsfargoVoidRequest::try_from(&connector_router_data)?;\n\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&PaymentsVoidType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsVoidType::get_headers(self, req, connectors)?)\n .set_body(self.get_request_body(req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCancelRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoPaymentsResponse = res\n .response\n .parse_struct(\"Wellsfargo PaymentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n\n fn get_5xx_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoServerErrorResponse = res\n .response\n .parse_struct(\"WellsfargoServerErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|event| event.set_response_body(&response));\n router_env::logger::info!(error_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n reason: response.status.clone(),\n code: response\n .status\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),\n message: response\n .message\n .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl Refund for Wellsfargo {}\nimpl RefundExecute for Wellsfargo {}\nimpl RefundSync for Wellsfargo {}\n\nimpl ConnectorIntegration for Wellsfargo {\n fn get_headers(\n &self,\n req: &RefundExecuteRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &RefundExecuteRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}pts/v2/payments/{}/refunds\",\n self.base_url(connectors),\n connector_payment_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RefundExecuteRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_converter,\n MinorUnit::new(req.request.refund_amount),\n req.request.currency,\n )?;\n\n let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));\n let connector_req = wellsfargo::WellsfargoRefundRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n fn build_request(\n &self,\n req: &RefundExecuteRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(RefundExecuteType::get_headers(self, req, connectors)?)\n .set_body(self.get_request_body(req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundExecuteRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoRefundResponse = res\n .response\n .parse_struct(\"Wellsfargo RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Wellsfargo {\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n fn get_http_method(&self) -> Method {\n Method::Get\n }\n fn get_url(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let refund_id = req.request.get_connector_refund_id()?;\n Ok(format!(\n \"{}tss/v2/transactions/{}\",\n self.base_url(connectors),\n refund_id\n ))\n }\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Get)\n .url(&RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(RefundSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: wellsfargo::WellsfargoRsyncResponse = res\n .response\n .parse_struct(\"Wellsfargo RefundSyncResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl\n ConnectorIntegration<\n IncrementalAuthorization,\n PaymentsIncrementalAuthorizationData,\n PaymentsResponseData,\n > for Wellsfargo\n{\n fn get_headers(\n &self,\n req: &PaymentsIncrementalAuthorizationRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_http_method(&self) -> Method {\n Method::Patch\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n req: &PaymentsIncrementalAuthorizationRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let connector_payment_id = req.request.connector_transaction_id.clone();\n Ok(format!(\n \"{}pts/v2/payments/{}\",\n self.base_url(connectors),\n connector_payment_id\n ))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsIncrementalAuthorizationRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = convert_amount(\n self.amount_converter,\n MinorUnit::new(req.request.additional_amount),\n req.request.currency,\n )?;\n\n let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));\n let connector_request =\n wellsfargo::WellsfargoPaymentsIncrementalAuthorizationRequest::try_from(\n &connector_router_data,\n )?;\n Ok(RequestContent::Json(Box::new(connector_request)))\n }\n fn build_request(\n &self,\n req: &PaymentsIncrementalAuthorizationRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Patch)\n .url(&IncrementalAuthorizationType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(IncrementalAuthorizationType::get_headers(\n self, req, connectors,\n )?)\n .set_body(IncrementalAuthorizationType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &PaymentsIncrementalAuthorizationRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult<\n RouterData<\n IncrementalAuthorization,\n PaymentsIncrementalAuthorizationData,\n PaymentsResponseData,\n >,\n errors::ConnectorError,\n > {\n let response: wellsfargo::WellsfargoPaymentsIncrementalAuthorizationResponse = res\n .response\n .parse_struct(\"Wellsfargo PaymentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Wellsfargo {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic WELLSFARGO_SUPPORTED_PAYMENT_METHODS: LazyLock =\n LazyLock::new(|| {\n let supported_capture_methods = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::Manual,\n enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let supported_card_network = vec![\n common_enums::CardNetwork::AmericanExpress,\n common_enums::CardNetwork::Discover,\n common_enums::CardNetwork::Mastercard,\n common_enums::CardNetwork::Visa,\n ];\n\n let mut wellsfargo_supported_payment_methods = SupportedPaymentMethods::new();\n\n wellsfargo_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Credit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n wellsfargo_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Debit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n wellsfargo_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n enums::PaymentMethodType::GooglePay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n wellsfargo_supported_payment_methods.add(\n enums::PaymentMethod::Wallet,\n enums::PaymentMethodType::ApplePay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::Supported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n wellsfargo_supported_payment_methods.add(\n enums::PaymentMethod::BankDebit,\n enums::PaymentMethodType::Ach,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n wellsfargo_supported_payment_methods\n });\n\nstatic WELLSFARGO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Wells Fargo\",\n description:\n \"Wells Fargo is a major bank offering retail, commercial, and wealth management services\",\n connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,\n integration_status: enums::ConnectorIntegrationStatus::Beta,\n};\n\nstatic WELLSFARGO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];\n\nimpl ConnectorSpecifications for Wellsfargo {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&WELLSFARGO_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*WELLSFARGO_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&WELLSFARGO_SUPPORTED_WEBHOOK_FLOWS)\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__wise__transformers.rs", "text": "#[cfg(feature = \"payouts\")]\nuse api_models::payouts::Bank;\n#[cfg(feature = \"payouts\")]\nuse api_models::payouts::PayoutMethodData;\n#[cfg(feature = \"payouts\")]\nuse common_enums::PayoutEntityType;\n#[cfg(feature = \"payouts\")]\nuse common_enums::{CountryAlpha2, PayoutStatus, PayoutType};\n#[cfg(feature = \"payouts\")]\nuse common_utils::pii::Email;\nuse common_utils::types::FloatMajorUnit;\nuse hyperswitch_domain_models::router_data::ConnectorAuthType;\n#[cfg(feature = \"payouts\")]\nuse hyperswitch_domain_models::types::{PayoutsResponseData, PayoutsRouterData};\nuse hyperswitch_interfaces::errors::ConnectorError;\nuse masking::Secret;\nuse serde::{Deserialize, Serialize};\n\n#[cfg(feature = \"payouts\")]\nuse crate::types::PayoutsResponseRouterData;\n#[cfg(feature = \"payouts\")]\nuse crate::utils::get_unimplemented_payment_method_error_message;\n#[cfg(feature = \"payouts\")]\nuse crate::utils::{PayoutsData as _, RouterData as _};\n\ntype Error = error_stack::Report;\n\n#[derive(Debug, Serialize)]\npub struct WiseRouterData {\n pub amount: FloatMajorUnit,\n pub router_data: T,\n}\n\nimpl From<(FloatMajorUnit, T)> for WiseRouterData {\n fn from((amount, router_data): (FloatMajorUnit, T)) -> Self {\n Self {\n amount,\n router_data,\n }\n }\n}\n\npub struct WiseAuthType {\n pub(super) api_key: Secret,\n #[allow(dead_code)]\n pub(super) profile_id: Secret,\n}\n\nimpl TryFrom<&ConnectorAuthType> for WiseAuthType {\n type Error = Error;\n fn try_from(auth_type: &ConnectorAuthType) -> Result {\n match auth_type {\n ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {\n api_key: api_key.to_owned(),\n profile_id: key1.to_owned(),\n }),\n _ => Err(ConnectorError::FailedToObtainAuthType)?,\n }\n }\n}\n\n// Wise error response\n#[derive(Debug, Deserialize, Serialize)]\npub struct ErrorResponse {\n pub timestamp: Option,\n pub errors: Option>,\n pub status: Option,\n pub error: Option,\n pub error_description: Option,\n pub message: Option,\n pub path: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize)]\n#[serde(untagged)]\npub enum WiseHttpStatus {\n String(String),\n Number(u16),\n}\n\nimpl Default for WiseHttpStatus {\n fn default() -> Self {\n Self::String(\"\".to_string())\n }\n}\n\nimpl WiseHttpStatus {\n pub fn get_status(&self) -> String {\n match self {\n Self::String(val) => val.clone(),\n Self::Number(val) => val.to_string(),\n }\n }\n}\n\n#[derive(Debug, Deserialize, Serialize)]\npub struct SubError {\n pub code: String,\n pub message: String,\n pub path: Option,\n pub field: Option,\n}\n\n// Payouts\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WiseRecipientCreateRequest {\n currency: String,\n #[serde(rename = \"type\")]\n recipient_type: RecipientType,\n profile: Secret,\n account_holder_name: Secret,\n details: WiseBankDetails,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"snake_case\")]\n#[allow(dead_code)]\npub enum RecipientType {\n Aba,\n Iban,\n SortCode,\n SwiftCode,\n}\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum AccountType {\n Checking,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WiseBankDetails {\n legal_type: LegalType,\n account_type: Option,\n address: Option,\n post_code: Option,\n nationality: Option,\n account_holder_name: Option>,\n email: Option,\n account_number: Option>,\n city: Option,\n sort_code: Option>,\n iban: Option>,\n bic: Option>,\n transit_number: Option>,\n routing_number: Option>,\n abartn: Option>,\n swift_code: Option>,\n payin_reference: Option,\n psp_reference: Option,\n tax_id: Option,\n order_id: Option,\n job: Option,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Serialize, Deserialize)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum LegalType {\n Business,\n #[default]\n Private,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WiseAddressDetails {\n country: Option,\n country_code: Option,\n first_line: Option>,\n post_code: Option>,\n city: Option,\n state: Option>,\n}\n\n#[allow(dead_code)]\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WiseRecipientCreateResponse {\n id: i64,\n business: Option,\n profile: Option,\n account_holder_name: Secret,\n currency: String,\n country: String,\n #[serde(rename = \"type\")]\n request_type: String,\n details: Option,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WisePayoutQuoteRequest {\n source_currency: String,\n target_currency: String,\n source_amount: Option,\n target_amount: Option,\n pay_out: WisePayOutOption,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Serialize, Deserialize)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum WisePayOutOption {\n Balance,\n #[default]\n BankTransfer,\n Swift,\n SwiftOur,\n Interac,\n}\n\n#[allow(dead_code)]\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WisePayoutQuoteResponse {\n source_amount: f64,\n client_id: String,\n id: String,\n status: WiseStatus,\n profile: i64,\n rate: Option,\n source_currency: Option,\n target_currency: Option,\n user: Option,\n rate_type: Option,\n pay_out: Option,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Deserialize, Serialize)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum WiseRateType {\n #[default]\n Fixed,\n Floating,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WisePayoutCreateRequest {\n target_account: i64,\n quote_uuid: String,\n customer_transaction_id: String,\n details: WiseTransferDetails,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WiseTransferDetails {\n transfer_purpose: Option,\n source_of_funds: Option,\n transfer_purpose_sub_transfer_purpose: Option,\n}\n\n#[allow(dead_code)]\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WisePayoutResponse {\n id: i64,\n user: i64,\n target_account: i64,\n source_account: Option,\n quote_uuid: String,\n status: WiseStatus,\n reference: Option,\n rate: Option,\n business: Option,\n details: Option,\n has_active_issues: Option,\n source_currency: Option,\n source_value: Option,\n target_currency: Option,\n target_value: Option,\n customer_transaction_id: Option,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WisePayoutFulfillRequest {\n #[serde(rename = \"type\")]\n fund_type: FundType,\n}\n\n// NOTE - Only balance is allowed as time of incorporating this field - https://api-docs.transferwise.com/api-reference/transfer#fund\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Serialize)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum FundType {\n #[default]\n Balance,\n}\n\n#[allow(dead_code)]\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct WiseFulfillResponse {\n status: WiseStatus,\n error_code: Option,\n error_message: Option,\n balance_transaction_id: Option,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Default, Clone, Serialize, Deserialize)]\n#[serde(rename_all = \"UPPERCASE\")]\npub enum WiseStatus {\n Completed,\n Pending,\n Rejected,\n\n #[serde(rename = \"cancelled\")]\n Cancelled,\n\n #[serde(rename = \"processing\")]\n #[default]\n Processing,\n\n #[serde(rename = \"incoming_payment_waiting\")]\n IncomingPaymentWaiting,\n}\n\n#[cfg(feature = \"payouts\")]\nfn get_payout_address_details(\n address: Option<&hyperswitch_domain_models::address::Address>,\n) -> Option {\n address.and_then(|add| {\n add.address.as_ref().map(|a| WiseAddressDetails {\n country: a.country,\n country_code: a.country,\n first_line: a.line1.clone(),\n post_code: a.zip.clone(),\n city: a.city.clone(),\n state: a.state.clone(),\n })\n })\n}\n\n#[cfg(feature = \"payouts\")]\nfn get_payout_bank_details(\n payout_method_data: PayoutMethodData,\n address: Option<&hyperswitch_domain_models::address::Address>,\n entity_type: PayoutEntityType,\n) -> Result {\n let wise_address_details = match get_payout_address_details(address) {\n Some(a) => Ok(a),\n None => Err(ConnectorError::MissingRequiredField {\n field_name: \"address\",\n }),\n }?;\n match payout_method_data {\n PayoutMethodData::Bank(Bank::Ach(b)) => Ok(WiseBankDetails {\n legal_type: LegalType::from(entity_type),\n address: Some(wise_address_details),\n account_number: Some(b.bank_account_number.to_owned()),\n abartn: Some(b.bank_routing_number),\n account_type: Some(AccountType::Checking),\n ..WiseBankDetails::default()\n }),\n PayoutMethodData::Bank(Bank::Bacs(b)) => Ok(WiseBankDetails {\n legal_type: LegalType::from(entity_type),\n address: Some(wise_address_details),\n account_number: Some(b.bank_account_number.to_owned()),\n sort_code: Some(b.bank_sort_code),\n ..WiseBankDetails::default()\n }),\n PayoutMethodData::Bank(Bank::Sepa(b)) => Ok(WiseBankDetails {\n legal_type: LegalType::from(entity_type),\n address: Some(wise_address_details),\n iban: Some(b.iban.to_owned()),\n bic: b.bic,\n ..WiseBankDetails::default()\n }),\n _ => Err(ConnectorError::NotImplemented(\n get_unimplemented_payment_method_error_message(\"Wise\"),\n ))?,\n }\n}\n\n// Payouts recipient create request transform\n#[cfg(feature = \"payouts\")]\nimpl TryFrom<&WiseRouterData<&PayoutsRouterData>> for WiseRecipientCreateRequest {\n type Error = Error;\n fn try_from(item_data: &WiseRouterData<&PayoutsRouterData>) -> Result {\n let item = item_data.router_data;\n let request = item.request.to_owned();\n let customer_details = request.customer_details.to_owned();\n let payout_method_data = item.get_payout_method_data()?;\n let bank_details = get_payout_bank_details(\n payout_method_data.to_owned(),\n item.get_optional_billing(),\n item.request.entity_type,\n )?;\n let source_id = match item.connector_auth_type.to_owned() {\n ConnectorAuthType::BodyKey { api_key: _, key1 } => Ok(key1),\n _ => Err(ConnectorError::MissingRequiredField {\n field_name: \"source_id for PayoutRecipient creation\",\n }),\n }?;\n let payout_type = request.get_payout_type()?;\n match payout_type {\n PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {\n Err(ConnectorError::NotImplemented(\n get_unimplemented_payment_method_error_message(\"Wise\"),\n ))?\n }\n PayoutType::Bank => {\n let account_holder_name = customer_details\n .ok_or(ConnectorError::MissingRequiredField {\n field_name: \"customer_details for PayoutRecipient creation\",\n })?\n .name\n .ok_or(ConnectorError::MissingRequiredField {\n field_name: \"customer_details.name for PayoutRecipient creation\",\n })?;\n Ok(Self {\n profile: source_id,\n currency: request.destination_currency.to_string(),\n recipient_type: RecipientType::try_from(payout_method_data)?,\n account_holder_name,\n details: bank_details,\n })\n }\n }\n }\n}\n\n// Payouts recipient fulfill response transform\n#[cfg(feature = \"payouts\")]\nimpl TryFrom>\n for PayoutsRouterData\n{\n type Error = Error;\n fn try_from(\n item: PayoutsResponseRouterData,\n ) -> Result {\n let response: WiseRecipientCreateResponse = item.response;\n\n Ok(Self {\n response: Ok(PayoutsResponseData {\n status: Some(PayoutStatus::RequiresCreation),\n connector_payout_id: Some(response.id.to_string()),\n payout_eligible: None,\n should_add_next_step_to_process_tracker: false,\n error_code: None,\n error_message: None,\n payout_connector_metadata: None,\n }),\n ..item.data\n })\n }\n}\n\n// Payouts quote request transform\n#[cfg(feature = \"payouts\")]\nimpl TryFrom<&WiseRouterData<&PayoutsRouterData>> for WisePayoutQuoteRequest {\n type Error = Error;\n fn try_from(item_data: &WiseRouterData<&PayoutsRouterData>) -> Result {\n let item = item_data.router_data;\n let request = item.request.to_owned();\n let payout_type = request.get_payout_type()?;\n match payout_type {\n PayoutType::Bank => Ok(Self {\n source_amount: Some(item_data.amount),\n source_currency: request.source_currency.to_string(),\n target_amount: None,\n target_currency: request.destination_currency.to_string(),\n pay_out: WisePayOutOption::default(),\n }),\n PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {\n Err(ConnectorError::NotImplemented(\n get_unimplemented_payment_method_error_message(\"Wise\"),\n ))?\n }\n }\n }\n}\n\n// Payouts quote response transform\n#[cfg(feature = \"payouts\")]\nimpl TryFrom> for PayoutsRouterData {\n type Error = Error;\n fn try_from(\n item: PayoutsResponseRouterData,\n ) -> Result {\n let response: WisePayoutQuoteResponse = item.response;\n\n Ok(Self {\n response: Ok(PayoutsResponseData {\n status: Some(PayoutStatus::RequiresCreation),\n connector_payout_id: Some(response.id),\n payout_eligible: None,\n should_add_next_step_to_process_tracker: false,\n error_code: None,\n error_message: None,\n payout_connector_metadata: None,\n }),\n ..item.data\n })\n }\n}\n\n// Payouts transfer creation request\n#[cfg(feature = \"payouts\")]\nimpl TryFrom<&PayoutsRouterData> for WisePayoutCreateRequest {\n type Error = Error;\n fn try_from(item: &PayoutsRouterData) -> Result {\n let request = item.request.to_owned();\n let payout_type = request.get_payout_type()?;\n match payout_type {\n PayoutType::Bank => {\n let connector_customer_id = item.get_connector_customer_id()?;\n let quote_uuid = item.get_quote_id()?;\n let wise_transfer_details = WiseTransferDetails {\n transfer_purpose: None,\n source_of_funds: None,\n transfer_purpose_sub_transfer_purpose: None,\n };\n let target_account: i64 = connector_customer_id.trim().parse().map_err(|_| {\n ConnectorError::MissingRequiredField {\n field_name: \"profile\",\n }\n })?;\n Ok(Self {\n target_account,\n quote_uuid,\n customer_transaction_id: uuid::Uuid::new_v4().to_string(),\n details: wise_transfer_details,\n })\n }\n PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {\n Err(ConnectorError::NotImplemented(\n get_unimplemented_payment_method_error_message(\"Wise\"),\n ))?\n }\n }\n }\n}\n\n// Payouts transfer creation response\n#[cfg(feature = \"payouts\")]\nimpl TryFrom> for PayoutsRouterData {\n type Error = Error;\n fn try_from(\n item: PayoutsResponseRouterData,\n ) -> Result {\n let response: WisePayoutResponse = item.response;\n let status = match PayoutStatus::from(response.status) {\n PayoutStatus::Cancelled => PayoutStatus::Cancelled,\n _ => PayoutStatus::RequiresFulfillment,\n };\n\n Ok(Self {\n response: Ok(PayoutsResponseData {\n status: Some(status),\n connector_payout_id: Some(response.id.to_string()),\n payout_eligible: None,\n should_add_next_step_to_process_tracker: false,\n error_code: None,\n error_message: None,\n payout_connector_metadata: None,\n }),\n ..item.data\n })\n }\n}\n\n// Payouts fulfill request transform\n#[cfg(feature = \"payouts\")]\nimpl TryFrom<&PayoutsRouterData> for WisePayoutFulfillRequest {\n type Error = Error;\n fn try_from(item: &PayoutsRouterData) -> Result {\n let payout_type = item.request.get_payout_type()?;\n match payout_type {\n PayoutType::Bank => Ok(Self {\n fund_type: FundType::default(),\n }),\n PayoutType::Card | PayoutType::Wallet | PayoutType::BankRedirect => {\n Err(ConnectorError::NotImplemented(\n get_unimplemented_payment_method_error_message(\"Wise\"),\n ))?\n }\n }\n }\n}\n\n// Payouts fulfill response transform\n#[cfg(feature = \"payouts\")]\nimpl TryFrom> for PayoutsRouterData {\n type Error = Error;\n fn try_from(\n item: PayoutsResponseRouterData,\n ) -> Result {\n let response: WiseFulfillResponse = item.response;\n\n Ok(Self {\n response: Ok(PayoutsResponseData {\n status: Some(PayoutStatus::from(response.status)),\n connector_payout_id: Some(\n item.data\n .request\n .connector_payout_id\n .clone()\n .ok_or(ConnectorError::MissingConnectorTransactionID)?,\n ),\n payout_eligible: None,\n should_add_next_step_to_process_tracker: false,\n error_code: None,\n error_message: None,\n payout_connector_metadata: None,\n }),\n ..item.data\n })\n }\n}\n\n#[cfg(feature = \"payouts\")]\nimpl From for PayoutStatus {\n fn from(wise_status: WiseStatus) -> Self {\n match wise_status {\n WiseStatus::Completed => Self::Initiated,\n WiseStatus::Rejected => Self::Failed,\n WiseStatus::Cancelled => Self::Cancelled,\n WiseStatus::Pending | WiseStatus::Processing | WiseStatus::IncomingPaymentWaiting => {\n Self::Pending\n }\n }\n }\n}\n\n#[cfg(feature = \"payouts\")]\nimpl From for LegalType {\n fn from(entity_type: PayoutEntityType) -> Self {\n match entity_type {\n PayoutEntityType::Individual\n | PayoutEntityType::Personal\n | PayoutEntityType::NonProfit\n | PayoutEntityType::NaturalPerson => Self::Private,\n PayoutEntityType::Company\n | PayoutEntityType::PublicSector\n | PayoutEntityType::Business => Self::Business,\n }\n }\n}\n\n#[cfg(feature = \"payouts\")]\nimpl TryFrom for RecipientType {\n type Error = error_stack::Report;\n fn try_from(payout_method_type: PayoutMethodData) -> Result {\n match payout_method_type {\n PayoutMethodData::Bank(Bank::Ach(_)) => Ok(Self::Aba),\n PayoutMethodData::Bank(Bank::Bacs(_)) => Ok(Self::SortCode),\n PayoutMethodData::Bank(Bank::Sepa(_)) => Ok(Self::Iban),\n _ => Err(ConnectorError::NotImplemented(\n get_unimplemented_payment_method_error_message(\"Wise\"),\n )\n .into()),\n }\n }\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\npub struct WisePayoutSyncResponse {\n id: u64,\n status: WiseSyncStatus,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub enum WiseSyncStatus {\n IncomingPaymentWaiting,\n IncomingPaymentInitiated,\n Processing,\n FundsConverted,\n OutgoingPaymentSent,\n Cancelled,\n FundsRefunded,\n BouncedBack,\n ChargedBack,\n Unknown,\n}\n\n#[cfg(feature = \"payouts\")]\nimpl TryFrom> for PayoutsRouterData {\n type Error = Error;\n fn try_from(\n item: PayoutsResponseRouterData,\n ) -> Result {\n Ok(Self {\n response: Ok(PayoutsResponseData {\n status: Some(PayoutStatus::from(item.response.status)),\n connector_payout_id: Some(item.response.id.to_string()),\n payout_eligible: None,\n should_add_next_step_to_process_tracker: false,\n error_code: None,\n error_message: None,\n payout_connector_metadata: None,\n }),\n ..item.data\n })\n }\n}\n\n#[cfg(feature = \"payouts\")]\nimpl From for PayoutStatus {\n fn from(status: WiseSyncStatus) -> Self {\n match status {\n WiseSyncStatus::IncomingPaymentWaiting => Self::Pending,\n WiseSyncStatus::IncomingPaymentInitiated => Self::Pending,\n WiseSyncStatus::Processing => Self::Pending,\n WiseSyncStatus::FundsConverted => Self::Pending,\n WiseSyncStatus::OutgoingPaymentSent => Self::Success,\n WiseSyncStatus::Cancelled => Self::Cancelled,\n WiseSyncStatus::FundsRefunded => Self::Reversed,\n WiseSyncStatus::BouncedBack => Self::Pending,\n WiseSyncStatus::ChargedBack => Self::Reversed,\n WiseSyncStatus::Unknown => Self::Ineligible,\n }\n }\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\npub struct WisePayoutsWebhookBody {\n pub data: WisePayoutsWebhookData,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\npub struct WisePayoutsWebhookData {\n pub resource: WisePayoutsWebhookResource,\n pub current_state: WiseSyncStatus,\n}\n\n#[cfg(feature = \"payouts\")]\n#[derive(Debug, Deserialize, Serialize)]\npub struct WisePayoutsWebhookResource {\n pub id: u64,\n}\n\n#[cfg(feature = \"payouts\")]\nimpl From for WisePayoutSyncResponse {\n fn from(data: WisePayoutsWebhookData) -> Self {\n Self {\n id: data.resource.id,\n status: data.current_state,\n }\n }\n}\n\n#[cfg(feature = \"payouts\")]\npub fn get_wise_webhooks_event(\n state: WiseSyncStatus,\n) -> api_models::webhooks::IncomingWebhookEvent {\n match state {\n WiseSyncStatus::IncomingPaymentWaiting => {\n api_models::webhooks::IncomingWebhookEvent::PayoutProcessing\n }\n WiseSyncStatus::IncomingPaymentInitiated => {\n api_models::webhooks::IncomingWebhookEvent::PayoutProcessing\n }\n WiseSyncStatus::Processing => api_models::webhooks::IncomingWebhookEvent::PayoutProcessing,\n WiseSyncStatus::FundsConverted => {\n api_models::webhooks::IncomingWebhookEvent::PayoutProcessing\n }\n WiseSyncStatus::OutgoingPaymentSent => {\n api_models::webhooks::IncomingWebhookEvent::PayoutSuccess\n }\n WiseSyncStatus::Cancelled => api_models::webhooks::IncomingWebhookEvent::PayoutCancelled,\n WiseSyncStatus::FundsRefunded => api_models::webhooks::IncomingWebhookEvent::PayoutReversed,\n WiseSyncStatus::BouncedBack => api_models::webhooks::IncomingWebhookEvent::PayoutProcessing,\n WiseSyncStatus::ChargedBack => api_models::webhooks::IncomingWebhookEvent::PayoutReversed,\n WiseSyncStatus::Unknown => api_models::webhooks::IncomingWebhookEvent::EventNotSupported,\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__worldline.rs", "text": "pub mod transformers;\n\nuse std::{fmt::Debug, sync::LazyLock};\n\nuse base64::Engine;\nuse common_enums::enums;\nuse common_utils::{\n consts, crypto,\n errors::CustomResult,\n ext_traits::{ByteSliceExt, OptionExt},\n request::{Method, Request, RequestBuilder, RequestContent},\n};\nuse error_stack::ResultExt;\nuse hyperswitch_domain_models::{\n router_data::{AccessToken, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n },\n router_request_types::{\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsSyncRouterData,\n RefundSyncRouterData, RefundsRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation, PaymentCapture, PaymentSync,\n },\n configs::Connectors,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{\n PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,\n RefundExecuteType, RefundSyncType, Response,\n },\n webhooks::{self, IncomingWebhookFlowError},\n};\nuse masking::{ExposeInterface, Mask, PeekInterface};\nuse ring::hmac;\nuse router_env::logger;\nuse time::{format_description, OffsetDateTime};\nuse transformers as worldline;\n\nuse crate::{\n constants::headers,\n types::ResponseRouterData,\n utils::{self, RefundsRequestData as _},\n};\n\n#[derive(Debug, Clone)]\npub struct Worldline;\n\nimpl Worldline {\n pub fn generate_authorization_token(\n &self,\n auth: worldline::WorldlineAuthType,\n http_method: Method,\n content_type: &str,\n date: &str,\n endpoint: &str,\n ) -> CustomResult {\n let signature_data: String = format!(\n \"{}\\n{}\\n{}\\n/{}\\n\",\n http_method,\n content_type.trim(),\n date.trim(),\n endpoint.trim()\n );\n let worldline::WorldlineAuthType {\n api_key,\n api_secret,\n ..\n } = auth;\n let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes());\n let signed_data = consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_data.as_bytes()));\n\n Ok(format!(\"GCS v1HMAC:{}:{signed_data}\", api_key.peek()))\n }\n\n pub fn get_current_date_time() -> CustomResult {\n let format = format_description::parse(\n \"[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT\",\n )\n .change_context(errors::ConnectorError::InvalidDateFormat)?;\n OffsetDateTime::now_utc()\n .format(&format)\n .change_context(errors::ConnectorError::InvalidDateFormat)\n }\n}\n\nimpl ConnectorCommonExt for Worldline\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n let base_url = self.base_url(connectors);\n let url = Self::get_url(self, req, connectors)?;\n let endpoint = url.replace(base_url, \"\");\n let http_method = Self::get_http_method(self);\n let auth = worldline::WorldlineAuthType::try_from(&req.connector_auth_type)?;\n let date = Self::get_current_date_time()?;\n let content_type = Self::get_content_type(self);\n let signed_data: String =\n self.generate_authorization_token(auth, http_method, content_type, &date, &endpoint)?;\n\n Ok(vec![\n (headers::DATE.to_string(), date.into()),\n (\n headers::AUTHORIZATION.to_string(),\n signed_data.into_masked(),\n ),\n (\n headers::CONTENT_TYPE.to_string(),\n content_type.to_string().into(),\n ),\n ])\n }\n}\n\nimpl ConnectorCommon for Worldline {\n fn id(&self) -> &'static str {\n \"worldline\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Minor\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.worldline.base_url.as_ref()\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: worldline::ErrorResponse = res\n .response\n .parse_struct(\"Worldline ErrorResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_error_response_body(&response));\n logger::info!(connector_response=?response);\n\n let error = response.errors.into_iter().next().unwrap_or_default();\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: error\n .code\n .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),\n message: error\n .message\n .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),\n ..Default::default()\n })\n }\n}\n\nimpl ConnectorValidation for Worldline {}\n\nimpl api::ConnectorAccessToken for Worldline {}\n\nimpl ConnectorIntegration for Worldline {}\n\nimpl api::Payment for Worldline {}\n\nimpl api::MandateSetup for Worldline {}\nimpl ConnectorIntegration\n for Worldline\n{\n fn build_request(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Err(\n errors::ConnectorError::NotImplemented(\"Setup Mandate flow for Worldline\".to_string())\n .into(),\n )\n }\n}\n\nimpl api::PaymentToken for Worldline {}\n\nimpl ConnectorIntegration\n for Worldline\n{\n // Not Implemented (R)\n}\n\nimpl api::PaymentVoid for Worldline {}\n\nimpl ConnectorIntegration for Worldline {\n fn get_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let base_url = self.base_url(connectors);\n let auth: worldline::WorldlineAuthType =\n worldline::WorldlineAuthType::try_from(&req.connector_auth_type)?;\n let merchant_account_id = auth.merchant_account_id.expose();\n let payment_id = &req.request.connector_transaction_id;\n Ok(format!(\n \"{base_url}v1/{merchant_account_id}/payments/{payment_id}/cancel\",\n ))\n }\n\n fn build_request(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(PaymentsVoidType::get_http_method(self))\n .url(&PaymentsVoidType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsVoidType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCancelRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: worldline::PaymentResponse = res\n .response\n .parse_struct(\"Worldline PaymentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl PaymentSync for Worldline {}\nimpl ConnectorIntegration for Worldline {\n fn get_http_method(&self) -> Method {\n Method::Get\n }\n\n fn get_content_type(&self) -> &'static str {\n \"\"\n }\n\n fn get_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let payment_id = req\n .request\n .connector_transaction_id\n .get_connector_transaction_id()\n .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;\n let base_url = self.base_url(connectors);\n let auth = worldline::WorldlineAuthType::try_from(&req.connector_auth_type)?;\n let merchant_account_id = auth.merchant_account_id.expose();\n Ok(format!(\n \"{base_url}v1/{merchant_account_id}/payments/{payment_id}\"\n ))\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(PaymentsSyncType::get_http_method(self))\n .url(&PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n logger::debug!(payment_sync_response=?res);\n let mut response: worldline::Payment = res\n .response\n .parse_struct(\"Worldline Payment\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n response.capture_method = data.request.capture_method.unwrap_or_default();\n\n event_builder.map(|i| i.set_response_body(&response));\n logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n}\n\nimpl PaymentCapture for Worldline {}\nimpl ConnectorIntegration for Worldline {\n fn get_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let payment_id = req.request.connector_transaction_id.clone();\n let base_url = self.base_url(connectors);\n let auth = worldline::WorldlineAuthType::try_from(&req.connector_auth_type)?;\n let merchant_account_id = auth.merchant_account_id.expose();\n Ok(format!(\n \"{base_url}v1/{merchant_account_id}/payments/{payment_id}/approve\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = worldline::ApproveRequest::try_from(req)?;\n\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(PaymentsCaptureType::get_http_method(self))\n .url(&PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)\n .set_body(PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult<\n RouterData,\n errors::ConnectorError,\n >\n where\n Capture: Clone,\n PaymentsCaptureData: Clone,\n PaymentsResponseData: Clone,\n {\n logger::debug!(payment_capture_response=?res);\n let mut response: worldline::PaymentResponse = res\n .response\n .parse_struct(\"Worldline PaymentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n response.payment.capture_method = enums::CaptureMethod::Manual;\n\n event_builder.map(|i| i.set_response_body(&response));\n logger::info!(connector_response=?response);\n\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::PaymentSession for Worldline {}\n\nimpl ConnectorIntegration for Worldline {\n // Not Implemented\n}\n\nimpl api::PaymentAuthorize for Worldline {}\n\nimpl ConnectorIntegration for Worldline {\n fn get_headers(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let base_url = self.base_url(connectors);\n let auth = worldline::WorldlineAuthType::try_from(&req.connector_auth_type)?;\n let merchant_account_id = auth.merchant_account_id.expose();\n Ok(format!(\"{base_url}v1/{merchant_account_id}/payments\"))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_router_data = worldline::WorldlineRouterData::try_from((\n &self.get_currency_unit(),\n req.request.currency,\n req.request.amount,\n req,\n ))?;\n let connector_req = worldline::PaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(PaymentsAuthorizeType::get_http_method(self))\n .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)\n .set_body(PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n logger::debug!(payment_authorize_response=?res);\n let mut response: worldline::PaymentResponse = res\n .response\n .parse_struct(\"Worldline PaymentResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n response.payment.capture_method = data.request.capture_method.unwrap_or_default();\n event_builder.map(|i| i.set_response_body(&response));\n logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl api::Refund for Worldline {}\nimpl api::RefundExecute for Worldline {}\nimpl api::RefundSync for Worldline {}\n\nimpl ConnectorIntegration for Worldline {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let payment_id = req.request.connector_transaction_id.clone();\n let base_url = self.base_url(connectors);\n let auth = worldline::WorldlineAuthType::try_from(&req.connector_auth_type)?;\n let merchant_account_id = auth.merchant_account_id.expose();\n Ok(format!(\n \"{base_url}v1/{merchant_account_id}/payments/{payment_id}/refund\"\n ))\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = worldline::WorldlineRefundRequest::try_from(req)?;\n Ok(RequestContent::Json(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(RefundExecuteType::get_http_method(self))\n .url(&RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(RefundExecuteType::get_headers(self, req, connectors)?)\n .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n logger::debug!(target: \"router::connector::worldline\", response=?res);\n let response: worldline::RefundResponse = res\n .response\n .parse_struct(\"Worldline RefundResponse\")\n .change_context(errors::ConnectorError::RequestEncodingFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Worldline {\n fn get_http_method(&self) -> Method {\n Method::Get\n }\n\n fn get_content_type(&self) -> &'static str {\n \"\"\n }\n\n fn get_headers(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_url(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n let refund_id = req.request.get_connector_refund_id()?;\n let base_url = self.base_url(connectors);\n let auth: worldline::WorldlineAuthType =\n worldline::WorldlineAuthType::try_from(&req.connector_auth_type)?;\n let merchant_account_id = auth.merchant_account_id.expose();\n Ok(format!(\n \"{base_url}v1/{merchant_account_id}/refunds/{refund_id}/\"\n ))\n }\n\n fn build_request(\n &self,\n req: &RefundSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(RefundSyncType::get_http_method(self))\n .url(&RefundSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(RefundSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &RefundSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n logger::debug!(target: \"router::connector::worldline\", response=?res);\n let response: worldline::RefundResponse = res\n .response\n .parse_struct(\"Worldline RefundResponse\")\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n .change_context(errors::ConnectorError::ResponseHandlingFailed)\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nfn is_endpoint_verification(headers: &actix_web::http::header::HeaderMap) -> bool {\n headers\n .get(\"x-gcs-webhooks-endpoint-verification\")\n .is_some()\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Worldline {\n fn get_webhook_source_verification_algorithm(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Box::new(crypto::HmacSha256))\n }\n\n fn get_webhook_source_verification_signature(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n let header_value = utils::get_header_key_value(\"X-GCS-Signature\", request.headers)?;\n let signature = consts::BASE64_ENGINE\n .decode(header_value.as_bytes())\n .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;\n Ok(signature)\n }\n\n fn get_webhook_source_verification_message(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _merchant_id: &common_utils::id_type::MerchantId,\n _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(request.body.to_vec())\n }\n\n fn get_webhook_object_reference_id(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n || -> _ {\n Ok::<_, error_stack::Report>(\n api_models::webhooks::ObjectReferenceId::PaymentId(\n api_models::payments::PaymentIdType::ConnectorTransactionId(\n request\n .body\n .parse_struct::(\"WorldlineWebhookEvent\")?\n .payment\n .parse_value::(\"WorldlineWebhookObjectId\")?\n .id,\n ),\n ),\n )\n }()\n .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)\n }\n\n fn get_webhook_event_type(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n if is_endpoint_verification(request.headers) {\n Ok(api_models::webhooks::IncomingWebhookEvent::EndpointVerification)\n } else {\n let details: worldline::WebhookBody = request\n .body\n .parse_struct(\"WorldlineWebhookObjectId\")\n .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;\n let event = match details.event_type {\n worldline::WebhookEvent::Paid => {\n api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess\n }\n worldline::WebhookEvent::Rejected | worldline::WebhookEvent::RejectedCapture => {\n api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure\n }\n worldline::WebhookEvent::Unknown => {\n api_models::webhooks::IncomingWebhookEvent::EventNotSupported\n }\n };\n Ok(event)\n }\n }\n\n fn get_webhook_resource_object(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n let details = request\n .body\n .parse_struct::(\"WorldlineWebhookObjectId\")\n .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?\n .payment\n .ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)?;\n // Ideally this should be a strict type that has type information\n // PII information is likely being logged here when this response will be logged\n Ok(Box::new(details))\n }\n\n fn get_webhook_api_response(\n &self,\n request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _error_kind: Option,\n ) -> CustomResult<\n hyperswitch_domain_models::api::ApplicationResponse,\n errors::ConnectorError,\n > {\n let verification_header = request.headers.get(\"x-gcs-webhooks-endpoint-verification\");\n let response = match verification_header {\n None => hyperswitch_domain_models::api::ApplicationResponse::StatusOk,\n Some(header_value) => {\n let verification_signature_value = header_value\n .to_str()\n .change_context(errors::ConnectorError::WebhookResponseEncodingFailed)?\n .to_string();\n hyperswitch_domain_models::api::ApplicationResponse::TextPlain(\n verification_signature_value,\n )\n }\n };\n Ok(response)\n }\n}\n\nstatic WORLDLINE_SUPPORTED_PAYMENT_METHODS: LazyLock =\n LazyLock::new(|| {\n let supported_capture_methods = vec![\n enums::CaptureMethod::Automatic,\n enums::CaptureMethod::Manual,\n enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let supported_card_network = vec![\n common_enums::CardNetwork::AmericanExpress,\n common_enums::CardNetwork::Discover,\n common_enums::CardNetwork::Mastercard,\n common_enums::CardNetwork::Visa,\n ];\n\n let mut worldline_supported_payment_methods = SupportedPaymentMethods::new();\n\n worldline_supported_payment_methods.add(\n enums::PaymentMethod::BankRedirect,\n enums::PaymentMethodType::Giropay,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n worldline_supported_payment_methods.add(\n enums::PaymentMethod::BankRedirect,\n enums::PaymentMethodType::Ideal,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: None,\n },\n );\n\n worldline_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Credit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::Supported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n worldline_supported_payment_methods.add(\n enums::PaymentMethod::Card,\n enums::PaymentMethodType::Debit,\n PaymentMethodDetails {\n mandates: enums::FeatureStatus::NotSupported,\n refunds: enums::FeatureStatus::Supported,\n supported_capture_methods,\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::Supported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n worldline_supported_payment_methods\n });\n\nstatic WORLDLINE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Worldline\",\n description: \"Worldpay is an industry leading payments technology and solutions company with unique capabilities to power omni-commerce across the globe.r\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: enums::ConnectorIntegrationStatus::Sandbox,\n};\n\nstatic WORLDLINE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];\n\nimpl ConnectorSpecifications for Worldline {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&WORLDLINE_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*WORLDLINE_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&WORLDLINE_SUPPORTED_WEBHOOK_FLOWS)\n }\n}\n"} {"file_name": "crates__hyperswitch_connectors__src__connectors__zift.rs", "text": "pub mod transformers;\n\nuse std::sync::LazyLock;\n\nuse common_enums::enums;\nuse common_utils::{\n errors::CustomResult,\n request::{Method, Request, RequestBuilder, RequestContent},\n types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n payment_method_data::PaymentMethodData,\n router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},\n router_flow_types::{\n access_token_auth::AccessTokenAuth,\n payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},\n refunds::{Execute, RSync},\n },\n router_request_types::{\n AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,\n PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,\n RefundsData, SetupMandateRequestData,\n },\n router_response_types::{\n ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,\n SupportedPaymentMethods, SupportedPaymentMethodsExt,\n },\n types::{\n PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,\n PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,\n },\n};\nuse hyperswitch_interfaces::{\n api::{\n self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,\n ConnectorValidation,\n },\n configs::Connectors,\n errors,\n events::connector_api_logs::ConnectorEvent,\n types::{self, Response},\n webhooks,\n};\nuse transformers as zift;\n\nuse crate::{constants::headers, types::ResponseRouterData, utils};\n\n#[derive(Clone)]\npub struct Zift {\n amount_converter: &'static (dyn AmountConvertor + Sync),\n}\n\nimpl Zift {\n pub fn new() -> &'static Self {\n &Self {\n amount_converter: &StringMinorUnitForConnector,\n }\n }\n}\n\nimpl api::Payment for Zift {}\nimpl api::PaymentSession for Zift {}\nimpl api::ConnectorAccessToken for Zift {}\nimpl api::PaymentAuthorize for Zift {}\nimpl api::PaymentSync for Zift {}\nimpl api::PaymentCapture for Zift {}\nimpl api::PaymentVoid for Zift {}\nimpl api::Refund for Zift {}\nimpl api::RefundExecute for Zift {}\nimpl api::RefundSync for Zift {}\nimpl api::PaymentToken for Zift {}\nimpl api::MandateSetup for Zift {}\n\nimpl ConnectorIntegration for Zift {\n fn get_headers(\n &self,\n req: &SetupMandateRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &SetupMandateRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}gates/xurl\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &SetupMandateRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = zift::ZiftSetupMandateRequest::try_from(req)?;\n Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &SetupMandateRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::SetupMandateType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::SetupMandateType::get_headers(self, req, connectors)?)\n .set_body(types::SetupMandateType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &SetupMandateRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: zift::ZiftAuthPaymentsResponse = serde_urlencoded::from_bytes(&res.response)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration\n for Zift\n{\n // Not Implemented (R)\n}\n\nimpl ConnectorCommonExt for Zift\nwhere\n Self: ConnectorIntegration,\n{\n fn build_headers(\n &self,\n _req: &RouterData,\n _connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n Ok(vec![(\n headers::CONTENT_TYPE.to_string(),\n self.get_content_type().to_string().into(),\n )])\n }\n}\n\nimpl ConnectorCommon for Zift {\n fn id(&self) -> &'static str {\n \"zift\"\n }\n\n fn get_currency_unit(&self) -> api::CurrencyUnit {\n api::CurrencyUnit::Minor\n }\n\n fn common_get_content_type(&self) -> &'static str {\n \"application/x-www-form-urlencoded\"\n }\n\n fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {\n connectors.zift.base_url.as_ref()\n }\n\n fn get_auth_header(\n &self,\n _auth_type: &ConnectorAuthType,\n ) -> CustomResult)>, errors::ConnectorError> {\n Ok(vec![])\n }\n\n fn build_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n let response: zift::ZiftErrorResponse = serde_urlencoded::from_bytes(&res.response)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n\n Ok(ErrorResponse {\n status_code: res.status_code,\n code: response.response_code,\n message: response.response_message.clone(),\n reason: Some(response.response_message),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n}\n\nimpl ConnectorValidation for Zift {\n fn validate_mandate_payment(\n &self,\n _pm_type: Option,\n pm_data: PaymentMethodData,\n ) -> CustomResult<(), errors::ConnectorError> {\n let connector = self.id();\n match pm_data {\n PaymentMethodData::Card(_) => Ok(()),\n _ => Err(errors::ConnectorError::NotSupported {\n message: \" mandate payment\".to_string(),\n connector,\n }\n .into()),\n }\n }\n\n fn validate_psync_reference_id(\n &self,\n _data: &PaymentsSyncData,\n _is_three_ds: bool,\n _status: enums::AttemptStatus,\n _connector_meta_data: Option,\n ) -> CustomResult<(), errors::ConnectorError> {\n Ok(())\n }\n}\n\nimpl ConnectorIntegration for Zift {\n //TODO: implement sessions flow\n}\n\nimpl ConnectorIntegration for Zift {}\n\nimpl ConnectorIntegration for Zift {\n fn get_headers(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}gates/xurl\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsAuthorizeRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = zift::ZiftRouterData::from((amount, req));\n let connector_req = zift::ZiftPaymentsRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsAuthorizeRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsAuthorizeType::get_url(\n self, req, connectors,\n )?)\n .attach_default_headers()\n .headers(types::PaymentsAuthorizeType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsAuthorizeType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsAuthorizeRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: zift::ZiftAuthPaymentsResponse = serde_urlencoded::from_bytes(&res.response)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Zift {\n fn get_headers(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n fn get_request_body(\n &self,\n req: &PaymentsSyncRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = zift::ZiftSyncRequest::try_from(req)?;\n Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))\n }\n\n fn get_url(\n &self,\n _req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}gates/xurl\", self.base_url(connectors)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsSyncRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .set_body(types::PaymentsSyncType::get_request_body(\n self, req, connectors,\n )?)\n .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsSyncRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: zift::ZiftSyncResponse = serde_urlencoded::from_bytes(&res.response)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Zift {\n fn get_headers(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}gates/xurl\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCaptureRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_amount_to_capture,\n req.request.currency,\n )?;\n let connector_router_data = zift::ZiftRouterData::from((amount, req));\n let connector_req = zift::ZiftCaptureRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCaptureRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsCaptureType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::PaymentsCaptureType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCaptureRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: zift::ZiftCaptureResponse = serde_urlencoded::from_bytes(&res.response)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Zift {\n fn get_headers(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}gates/xurl\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &PaymentsCancelRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let connector_req = zift::ZiftCancelRequest::try_from(req)?;\n Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &PaymentsCancelRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n Ok(Some(\n RequestBuilder::new()\n .method(Method::Post)\n .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)\n .set_body(types::PaymentsVoidType::get_request_body(\n self, req, connectors,\n )?)\n .build(),\n ))\n }\n\n fn handle_response(\n &self,\n data: &PaymentsCancelRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult {\n let response: zift::ZiftVoidResponse = serde_urlencoded::from_bytes(&res.response)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Zift {\n fn get_headers(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult)>, errors::ConnectorError> {\n self.build_headers(req, connectors)\n }\n\n fn get_content_type(&self) -> &'static str {\n self.common_get_content_type()\n }\n\n fn get_url(\n &self,\n _req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult {\n Ok(format!(\"{}gates/xurl\", self.base_url(connectors)))\n }\n\n fn get_request_body(\n &self,\n req: &RefundsRouterData,\n _connectors: &Connectors,\n ) -> CustomResult {\n let refund_amount = utils::convert_amount(\n self.amount_converter,\n req.request.minor_refund_amount,\n req.request.currency,\n )?;\n\n let connector_router_data = zift::ZiftRouterData::from((refund_amount, req));\n let connector_req = zift::ZiftRefundRequest::try_from(&connector_router_data)?;\n Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))\n }\n\n fn build_request(\n &self,\n req: &RefundsRouterData,\n connectors: &Connectors,\n ) -> CustomResult, errors::ConnectorError> {\n let request = RequestBuilder::new()\n .method(Method::Post)\n .url(&types::RefundExecuteType::get_url(self, req, connectors)?)\n .attach_default_headers()\n .headers(types::RefundExecuteType::get_headers(\n self, req, connectors,\n )?)\n .set_body(types::RefundExecuteType::get_request_body(\n self, req, connectors,\n )?)\n .build();\n Ok(Some(request))\n }\n\n fn handle_response(\n &self,\n data: &RefundsRouterData,\n event_builder: Option<&mut ConnectorEvent>,\n res: Response,\n ) -> CustomResult, errors::ConnectorError> {\n let response: zift::RefundResponse = serde_urlencoded::from_bytes(&res.response)\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n event_builder.map(|i| i.set_response_body(&response));\n router_env::logger::info!(connector_response=?response);\n RouterData::try_from(ResponseRouterData {\n response,\n data: data.clone(),\n http_code: res.status_code,\n })\n }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\nimpl ConnectorIntegration for Zift {\n // fn get_headers(\n // &self,\n // req: &RefundSyncRouterData,\n // connectors: &Connectors,\n // ) -> CustomResult)>, errors::ConnectorError> {\n // self.build_headers(req, connectors)\n // }\n\n // fn get_content_type(&self) -> &'static str {\n // self.common_get_content_type()\n // }\n\n // fn get_url(\n // &self,\n // _req: &RefundSyncRouterData,\n // connectors: &Connectors,\n // ) -> CustomResult {\n // Ok(format!(\"{}gates/xurl\", self.base_url(connectors)))\n // }\n\n // fn build_request(\n // &self,\n // _req: &RefundSyncRouterData,\n // _connectors: &Connectors,\n // ) -> CustomResult, errors::ConnectorError> {\n // Ok(Some(\n // RequestBuilder::new()\n // .method(Method::Post)\n // .url(&types::RefundSyncType::get_url(self, req, connectors)?)\n // .attach_default_headers()\n // .headers(types::RefundSyncType::get_headers(self, req, connectors)?)\n // .set_body(types::RefundSyncType::get_request_body(\n // self, req, connectors,\n // )?)\n // .build(),\n // ))\n // }\n\n // fn handle_response(\n // &self,\n // data: &RefundSyncRouterData,\n // event_builder: Option<&mut ConnectorEvent>,\n // res: Response,\n // ) -> CustomResult {\n // let response: zift::RefundResponse = serde_urlencoded::from_bytes(&res.response)\n // .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n // event_builder.map(|i| i.set_response_body(&response));\n // router_env::logger::info!(connector_response=?response);\n // RouterData::try_from(ResponseRouterData {\n // response,\n // data: data.clone(),\n // http_code: res.status_code,\n // })\n // }\n\n fn get_error_response(\n &self,\n res: Response,\n event_builder: Option<&mut ConnectorEvent>,\n ) -> CustomResult {\n self.build_error_response(res, event_builder)\n }\n}\n\n#[async_trait::async_trait]\nimpl webhooks::IncomingWebhook for Zift {\n fn get_webhook_object_reference_id(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_event_type(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n _context: Option<&webhooks::WebhookContext>,\n ) -> CustomResult {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n\n fn get_webhook_resource_object(\n &self,\n _request: &webhooks::IncomingWebhookRequestDetails<'_>,\n ) -> CustomResult, errors::ConnectorError> {\n Err(report!(errors::ConnectorError::WebhooksNotImplemented))\n }\n}\n\nstatic ZIFT_SUPPORTED_PAYMENT_METHODS: LazyLock = LazyLock::new(|| {\n let supported_capture_methods = vec![\n common_enums::CaptureMethod::Automatic,\n common_enums::CaptureMethod::Manual,\n common_enums::CaptureMethod::SequentialAutomatic,\n ];\n\n let supported_card_network = vec![\n common_enums::CardNetwork::AmericanExpress,\n common_enums::CardNetwork::DinersClub,\n common_enums::CardNetwork::JCB,\n common_enums::CardNetwork::Mastercard,\n common_enums::CardNetwork::Visa,\n common_enums::CardNetwork::Discover,\n ];\n\n let mut zift_supported_payment_methods = SupportedPaymentMethods::new();\n\n zift_supported_payment_methods.add(\n common_enums::PaymentMethod::Card,\n common_enums::PaymentMethodType::Credit,\n PaymentMethodDetails {\n mandates: common_enums::FeatureStatus::Supported,\n refunds: common_enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n zift_supported_payment_methods.add(\n common_enums::PaymentMethod::Card,\n common_enums::PaymentMethodType::Debit,\n PaymentMethodDetails {\n mandates: common_enums::FeatureStatus::Supported,\n refunds: common_enums::FeatureStatus::Supported,\n supported_capture_methods: supported_capture_methods.clone(),\n specific_features: Some(\n api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({\n api_models::feature_matrix::CardSpecificFeatures {\n three_ds: common_enums::FeatureStatus::NotSupported,\n no_three_ds: common_enums::FeatureStatus::Supported,\n supported_card_networks: supported_card_network.clone(),\n }\n }),\n ),\n },\n );\n\n zift_supported_payment_methods\n});\n\nstatic ZIFT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {\n display_name: \"Zift\",\n description: \"Zift connector\",\n connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,\n integration_status: enums::ConnectorIntegrationStatus::Alpha,\n};\n\nstatic ZIFT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];\n\nimpl ConnectorSpecifications for Zift {\n fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {\n Some(&ZIFT_CONNECTOR_INFO)\n }\n\n fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {\n Some(&*ZIFT_SUPPORTED_PAYMENT_METHODS)\n }\n\n fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {\n Some(&ZIFT_SUPPORTED_WEBHOOK_FLOWS)\n }\n}\n"} {"file_name": "crates__hyperswitch_domain_models__src__merchant_connector_account.rs", "text": "#[cfg(feature = \"v2\")]\nuse std::collections::HashMap;\n\nuse common_utils::{\n crypto::Encryptable,\n date_time,\n encryption::Encryption,\n errors::{CustomResult, ValidationError},\n ext_traits::{StringExt, ValueExt},\n id_type, pii, type_name,\n types::keymanager::{Identifier, KeyManagerState, ToEncryptable},\n};\n#[cfg(feature = \"v2\")]\nuse diesel_models::merchant_connector_account::{\n BillingAccountReference as DieselBillingAccountReference,\n MerchantConnectorAccountFeatureMetadata as DieselMerchantConnectorAccountFeatureMetadata,\n RevenueRecoveryMetadata as DieselRevenueRecoveryMetadata,\n};\nuse diesel_models::{\n enums,\n merchant_connector_account::{self as storage, MerchantConnectorAccountUpdateInternal},\n};\nuse error_stack::ResultExt;\nuse masking::{PeekInterface, Secret};\nuse rustc_hash::FxHashMap;\nuse serde_json::Value;\n\nuse super::behaviour;\n#[cfg(feature = \"v2\")]\nuse crate::errors::api_error_response;\nuse crate::{\n mandates::CommonMandateReference,\n merchant_key_store::MerchantKeyStore,\n router_data,\n type_encryption::{crypto_operation, CryptoOperation},\n};\n\n#[cfg(feature = \"v1\")]\n#[derive(Clone, Debug, router_derive::ToEncryption)]\npub struct MerchantConnectorAccount {\n pub merchant_id: id_type::MerchantId,\n pub connector_name: String,\n #[encrypt]\n pub connector_account_details: Encryptable>,\n pub test_mode: Option,\n pub disabled: Option,\n pub merchant_connector_id: id_type::MerchantConnectorAccountId,\n pub payment_methods_enabled: Option>,\n pub connector_type: enums::ConnectorType,\n pub metadata: Option,\n pub frm_configs: Option>,\n pub connector_label: Option,\n pub business_country: Option,\n pub business_label: Option,\n pub business_sub_label: Option,\n pub created_at: time::PrimitiveDateTime,\n pub modified_at: time::PrimitiveDateTime,\n pub connector_webhook_details: Option,\n pub profile_id: id_type::ProfileId,\n pub applepay_verified_domains: Option>,\n pub pm_auth_config: Option,\n pub status: enums::ConnectorStatus,\n #[encrypt]\n pub connector_wallets_details: Option>>,\n #[encrypt]\n pub additional_merchant_data: Option>>,\n pub version: common_enums::ApiVersion,\n pub connector_webhook_registration_details: Option,\n}\n\n#[cfg(feature = \"v1\")]\nimpl MerchantConnectorAccount {\n pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {\n self.merchant_connector_id.clone()\n }\n pub fn get_connector_account_details(\n &self,\n ) -> error_stack::Result\n {\n self.connector_account_details\n .get_inner()\n .clone()\n .parse_value(\"ConnectorAuthType\")\n }\n\n pub fn get_connector_wallets_details(&self) -> Option> {\n self.connector_wallets_details.as_deref().cloned()\n }\n\n pub fn get_connector_test_mode(&self) -> Option {\n self.test_mode\n }\n\n pub fn get_connector_name_as_string(&self) -> String {\n self.connector_name.clone()\n }\n\n pub fn get_metadata(&self) -> Option> {\n self.metadata.clone()\n }\n\n pub fn get_ctp_service_provider(\n &self,\n ) -> error_stack::Result<\n Option,\n common_utils::errors::ParsingError,\n > {\n let provider = self\n .connector_name\n .clone()\n .parse_enum(\"CtpServiceProvider\")\n .attach_printable_lazy(|| {\n format!(\n \"Failed to parse ctp service provider from connector_name: {}\",\n self.connector_name\n )\n })?;\n\n Ok(Some(provider))\n }\n\n pub fn should_construct_webhook_setup_capability(&self) -> bool {\n matches!(self.connector_type, enums::ConnectorType::PaymentProcessor)\n }\n\n pub fn get_connector_webhook_registration_details(&self) -> Option {\n self.connector_webhook_registration_details.clone()\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Clone, Debug)]\npub enum MerchantConnectorAccountTypeDetails {\n MerchantConnectorAccount(Box),\n MerchantConnectorDetails(common_types::domain::MerchantConnectorAuthDetails),\n}\n\n#[cfg(feature = \"v2\")]\nimpl MerchantConnectorAccountTypeDetails {\n pub fn get_connector_account_details(\n &self,\n ) -> error_stack::Result\n {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n merchant_connector_account\n .connector_account_details\n .peek()\n .clone()\n .parse_value(\"ConnectorAuthType\")\n }\n Self::MerchantConnectorDetails(merchant_connector_details) => {\n merchant_connector_details\n .merchant_connector_creds\n .peek()\n .clone()\n .parse_value(\"ConnectorAuthType\")\n }\n }\n }\n\n pub fn is_disabled(&self) -> bool {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n merchant_connector_account.disabled.unwrap_or(false)\n }\n Self::MerchantConnectorDetails(_) => false,\n }\n }\n\n pub fn get_metadata(&self) -> Option> {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n merchant_connector_account.metadata.to_owned()\n }\n Self::MerchantConnectorDetails(_) => None,\n }\n }\n\n pub fn get_id(&self) -> Option {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n Some(merchant_connector_account.id.clone())\n }\n Self::MerchantConnectorDetails(_) => None,\n }\n }\n\n pub fn get_mca_id(&self) -> Option {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n Some(merchant_connector_account.get_id())\n }\n Self::MerchantConnectorDetails(_) => None,\n }\n }\n\n pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n merchant_connector_account.connector_name\n }\n Self::MerchantConnectorDetails(merchant_connector_details) => {\n merchant_connector_details.connector_name\n }\n }\n }\n\n pub fn get_connector_name_as_string(&self) -> String {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n merchant_connector_account.connector_name.to_string()\n }\n Self::MerchantConnectorDetails(merchant_connector_details) => {\n merchant_connector_details.connector_name.to_string()\n }\n }\n }\n\n pub fn get_inner_db_merchant_connector_account(&self) -> Option<&MerchantConnectorAccount> {\n match self {\n Self::MerchantConnectorAccount(merchant_connector_account) => {\n Some(merchant_connector_account)\n }\n Self::MerchantConnectorDetails(_) => None,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Clone, Debug, router_derive::ToEncryption)]\npub struct MerchantConnectorAccount {\n pub id: id_type::MerchantConnectorAccountId,\n pub merchant_id: id_type::MerchantId,\n pub connector_name: common_enums::connector_enums::Connector,\n #[encrypt]\n pub connector_account_details: Encryptable>,\n pub disabled: Option,\n pub payment_methods_enabled: Option>,\n pub connector_type: enums::ConnectorType,\n pub metadata: Option,\n pub frm_configs: Option>,\n pub connector_label: Option,\n pub created_at: time::PrimitiveDateTime,\n pub modified_at: time::PrimitiveDateTime,\n pub connector_webhook_details: Option,\n pub profile_id: id_type::ProfileId,\n pub applepay_verified_domains: Option>,\n pub pm_auth_config: Option,\n pub status: enums::ConnectorStatus,\n #[encrypt]\n pub connector_wallets_details: Option>>,\n #[encrypt]\n pub additional_merchant_data: Option>>,\n pub version: common_enums::ApiVersion,\n pub feature_metadata: Option,\n}\n\n#[cfg(feature = \"v2\")]\nimpl MerchantConnectorAccount {\n pub fn get_retry_threshold(&self) -> Option {\n self.feature_metadata\n .as_ref()\n .and_then(|metadata| metadata.revenue_recovery.as_ref())\n .map(|recovery| recovery.billing_connector_retry_threshold)\n }\n\n pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {\n self.id.clone()\n }\n\n pub fn get_metadata(&self) -> Option {\n self.metadata.clone()\n }\n\n pub fn is_disabled(&self) -> bool {\n self.disabled.unwrap_or(false)\n }\n\n pub fn get_connector_account_details(\n &self,\n ) -> error_stack::Result\n {\n use common_utils::ext_traits::ValueExt;\n\n self.connector_account_details\n .get_inner()\n .clone()\n .parse_value(\"ConnectorAuthType\")\n }\n\n pub fn get_connector_wallets_details(&self) -> Option> {\n self.connector_wallets_details.as_deref().cloned()\n }\n\n pub fn get_connector_test_mode(&self) -> Option {\n todo!()\n }\n\n pub fn get_connector_name_as_string(&self) -> String {\n self.connector_name.clone().to_string()\n }\n\n #[cfg(feature = \"v2\")]\n pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector {\n self.connector_name\n }\n\n pub fn get_payment_merchant_connector_account_id_using_account_reference_id(\n &self,\n account_reference_id: String,\n ) -> Option {\n self.feature_metadata.as_ref().and_then(|metadata| {\n metadata.revenue_recovery.as_ref().and_then(|recovery| {\n recovery\n .mca_reference\n .billing_to_recovery\n .get(&account_reference_id)\n .cloned()\n })\n })\n }\n pub fn get_account_reference_id_using_payment_merchant_connector_account_id(\n &self,\n payment_merchant_connector_account_id: id_type::MerchantConnectorAccountId,\n ) -> Option {\n self.feature_metadata.as_ref().and_then(|metadata| {\n metadata.revenue_recovery.as_ref().and_then(|recovery| {\n recovery\n .mca_reference\n .recovery_to_billing\n .get(&payment_merchant_connector_account_id)\n .cloned()\n })\n })\n }\n}\n\n#[cfg(feature = \"v2\")]\n/// Holds the payment methods enabled for a connector along with the connector name\n/// This struct is a flattened representation of the payment methods enabled for a connector\n#[derive(Debug)]\npub struct PaymentMethodsEnabledForConnector {\n pub payment_methods_enabled: common_types::payment_methods::RequestPaymentMethodTypes,\n pub payment_method: common_enums::PaymentMethod,\n pub connector: common_enums::connector_enums::Connector,\n pub merchant_connector_id: id_type::MerchantConnectorAccountId,\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Debug, Clone)]\npub struct MerchantConnectorAccountFeatureMetadata {\n pub revenue_recovery: Option,\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Debug, Clone)]\npub struct RevenueRecoveryMetadata {\n pub max_retry_count: u16,\n pub billing_connector_retry_threshold: u16,\n pub mca_reference: AccountReferenceMap,\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Debug, Clone, serde::Deserialize)]\npub struct ExternalVaultConnectorMetadata {\n pub proxy_url: common_utils::types::Url,\n pub certificate: Secret,\n}\n#[cfg(feature = \"v2\")]\n#[derive(Debug, Clone)]\npub struct AccountReferenceMap {\n pub recovery_to_billing: HashMap,\n pub billing_to_recovery: HashMap,\n}\n\n#[cfg(feature = \"v2\")]\nimpl AccountReferenceMap {\n pub fn new(\n hash_map: HashMap,\n ) -> Result {\n Self::validate(&hash_map)?;\n\n let recovery_to_billing = hash_map.clone();\n let mut billing_to_recovery = HashMap::new();\n\n for (key, value) in &hash_map {\n billing_to_recovery.insert(value.clone(), key.clone());\n }\n\n Ok(Self {\n recovery_to_billing,\n billing_to_recovery,\n })\n }\n\n fn validate(\n hash_map: &HashMap,\n ) -> Result<(), api_error_response::ApiErrorResponse> {\n let mut seen_values = std::collections::HashSet::new(); // To check uniqueness of values\n\n for value in hash_map.values() {\n if !seen_values.insert(value.clone()) {\n return Err(api_error_response::ApiErrorResponse::InvalidRequestData {\n message: \"Duplicate account reference IDs found in Recovery feature metadata. Each account reference ID must be unique.\".to_string(),\n });\n }\n }\n Ok(())\n }\n}\n\n#[cfg(feature = \"v2\")]\n/// Holds the payment methods enabled for a connector\npub struct FlattenedPaymentMethodsEnabled {\n pub payment_methods_enabled: Vec,\n}\n\n#[cfg(feature = \"v2\")]\nimpl FlattenedPaymentMethodsEnabled {\n /// This functions flattens the payment methods enabled from the connector accounts\n /// Retains the connector name and payment method in every flattened element\n pub fn from_payment_connectors_list(payment_connectors: Vec) -> Self {\n let payment_methods_enabled_flattened_with_connector = payment_connectors\n .into_iter()\n .map(|connector| {\n (\n connector\n .payment_methods_enabled\n .clone()\n .unwrap_or_default(),\n connector.connector_name,\n connector.get_id(),\n )\n })\n .flat_map(\n |(payment_method_enabled, connector, merchant_connector_id)| {\n payment_method_enabled\n .into_iter()\n .flat_map(move |payment_method| {\n let request_payment_methods_enabled =\n payment_method.payment_method_subtypes.unwrap_or_default();\n let length = request_payment_methods_enabled.len();\n request_payment_methods_enabled\n .into_iter()\n .zip(std::iter::repeat_n(\n (\n connector,\n merchant_connector_id.clone(),\n payment_method.payment_method_type,\n ),\n length,\n ))\n })\n },\n )\n .map(\n |(request_payment_methods, (connector, merchant_connector_id, payment_method))| {\n PaymentMethodsEnabledForConnector {\n payment_methods_enabled: request_payment_methods,\n connector,\n payment_method,\n merchant_connector_id,\n }\n },\n )\n .collect();\n\n Self {\n payment_methods_enabled: payment_methods_enabled_flattened_with_connector,\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug)]\npub enum MerchantConnectorAccountUpdate {\n Update {\n connector_type: Option,\n connector_name: Option,\n connector_account_details: Box>>,\n test_mode: Option,\n disabled: Option,\n merchant_connector_id: Option,\n payment_methods_enabled: Option>,\n metadata: Option,\n frm_configs: Option>,\n connector_webhook_details: Box>,\n applepay_verified_domains: Option>,\n pm_auth_config: Box>,\n connector_label: Option,\n status: Option,\n connector_wallets_details: Box>>,\n additional_merchant_data: Box>>,\n },\n ConnectorWalletDetailsUpdate {\n connector_wallets_details: Encryptable,\n },\n ConnectorWebhookRegisterationUpdate {\n connector_webhook_registration_details: Option,\n },\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Debug)]\npub enum MerchantConnectorAccountUpdate {\n Update {\n connector_type: Option,\n connector_account_details: Box>>,\n disabled: Option,\n payment_methods_enabled: Option>,\n metadata: Option,\n frm_configs: Option>,\n connector_webhook_details: Box>,\n applepay_verified_domains: Option>,\n pm_auth_config: Box>,\n connector_label: Option,\n status: Option,\n connector_wallets_details: Box>>,\n additional_merchant_data: Box>>,\n feature_metadata: Box>,\n },\n ConnectorWalletDetailsUpdate {\n connector_wallets_details: Encryptable,\n },\n}\n\n#[cfg(feature = \"v1\")]\n#[async_trait::async_trait]\nimpl behaviour::Conversion for MerchantConnectorAccount {\n type DstType = storage::MerchantConnectorAccount;\n type NewDstType = storage::MerchantConnectorAccountNew;\n\n async fn convert(self) -> CustomResult {\n Ok(storage::MerchantConnectorAccount {\n merchant_id: self.merchant_id,\n connector_name: self.connector_name,\n connector_account_details: self.connector_account_details.into(),\n test_mode: self.test_mode,\n disabled: self.disabled,\n merchant_connector_id: self.merchant_connector_id.clone(),\n id: Some(self.merchant_connector_id),\n payment_methods_enabled: self.payment_methods_enabled,\n connector_type: self.connector_type,\n metadata: self.metadata,\n frm_configs: None,\n frm_config: self.frm_configs,\n business_country: self.business_country,\n business_label: self.business_label,\n connector_label: self.connector_label,\n business_sub_label: self.business_sub_label,\n created_at: self.created_at,\n modified_at: self.modified_at,\n connector_webhook_details: self.connector_webhook_details,\n profile_id: Some(self.profile_id),\n applepay_verified_domains: self.applepay_verified_domains,\n pm_auth_config: self.pm_auth_config,\n status: self.status,\n connector_wallets_details: self.connector_wallets_details.map(Encryption::from),\n additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),\n version: self.version,\n connector_webhook_registration_details: self.connector_webhook_registration_details,\n })\n }\n\n async fn convert_back(\n state: &KeyManagerState,\n other: Self::DstType,\n key: &Secret>,\n _key_manager_identifier: Identifier,\n ) -> CustomResult {\n let identifier = Identifier::Merchant(other.merchant_id.clone());\n let decrypted_data = crypto_operation(\n state,\n type_name!(Self::DstType),\n CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(\n EncryptedMerchantConnectorAccount {\n connector_account_details: other.connector_account_details,\n additional_merchant_data: other.additional_merchant_data,\n connector_wallets_details: other.connector_wallets_details,\n },\n )),\n identifier.clone(),\n key.peek(),\n )\n .await\n .and_then(|val| val.try_into_batchoperation())\n .change_context(ValidationError::InvalidValue {\n message: \"Failed while decrypting connector account details\".to_string(),\n })?;\n\n let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)\n .change_context(ValidationError::InvalidValue {\n message: \"Failed while decrypting connector account details\".to_string(),\n })?;\n\n Ok(Self {\n merchant_id: other.merchant_id,\n connector_name: other.connector_name,\n connector_account_details: decrypted_data.connector_account_details,\n test_mode: other.test_mode,\n disabled: other.disabled,\n merchant_connector_id: other.merchant_connector_id,\n payment_methods_enabled: other.payment_methods_enabled,\n connector_type: other.connector_type,\n metadata: other.metadata,\n\n frm_configs: other.frm_config,\n business_country: other.business_country,\n business_label: other.business_label,\n connector_label: other.connector_label,\n business_sub_label: other.business_sub_label,\n created_at: other.created_at,\n modified_at: other.modified_at,\n connector_webhook_details: other.connector_webhook_details,\n profile_id: other\n .profile_id\n .ok_or(ValidationError::MissingRequiredField {\n field_name: \"profile_id\".to_string(),\n })?,\n applepay_verified_domains: other.applepay_verified_domains,\n pm_auth_config: other.pm_auth_config,\n status: other.status,\n connector_wallets_details: decrypted_data.connector_wallets_details,\n additional_merchant_data: decrypted_data.additional_merchant_data,\n version: other.version,\n connector_webhook_registration_details: other.connector_webhook_registration_details,\n })\n }\n\n async fn construct_new(self) -> CustomResult {\n let now = date_time::now();\n Ok(Self::NewDstType {\n merchant_id: Some(self.merchant_id),\n connector_name: Some(self.connector_name),\n connector_account_details: Some(self.connector_account_details.into()),\n test_mode: self.test_mode,\n disabled: self.disabled,\n merchant_connector_id: self.merchant_connector_id.clone(),\n id: Some(self.merchant_connector_id),\n payment_methods_enabled: self.payment_methods_enabled,\n connector_type: Some(self.connector_type),\n metadata: self.metadata,\n frm_configs: None,\n frm_config: self.frm_configs,\n business_country: self.business_country,\n business_label: self.business_label,\n connector_label: self.connector_label,\n business_sub_label: self.business_sub_label,\n created_at: now,\n modified_at: now,\n connector_webhook_details: self.connector_webhook_details,\n profile_id: Some(self.profile_id),\n applepay_verified_domains: self.applepay_verified_domains,\n pm_auth_config: self.pm_auth_config,\n status: self.status,\n connector_wallets_details: self.connector_wallets_details.map(Encryption::from),\n additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),\n version: self.version,\n })\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[async_trait::async_trait]\nimpl behaviour::Conversion for MerchantConnectorAccount {\n type DstType = storage::MerchantConnectorAccount;\n type NewDstType = storage::MerchantConnectorAccountNew;\n\n async fn convert(self) -> CustomResult {\n Ok(storage::MerchantConnectorAccount {\n id: self.id,\n merchant_id: self.merchant_id,\n connector_name: self.connector_name,\n connector_account_details: self.connector_account_details.into(),\n disabled: self.disabled,\n payment_methods_enabled: self.payment_methods_enabled,\n connector_type: self.connector_type,\n metadata: self.metadata,\n frm_config: self.frm_configs,\n connector_label: self.connector_label,\n created_at: self.created_at,\n modified_at: self.modified_at,\n connector_webhook_details: self.connector_webhook_details,\n profile_id: self.profile_id,\n applepay_verified_domains: self.applepay_verified_domains,\n pm_auth_config: self.pm_auth_config,\n status: self.status,\n connector_wallets_details: self.connector_wallets_details.map(Encryption::from),\n additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),\n version: self.version,\n feature_metadata: self.feature_metadata.map(From::from),\n connector_webhook_registration_details: None,\n })\n }\n\n async fn convert_back(\n state: &KeyManagerState,\n other: Self::DstType,\n key: &Secret>,\n _key_manager_identifier: Identifier,\n ) -> CustomResult {\n let identifier = Identifier::Merchant(other.merchant_id.clone());\n\n let decrypted_data = crypto_operation(\n state,\n type_name!(Self::DstType),\n CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(\n EncryptedMerchantConnectorAccount {\n connector_account_details: other.connector_account_details,\n additional_merchant_data: other.additional_merchant_data,\n connector_wallets_details: other.connector_wallets_details,\n },\n )),\n identifier.clone(),\n key.peek(),\n )\n .await\n .and_then(|val| val.try_into_batchoperation())\n .change_context(ValidationError::InvalidValue {\n message: \"Failed while decrypting connector account details\".to_string(),\n })?;\n\n let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)\n .change_context(ValidationError::InvalidValue {\n message: \"Failed while decrypting connector account details\".to_string(),\n })?;\n\n Ok(Self {\n id: other.id,\n merchant_id: other.merchant_id,\n connector_name: other.connector_name,\n connector_account_details: decrypted_data.connector_account_details,\n disabled: other.disabled,\n payment_methods_enabled: other.payment_methods_enabled,\n connector_type: other.connector_type,\n metadata: other.metadata,\n\n frm_configs: other.frm_config,\n connector_label: other.connector_label,\n created_at: other.created_at,\n modified_at: other.modified_at,\n connector_webhook_details: other.connector_webhook_details,\n profile_id: other.profile_id,\n applepay_verified_domains: other.applepay_verified_domains,\n pm_auth_config: other.pm_auth_config,\n status: other.status,\n connector_wallets_details: decrypted_data.connector_wallets_details,\n additional_merchant_data: decrypted_data.additional_merchant_data,\n version: other.version,\n feature_metadata: other.feature_metadata.map(From::from),\n })\n }\n\n async fn construct_new(self) -> CustomResult {\n let now = date_time::now();\n Ok(Self::NewDstType {\n id: self.id,\n merchant_id: Some(self.merchant_id),\n connector_name: Some(self.connector_name),\n connector_account_details: Some(self.connector_account_details.into()),\n disabled: self.disabled,\n payment_methods_enabled: self.payment_methods_enabled,\n connector_type: Some(self.connector_type),\n metadata: self.metadata,\n frm_config: self.frm_configs,\n connector_label: self.connector_label,\n created_at: now,\n modified_at: now,\n connector_webhook_details: self.connector_webhook_details,\n profile_id: self.profile_id,\n applepay_verified_domains: self.applepay_verified_domains,\n pm_auth_config: self.pm_auth_config,\n status: self.status,\n connector_wallets_details: self.connector_wallets_details.map(Encryption::from),\n additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),\n version: self.version,\n feature_metadata: self.feature_metadata.map(From::from),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for MerchantConnectorAccountUpdateInternal {\n fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self {\n match merchant_connector_account_update {\n MerchantConnectorAccountUpdate::Update {\n connector_type,\n connector_name,\n connector_account_details,\n test_mode,\n disabled,\n merchant_connector_id,\n payment_methods_enabled,\n metadata,\n frm_configs,\n connector_webhook_details,\n applepay_verified_domains,\n pm_auth_config,\n connector_label,\n status,\n connector_wallets_details,\n additional_merchant_data,\n } => Self {\n connector_type,\n connector_name,\n connector_account_details: connector_account_details.map(Encryption::from),\n test_mode,\n disabled,\n merchant_connector_id,\n payment_methods_enabled,\n metadata,\n frm_configs: None,\n frm_config: frm_configs,\n modified_at: Some(date_time::now()),\n connector_webhook_details: *connector_webhook_details,\n applepay_verified_domains,\n pm_auth_config: *pm_auth_config,\n connector_label,\n status,\n connector_wallets_details: connector_wallets_details.map(Encryption::from),\n additional_merchant_data: additional_merchant_data.map(Encryption::from),\n connector_webhook_registration_details: None,\n },\n MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {\n connector_wallets_details,\n } => Self {\n connector_wallets_details: Some(Encryption::from(connector_wallets_details)),\n connector_type: None,\n connector_name: None,\n connector_account_details: None,\n connector_label: None,\n test_mode: None,\n disabled: None,\n merchant_connector_id: None,\n payment_methods_enabled: None,\n frm_configs: None,\n metadata: None,\n modified_at: None,\n connector_webhook_details: None,\n frm_config: None,\n applepay_verified_domains: None,\n pm_auth_config: None,\n status: None,\n additional_merchant_data: None,\n connector_webhook_registration_details: None,\n },\n MerchantConnectorAccountUpdate::ConnectorWebhookRegisterationUpdate {\n connector_webhook_registration_details,\n } => Self {\n connector_type: None,\n connector_name: None,\n connector_account_details: None,\n connector_label: None,\n test_mode: None,\n disabled: None,\n merchant_connector_id: None,\n payment_methods_enabled: None,\n frm_configs: None,\n metadata: None,\n modified_at: None,\n connector_webhook_details: None,\n frm_config: None,\n applepay_verified_domains: None,\n pm_auth_config: None,\n status: None,\n connector_wallets_details: None,\n additional_merchant_data: None,\n connector_webhook_registration_details,\n },\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for MerchantConnectorAccountUpdateInternal {\n fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self {\n match merchant_connector_account_update {\n MerchantConnectorAccountUpdate::Update {\n connector_type,\n connector_account_details,\n disabled,\n payment_methods_enabled,\n metadata,\n frm_configs,\n connector_webhook_details,\n applepay_verified_domains,\n pm_auth_config,\n connector_label,\n status,\n connector_wallets_details,\n additional_merchant_data,\n feature_metadata,\n } => Self {\n connector_type,\n connector_account_details: connector_account_details.map(Encryption::from),\n disabled,\n payment_methods_enabled,\n metadata,\n frm_config: frm_configs,\n modified_at: Some(date_time::now()),\n connector_webhook_details: *connector_webhook_details,\n applepay_verified_domains,\n pm_auth_config: *pm_auth_config,\n connector_label,\n status,\n connector_wallets_details: connector_wallets_details.map(Encryption::from),\n additional_merchant_data: additional_merchant_data.map(Encryption::from),\n feature_metadata: feature_metadata.map(From::from),\n },\n MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {\n connector_wallets_details,\n } => Self {\n connector_wallets_details: Some(Encryption::from(connector_wallets_details)),\n connector_type: None,\n connector_account_details: None,\n connector_label: None,\n disabled: None,\n payment_methods_enabled: None,\n metadata: None,\n modified_at: None,\n connector_webhook_details: None,\n frm_config: None,\n applepay_verified_domains: None,\n pm_auth_config: None,\n status: None,\n additional_merchant_data: None,\n feature_metadata: None,\n },\n }\n }\n}\n\ncommon_utils::create_list_wrapper!(\n MerchantConnectorAccounts,\n MerchantConnectorAccount,\n impl_functions: {\n fn filter_and_map<'a, T>(\n &'a self,\n filter: impl Fn(&'a MerchantConnectorAccount) -> bool,\n func: impl Fn(&'a MerchantConnectorAccount) -> T,\n ) -> rustc_hash::FxHashSet\n where\n T: std::hash::Hash + Eq,\n {\n self.0\n .iter()\n .filter(|mca| filter(mca))\n .map(func)\n .collect::>()\n }\n\n pub fn filter_by_profile<'a, T>(\n &'a self,\n profile_id: &'a id_type::ProfileId,\n func: impl Fn(&'a MerchantConnectorAccount) -> T,\n ) -> rustc_hash::FxHashSet\n where\n T: std::hash::Hash + Eq,\n {\n self.filter_and_map(|mca| mca.profile_id == *profile_id, func)\n }\n #[cfg(feature = \"v2\")]\n pub fn get_connector_and_supporting_payment_method_type_for_session_call(\n &self,\n ) -> Vec<(&MerchantConnectorAccount, common_enums::PaymentMethodType, common_enums::PaymentMethod)> {\n // This vector is created to work around lifetimes\n let ref_vector = Vec::default();\n\n let connector_and_supporting_payment_method_type = self.iter().flat_map(|connector_account| {\n connector_account\n .payment_methods_enabled.as_ref()\n .unwrap_or(&Vec::default())\n .iter()\n .flat_map(|payment_method_types| payment_method_types.payment_method_subtypes.as_ref().unwrap_or(&ref_vector).iter().map(|payment_method_subtype| (payment_method_subtype, payment_method_types.payment_method_type)).collect::>())\n .filter(|(payment_method_types_enabled, _)| {\n payment_method_types_enabled.payment_experience == Some(api_models::enums::PaymentExperience::InvokeSdkClient)\n })\n .map(|(payment_method_subtypes, payment_method_type)| {\n (connector_account, payment_method_subtypes.payment_method_subtype, payment_method_type)\n })\n .collect::>()\n }).collect();\n connector_and_supporting_payment_method_type\n }\n pub fn filter_based_on_profile_and_connector_type(\n self,\n profile_id: &id_type::ProfileId,\n connector_type: common_enums::ConnectorType,\n ) -> Self {\n self.into_iter()\n .filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type)\n .collect()\n }\n pub fn is_merchant_connector_account_id_in_connector_mandate_details(\n &self,\n profile_id: Option<&id_type::ProfileId>,\n connector_mandate_details: &CommonMandateReference,\n ) -> bool {\n let mca_ids = self\n .iter()\n .filter(|mca| {\n mca.disabled.is_some_and(|disabled| !disabled)\n && profile_id.is_some_and(|profile_id| *profile_id == mca.profile_id)\n })\n .map(|mca| mca.get_id())\n .collect::>();\n\n connector_mandate_details\n .payments\n .as_ref()\n .as_ref().is_some_and(|payments| {\n payments.0.keys().any(|mca_id| mca_ids.contains(mca_id))\n })\n }\n }\n);\n\n#[cfg(feature = \"v2\")]\nimpl From\n for DieselMerchantConnectorAccountFeatureMetadata\n{\n fn from(feature_metadata: MerchantConnectorAccountFeatureMetadata) -> Self {\n let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| {\n DieselRevenueRecoveryMetadata {\n max_retry_count: recovery_metadata.max_retry_count,\n billing_connector_retry_threshold: recovery_metadata\n .billing_connector_retry_threshold,\n billing_account_reference: DieselBillingAccountReference(\n recovery_metadata.mca_reference.recovery_to_billing,\n ),\n }\n });\n Self { revenue_recovery }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From\n for MerchantConnectorAccountFeatureMetadata\n{\n fn from(feature_metadata: DieselMerchantConnectorAccountFeatureMetadata) -> Self {\n let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| {\n let mut billing_to_recovery = HashMap::new();\n for (key, value) in &recovery_metadata.billing_account_reference.0 {\n billing_to_recovery.insert(value.to_string(), key.clone());\n }\n RevenueRecoveryMetadata {\n max_retry_count: recovery_metadata.max_retry_count,\n billing_connector_retry_threshold: recovery_metadata\n .billing_connector_retry_threshold,\n mca_reference: AccountReferenceMap {\n recovery_to_billing: recovery_metadata.billing_account_reference.0,\n billing_to_recovery,\n },\n }\n });\n Self { revenue_recovery }\n }\n}\n\n#[async_trait::async_trait]\npub trait MerchantConnectorAccountInterface\nwhere\n MerchantConnectorAccount: behaviour::Conversion<\n DstType = storage::MerchantConnectorAccount,\n NewDstType = storage::MerchantConnectorAccountNew,\n >,\n{\n type Error;\n #[cfg(feature = \"v1\")]\n async fn find_merchant_connector_account_by_merchant_id_connector_label(\n &self,\n merchant_id: &id_type::MerchantId,\n connector_label: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult;\n\n #[cfg(feature = \"v1\")]\n async fn find_merchant_connector_account_by_profile_id_connector_name(\n &self,\n profile_id: &id_type::ProfileId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult;\n\n #[cfg(feature = \"v1\")]\n async fn find_merchant_connector_account_by_merchant_id_connector_name(\n &self,\n merchant_id: &id_type::MerchantId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, Self::Error>;\n\n async fn insert_merchant_connector_account(\n &self,\n t: MerchantConnectorAccount,\n key_store: &MerchantKeyStore,\n ) -> CustomResult;\n\n #[cfg(feature = \"v1\")]\n async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &id_type::MerchantId,\n merchant_connector_id: &id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult;\n\n #[cfg(feature = \"v2\")]\n async fn find_merchant_connector_account_by_id(\n &self,\n id: &id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult;\n\n async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(\n &self,\n merchant_id: &id_type::MerchantId,\n get_disabled: bool,\n key_store: &MerchantKeyStore,\n ) -> CustomResult;\n\n #[cfg(all(feature = \"olap\", feature = \"v2\"))]\n async fn list_connector_account_by_profile_id(\n &self,\n profile_id: &id_type::ProfileId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, Self::Error>;\n\n async fn list_enabled_connector_accounts_by_profile_id(\n &self,\n profile_id: &id_type::ProfileId,\n key_store: &MerchantKeyStore,\n connector_type: common_enums::ConnectorType,\n ) -> CustomResult, Self::Error>;\n\n async fn update_merchant_connector_account(\n &self,\n this: MerchantConnectorAccount,\n merchant_connector_account: MerchantConnectorAccountUpdateInternal,\n key_store: &MerchantKeyStore,\n ) -> CustomResult;\n\n async fn update_multiple_merchant_connector_accounts(\n &self,\n this: Vec<(\n MerchantConnectorAccount,\n MerchantConnectorAccountUpdateInternal,\n )>,\n ) -> CustomResult<(), Self::Error>;\n\n #[cfg(feature = \"v1\")]\n async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &id_type::MerchantId,\n merchant_connector_id: &id_type::MerchantConnectorAccountId,\n ) -> CustomResult;\n\n #[cfg(feature = \"v2\")]\n async fn delete_merchant_connector_account_by_id(\n &self,\n id: &id_type::MerchantConnectorAccountId,\n ) -> CustomResult;\n}\n"} {"file_name": "crates__hyperswitch_domain_models__src__payment_method_data.rs", "text": "#[cfg(feature = \"v2\")]\nuse std::str::FromStr;\n\nuse api_models::{\n mandates,\n payment_methods::{self},\n payments::{\n additional_info as payment_additional_types, AdditionalNetworkTokenInfo, ExtendedCardInfo,\n },\n};\nuse common_enums::{enums as api_enums, GooglePayCardFundingSource};\nuse common_utils::{\n ext_traits::{OptionExt, StringExt},\n id_type,\n new_type::{\n MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId,\n },\n payout_method_utils,\n pii::{self, Email},\n};\nuse masking::{ExposeInterface, PeekInterface, Secret};\nuse serde::{Deserialize, Serialize};\nuse time::Date;\n\nuse crate::router_data::PaymentMethodToken;\n\n// We need to derive Serialize and Deserialize because some parts of payment method data are being\n// stored in the database as serde_json::Value\n#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]\npub enum PaymentMethodData {\n Card(Card),\n CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId),\n CardWithLimitedDetails(CardWithLimitedDetails),\n NetworkTokenDetailsForNetworkTransactionId(NetworkTokenDetailsForNetworkTransactionId),\n DecryptedWalletTokenDetailsForNetworkTransactionId(\n DecryptedWalletTokenDetailsForNetworkTransactionId,\n ),\n CardRedirect(CardRedirectData),\n Wallet(WalletData),\n PayLater(PayLaterData),\n BankRedirect(BankRedirectData),\n BankDebit(BankDebitData),\n BankTransfer(Box),\n Crypto(CryptoData),\n MandatePayment,\n Reward,\n RealTimePayment(Box),\n Upi(UpiData),\n Voucher(VoucherData),\n GiftCard(Box),\n CardToken(CardToken),\n OpenBanking(OpenBankingData),\n NetworkToken(NetworkTokenData),\n MobilePayment(MobilePaymentData),\n}\n\n#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]\npub enum ExternalVaultPaymentMethodData {\n Card(Box),\n VaultToken(VaultToken),\n}\n\n#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]\n#[serde(tag = \"type\", content = \"data\", rename_all = \"snake_case\")]\npub enum RecurringDetails {\n MandateId(String),\n PaymentMethodId(String),\n ProcessorPaymentToken(ProcessorPaymentToken),\n /// Network transaction ID and Card Details for MIT payments when payment_method_data\n /// is not stored in the application\n NetworkTransactionIdAndCardDetails(Box),\n\n /// Network transaction ID and Network Token Details for MIT payments when payment_method_data\n /// is not stored in the application\n NetworkTransactionIdAndNetworkTokenDetails(Box),\n\n /// Network transaction ID and Wallet Token details for MIT payments when payment_method_data\n /// is not stored in the application\n /// Applicable for wallet tokens such as Apple Pay and Google Pay.\n NetworkTransactionIdAndDecryptedWalletTokenDetails(\n Box,\n ),\n\n CardWithLimitedData(Box),\n}\n\n#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]\npub struct ProcessorPaymentToken {\n pub processor_payment_token: String,\n pub merchant_connector_id: Option,\n}\n\n#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]\npub struct NetworkTransactionIdAndCardDetails {\n /// The card number\n pub card_number: cards::CardNumber,\n\n /// The card's expiry month\n pub card_exp_month: Secret,\n\n /// The card's expiry year\n pub card_exp_year: Secret,\n\n /// The card holder's name\n pub card_holder_name: Option>,\n\n /// The name of the issuer of card\n pub card_issuer: Option,\n\n /// The card network for the card\n pub card_network: Option,\n\n pub card_type: Option,\n\n pub card_issuing_country: Option,\n\n pub card_issuing_country_code: Option,\n\n pub bank_code: Option,\n\n /// The card holder's nick name\n pub nick_name: Option>,\n\n /// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction),\n /// when `setup_future_usage` is set to `off_session`.\n pub network_transaction_id: Secret,\n}\n\n#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]\npub struct NetworkTransactionIdAndNetworkTokenDetails {\n /// The Network Token\n pub network_token: cards::NetworkToken,\n\n /// The token's expiry month\n pub token_exp_month: Secret,\n\n /// The token's expiry year\n pub token_exp_year: Secret,\n\n /// The card network for the card\n pub card_network: Option,\n\n /// The type of the card such as Credit, Debit\n pub card_type: Option,\n\n /// The country in which the card was issued\n pub card_issuing_country: Option,\n\n /// The bank code of the bank that issued the card\n pub bank_code: Option,\n\n /// The card holder's name\n pub card_holder_name: Option>,\n\n /// The name of the issuer of card\n pub card_issuer: Option,\n\n /// The card holder's nick name\n pub nick_name: Option>,\n\n /// The ECI(Electronic Commerce Indicator) value for this authentication.\n pub eci: Option,\n\n /// The network transaction ID provided by the card network during a Customer Initiated Transaction (CIT)\n /// when `setup_future_usage` is set to `off_session`.\n pub network_transaction_id: Secret,\n}\n\n#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]\npub struct CardWithLimitedData {\n /// The card number\n pub card_number: cards::CardNumber,\n\n /// The card's expiry month\n pub card_exp_month: Option>,\n\n /// The card's expiry year\n pub card_exp_year: Option>,\n\n /// The card holder's name\n pub card_holder_name: Option>,\n\n /// The ECI(Electronic Commerce Indicator) value for this authentication.\n pub eci: Option,\n}\n\n// Determines if decryption should be performed\n#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]\npub enum ApplePayFlow {\n // Either Merchant provided certificates i.e decryption by hyperswitch or Hyperswitch certificates i.e simplified flow\n // decryption is performed in hyperswitch\n DecryptAtApplication(api_models::payments::PaymentProcessingDetails),\n // decryption by connector or predecrypted token\n SkipDecryption,\n}\n\nimpl PaymentMethodData {\n pub fn apply_additional_payment_data(\n &self,\n additional_payment_data: api_models::payments::AdditionalPaymentData,\n ) -> Self {\n if let api_models::payments::AdditionalPaymentData::Card(additional_card_info) =\n additional_payment_data\n {\n match self {\n Self::Card(card) => {\n Self::Card(card.apply_additional_card_info(*additional_card_info))\n }\n Self::CardWithLimitedDetails(card_with_limited_details) => {\n Self::CardWithLimitedDetails(\n card_with_limited_details.apply_additional_card_info(*additional_card_info),\n )\n }\n Self::CardDetailsForNetworkTransactionId(card_with_network_transaction_id) => {\n Self::CardDetailsForNetworkTransactionId(\n card_with_network_transaction_id\n .apply_additional_card_info(*additional_card_info),\n )\n }\n _ => self.to_owned(),\n }\n } else {\n self.to_owned()\n }\n }\n\n pub fn get_payment_method(&self) -> Option {\n match self {\n Self::Card(_)\n | Self::NetworkToken(_)\n | Self::CardDetailsForNetworkTransactionId(_)\n | Self::NetworkTokenDetailsForNetworkTransactionId(_)\n | Self::DecryptedWalletTokenDetailsForNetworkTransactionId(_)\n | Self::CardWithLimitedDetails(_) => Some(common_enums::PaymentMethod::Card),\n Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),\n Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),\n Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),\n Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),\n Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),\n Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),\n Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),\n Self::Reward => Some(common_enums::PaymentMethod::Reward),\n Self::RealTimePayment(_) => Some(common_enums::PaymentMethod::RealTimePayment),\n Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),\n Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),\n Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),\n Self::OpenBanking(_) => Some(common_enums::PaymentMethod::OpenBanking),\n Self::MobilePayment(_) => Some(common_enums::PaymentMethod::MobilePayment),\n Self::CardToken(_) | Self::MandatePayment => None,\n }\n }\n\n pub fn get_wallet_data(&self) -> Option<&WalletData> {\n if let Self::Wallet(wallet_data) = self {\n Some(wallet_data)\n } else {\n None\n }\n }\n\n pub fn is_network_token_payment_method_data(&self) -> bool {\n matches!(self, Self::NetworkToken(_))\n }\n\n pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> {\n if let Self::Card(card) = self {\n card.co_badged_card_data.as_ref()\n } else {\n None\n }\n }\n\n pub fn get_card_data(&self) -> Option<&Card> {\n if let Self::Card(card) = self {\n Some(card)\n } else {\n None\n }\n }\n\n pub fn extract_debit_routing_saving_percentage(\n &self,\n network: &common_enums::CardNetwork,\n ) -> Option {\n self.get_co_badged_card_data()?\n .co_badged_card_networks_info\n .0\n .iter()\n .find(|info| &info.network == network)\n .and_then(|info| info.saving_percentage)\n }\n}\n\n#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct Card {\n pub card_number: cards::CardNumber,\n pub card_exp_month: Secret,\n pub card_exp_year: Secret,\n pub card_cvc: Secret,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub card_issuing_country_code: Option,\n pub bank_code: Option,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub co_badged_card_data: Option,\n}\n\nimpl Card {\n fn apply_additional_card_info(\n &self,\n additional_card_info: api_models::payments::AdditionalCardInfo,\n ) -> Self {\n Self {\n card_number: self.card_number.clone(),\n card_exp_month: self.card_exp_month.clone(),\n card_exp_year: self.card_exp_year.clone(),\n card_holder_name: self.card_holder_name.clone(),\n card_cvc: self.card_cvc.clone(),\n card_issuer: self\n .card_issuer\n .clone()\n .or(additional_card_info.card_issuer),\n card_network: self\n .card_network\n .clone()\n .or(additional_card_info.card_network.clone()),\n card_type: self.card_type.clone().or(additional_card_info.card_type),\n card_issuing_country: self\n .card_issuing_country\n .clone()\n .or(additional_card_info.card_issuing_country),\n card_issuing_country_code: self\n .card_issuing_country_code\n .clone()\n .or(additional_card_info.card_issuing_country_code),\n bank_code: self.bank_code.clone().or(additional_card_info.bank_code),\n nick_name: self.nick_name.clone(),\n co_badged_card_data: self.co_badged_card_data.clone(),\n }\n }\n}\n\n#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct ExternalVaultCard {\n pub card_number: Secret,\n pub card_exp_month: Secret,\n pub card_exp_year: Secret,\n pub card_cvc: Secret,\n pub bin_number: Option,\n pub last_four: Option,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub bank_code: Option,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub co_badged_card_data: Option,\n}\n\n#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct VaultToken {\n pub card_cvc: Secret,\n pub card_holder_name: Option>,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct CardDetailsForNetworkTransactionId {\n pub card_number: cards::CardNumber,\n pub card_exp_month: Secret,\n pub card_exp_year: Secret,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub card_issuing_country_code: Option,\n pub bank_code: Option,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n}\n\nimpl CardDetailsForNetworkTransactionId {\n fn apply_additional_card_info(\n &self,\n additional_card_info: api_models::payments::AdditionalCardInfo,\n ) -> Self {\n Self {\n card_number: self.card_number.clone(),\n card_exp_month: self.card_exp_month.clone(),\n card_exp_year: self.card_exp_year.clone(),\n card_holder_name: self.card_holder_name.clone(),\n card_issuer: self\n .card_issuer\n .clone()\n .or(additional_card_info.card_issuer),\n card_network: self\n .card_network\n .clone()\n .or(additional_card_info.card_network.clone()),\n card_type: self.card_type.clone().or(additional_card_info.card_type),\n card_issuing_country: self\n .card_issuing_country\n .clone()\n .or(additional_card_info.card_issuing_country),\n card_issuing_country_code: self\n .card_issuing_country_code\n .clone()\n .or(additional_card_info.card_issuing_country_code),\n bank_code: self.bank_code.clone().or(additional_card_info.bank_code),\n nick_name: self.nick_name.clone(),\n }\n }\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct NetworkTokenDetailsForNetworkTransactionId {\n pub network_token: cards::NetworkToken,\n pub token_exp_month: Secret,\n pub token_exp_year: Secret,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub bank_code: Option,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub eci: Option,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct DecryptedWalletTokenDetailsForNetworkTransactionId {\n pub decrypted_token: cards::NetworkToken,\n pub token_exp_month: Secret,\n pub token_exp_year: Secret,\n pub card_holder_name: Option>,\n pub eci: Option,\n pub token_source: Option,\n}\n\n#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct CardDetail {\n pub card_number: cards::CardNumber,\n pub card_exp_month: Secret,\n pub card_exp_year: Secret,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub card_issuing_country_code: Option,\n pub bank_code: Option,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub co_badged_card_data: Option,\n}\n\n#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct CardWithLimitedDetails {\n pub card_number: cards::CardNumber,\n pub card_exp_month: Option>,\n pub card_exp_year: Option>,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub card_issuing_country_code: Option,\n pub bank_code: Option,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub eci: Option,\n}\n\nimpl CardWithLimitedDetails {\n fn apply_additional_card_info(\n &self,\n additional_card_info: api_models::payments::AdditionalCardInfo,\n ) -> Self {\n Self {\n card_number: self.card_number.clone(),\n card_exp_month: self.card_exp_month.clone(),\n card_exp_year: self.card_exp_year.clone(),\n card_holder_name: self.card_holder_name.clone(),\n card_issuer: self\n .card_issuer\n .clone()\n .or(additional_card_info.card_issuer),\n card_network: self\n .card_network\n .clone()\n .or(additional_card_info.card_network.clone()),\n card_type: self.card_type.clone().or(additional_card_info.card_type),\n card_issuing_country: self\n .card_issuing_country\n .clone()\n .or(additional_card_info.card_issuing_country),\n card_issuing_country_code: self\n .card_issuing_country_code\n .clone()\n .or(additional_card_info.card_issuing_country_code),\n bank_code: self.bank_code.clone().or(additional_card_info.bank_code),\n nick_name: self.nick_name.clone(),\n eci: self.eci.clone(),\n }\n }\n\n pub fn get_card_details_for_mit_flow(\n card_with_limited_data: CardWithLimitedData,\n ) -> (api_models::payments::MandateReferenceId, PaymentMethodData) {\n (\n api_models::payments::MandateReferenceId::CardWithLimitedData,\n PaymentMethodData::CardWithLimitedDetails(card_with_limited_data.into()),\n )\n }\n}\n\nimpl CardDetailsForNetworkTransactionId {\n pub fn get_nti_and_card_details_for_mit_flow(\n network_transaction_id_and_card_details: NetworkTransactionIdAndCardDetails,\n ) -> (api_models::payments::MandateReferenceId, PaymentMethodData) {\n let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(\n network_transaction_id_and_card_details\n .network_transaction_id\n .peek()\n .to_string(),\n );\n\n (\n mandate_reference_id,\n PaymentMethodData::CardDetailsForNetworkTransactionId(\n network_transaction_id_and_card_details.into(),\n ),\n )\n }\n}\n\nimpl NetworkTokenDetailsForNetworkTransactionId {\n pub fn get_nti_and_network_token_details_for_mit_flow(\n network_transaction_id_and_network_token_details: NetworkTransactionIdAndNetworkTokenDetails,\n ) -> (api_models::payments::MandateReferenceId, PaymentMethodData) {\n let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(\n network_transaction_id_and_network_token_details\n .network_transaction_id\n .peek()\n .to_string(),\n );\n\n (\n mandate_reference_id,\n PaymentMethodData::NetworkTokenDetailsForNetworkTransactionId(\n network_transaction_id_and_network_token_details.into(),\n ),\n )\n }\n}\n\nimpl DecryptedWalletTokenDetailsForNetworkTransactionId {\n pub fn get_nti_and_decrypted_wallet_token_details_for_mit_flow(\n network_transaction_id_and_decrypted_wallet_token_details: common_types::payments::NetworkTransactionIdAndDecryptedWalletTokenDetails,\n ) -> (api_models::payments::MandateReferenceId, PaymentMethodData) {\n let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(\n network_transaction_id_and_decrypted_wallet_token_details\n .network_transaction_id\n .peek()\n .to_string(),\n );\n\n (\n mandate_reference_id,\n PaymentMethodData::DecryptedWalletTokenDetailsForNetworkTransactionId(\n network_transaction_id_and_decrypted_wallet_token_details.into(),\n ),\n )\n }\n}\n\nimpl From<&Card> for CardDetail {\n fn from(item: &Card) -> Self {\n Self {\n card_number: item.card_number.to_owned(),\n card_exp_month: item.card_exp_month.to_owned(),\n card_exp_year: item.card_exp_year.to_owned(),\n card_issuer: item.card_issuer.to_owned(),\n card_network: item.card_network.to_owned(),\n card_type: item.card_type.to_owned(),\n card_issuing_country: item.card_issuing_country.to_owned(),\n card_issuing_country_code: item.card_issuing_country_code.to_owned(),\n bank_code: item.bank_code.to_owned(),\n nick_name: item.nick_name.to_owned(),\n card_holder_name: item.card_holder_name.to_owned(),\n co_badged_card_data: item.co_badged_card_data.to_owned(),\n }\n }\n}\n\nimpl From for CardWithLimitedDetails {\n fn from(card_with_limited_data: CardWithLimitedData) -> Self {\n Self {\n card_number: card_with_limited_data.card_number,\n card_exp_month: card_with_limited_data.card_exp_month,\n card_exp_year: card_with_limited_data.card_exp_year,\n card_issuer: None,\n card_network: None,\n card_type: None,\n card_issuing_country: None,\n card_issuing_country_code: None,\n bank_code: None,\n nick_name: None,\n card_holder_name: card_with_limited_data.card_holder_name,\n eci: card_with_limited_data.eci,\n }\n }\n}\n\nimpl From for CardDetailsForNetworkTransactionId {\n fn from(card_details_for_nti: NetworkTransactionIdAndCardDetails) -> Self {\n Self {\n card_number: card_details_for_nti.card_number,\n card_exp_month: card_details_for_nti.card_exp_month,\n card_exp_year: card_details_for_nti.card_exp_year,\n card_issuer: card_details_for_nti.card_issuer,\n card_network: card_details_for_nti.card_network,\n card_type: card_details_for_nti.card_type,\n card_issuing_country: card_details_for_nti.card_issuing_country,\n card_issuing_country_code: card_details_for_nti.card_issuing_country_code,\n bank_code: card_details_for_nti.bank_code,\n nick_name: card_details_for_nti.nick_name,\n card_holder_name: card_details_for_nti.card_holder_name,\n }\n }\n}\n\nimpl From\n for NetworkTokenDetailsForNetworkTransactionId\n{\n fn from(network_token_details_for_nti: NetworkTransactionIdAndNetworkTokenDetails) -> Self {\n Self {\n network_token: network_token_details_for_nti.network_token,\n token_exp_month: network_token_details_for_nti.token_exp_month,\n token_exp_year: network_token_details_for_nti.token_exp_year,\n card_network: network_token_details_for_nti.card_network,\n card_issuer: network_token_details_for_nti.card_issuer,\n card_type: network_token_details_for_nti.card_type,\n card_issuing_country: network_token_details_for_nti.card_issuing_country,\n bank_code: network_token_details_for_nti.bank_code,\n nick_name: network_token_details_for_nti.nick_name,\n card_holder_name: network_token_details_for_nti.card_holder_name,\n eci: network_token_details_for_nti.eci,\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for NetworkTokenData {\n fn from(network_token_details_for_nti: NetworkTokenDetailsForNetworkTransactionId) -> Self {\n Self {\n token_number: network_token_details_for_nti.network_token,\n token_exp_month: network_token_details_for_nti.token_exp_month,\n token_exp_year: network_token_details_for_nti.token_exp_year,\n token_cryptogram: None,\n card_issuer: network_token_details_for_nti.card_issuer,\n card_network: network_token_details_for_nti.card_network,\n card_type: network_token_details_for_nti.card_type,\n card_issuing_country: network_token_details_for_nti.card_issuing_country,\n bank_code: network_token_details_for_nti.bank_code,\n nick_name: network_token_details_for_nti.nick_name,\n eci: network_token_details_for_nti.eci,\n }\n }\n}\n\nimpl From\n for DecryptedWalletTokenDetailsForNetworkTransactionId\n{\n fn from(\n decrypted_token_details_for_nti: common_types::payments::NetworkTransactionIdAndDecryptedWalletTokenDetails,\n ) -> Self {\n Self {\n decrypted_token: decrypted_token_details_for_nti.decrypted_token,\n token_exp_month: decrypted_token_details_for_nti.token_exp_month,\n token_exp_year: decrypted_token_details_for_nti.token_exp_year,\n card_holder_name: decrypted_token_details_for_nti.card_holder_name,\n token_source: decrypted_token_details_for_nti.token_source,\n eci: decrypted_token_details_for_nti.eci,\n }\n }\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]\npub enum CardRedirectData {\n Knet {},\n Benefit {},\n MomoAtm {},\n CardRedirect {},\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub enum PayLaterData {\n KlarnaRedirect {},\n KlarnaSdk { token: String },\n AffirmRedirect {},\n AfterpayClearpayRedirect {},\n PayBrightRedirect {},\n WalleyRedirect {},\n FlexitiRedirect {},\n AlmaRedirect {},\n AtomeRedirect {},\n BreadpayRedirect {},\n PayjustnowRedirect {},\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub enum WalletData {\n AliPayQr(Box),\n AliPayRedirect(AliPayRedirection),\n AliPayHkRedirect(AliPayHkRedirection),\n AmazonPay(AmazonPayWalletData),\n AmazonPayRedirect(Box),\n BluecodeRedirect {},\n Paysera(Box),\n Skrill(Box),\n MomoRedirect(MomoRedirection),\n KakaoPayRedirect(KakaoPayRedirection),\n GoPayRedirect(GoPayRedirection),\n GcashRedirect(GcashRedirection),\n ApplePay(ApplePayWalletData),\n ApplePayRedirect(Box),\n ApplePayThirdPartySdk(Box),\n DanaRedirect {},\n GooglePay(GooglePayWalletData),\n GooglePayRedirect(Box),\n GooglePayThirdPartySdk(Box),\n MbWayRedirect(Box),\n MobilePayRedirect(Box),\n PaypalRedirect(PaypalRedirection),\n PaypalSdk(PayPalWalletData),\n Paze(PazeWalletData),\n SamsungPay(Box),\n TwintRedirect {},\n VippsRedirect {},\n TouchNGoRedirect(Box),\n WeChatPayRedirect(Box),\n WeChatPayQr(Box),\n CashappQr(Box),\n SwishQr(SwishQrData),\n Mifinity(MifinityData),\n RevolutPay(RevolutPayData),\n}\n\nimpl WalletData {\n pub fn get_paze_wallet_data(&self) -> Option<&PazeWalletData> {\n if let Self::Paze(paze_wallet_data) = self {\n Some(paze_wallet_data)\n } else {\n None\n }\n }\n\n pub fn get_apple_pay_wallet_data(&self) -> Option<&ApplePayWalletData> {\n if let Self::ApplePay(apple_pay_wallet_data) = self {\n Some(apple_pay_wallet_data)\n } else {\n None\n }\n }\n\n pub fn get_google_pay_wallet_data(&self) -> Option<&GooglePayWalletData> {\n if let Self::GooglePay(google_pay_wallet_data) = self {\n Some(google_pay_wallet_data)\n } else {\n None\n }\n }\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct MifinityData {\n pub date_of_birth: Secret,\n pub language_preference: Option,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct PazeWalletData {\n pub complete_response: Secret,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct SamsungPayWalletData {\n pub payment_credential: SamsungPayWalletCredentials,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct SamsungPayWalletCredentials {\n pub method: Option,\n pub recurring_payment: Option,\n pub card_brand: common_enums::SamsungPayCardBrand,\n pub dpan_last_four_digits: Option,\n #[serde(rename = \"card_last4digits\")]\n pub card_last_four_digits: String,\n #[serde(rename = \"3_d_s\")]\n pub token_data: SamsungPayTokenData,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct SamsungPayTokenData {\n #[serde(rename = \"type\")]\n pub three_ds_type: Option,\n pub version: String,\n pub data: Secret,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct GooglePayWalletData {\n /// The type of payment method\n pub pm_type: String,\n /// User-facing message to describe the payment method that funds this transaction.\n pub description: String,\n /// The information of the payment method\n pub info: GooglePayPaymentMethodInfo,\n /// The tokenization data of Google pay\n pub tokenization_data: common_types::payments::GpayTokenizationData,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct ApplePayRedirectData {}\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct RevolutPayData {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct GooglePayRedirectData {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct GooglePayThirdPartySdkData {\n pub token: Option>,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct ApplePayThirdPartySdkData {\n pub token: Option>,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct WeChatPayRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct WeChatPay {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct WeChatPayQr {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct CashappQr {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct PaypalRedirection {\n /// paypal's email address\n pub email: Option,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct AliPayQr {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct AliPayRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct AliPayHkRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct AmazonPayRedirect {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct BluecodeQrRedirect {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct PayseraData {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct SkrillData {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct MomoRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct KakaoPayRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct GoPayRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct GcashRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct MobilePayRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct MbWayRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct GooglePayPaymentMethodInfo {\n /// The name of the card network\n pub card_network: String,\n /// The details of the card\n pub card_details: String,\n /// assurance_details of the card\n pub assurance_details: Option,\n /// Card funding source for the selected payment method\n pub card_funding_source: Option,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct GooglePayAssuranceDetails {\n ///indicates that Cardholder possession validation has been performed\n pub card_holder_authenticated: bool,\n /// indicates that identification and verifications (ID&V) was performed\n pub account_verified: bool,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct PayPalWalletData {\n /// Token generated for the Apple pay\n pub token: String,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct TouchNGoRedirection {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct SwishQrData {}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct ApplePayWalletData {\n /// The payment data of Apple pay\n pub payment_data: common_types::payments::ApplePayPaymentData,\n /// The payment method of Apple pay\n pub payment_method: ApplepayPaymentMethod,\n /// The unique identifier for the transaction\n pub transaction_identifier: String,\n}\n\nimpl ApplePayWalletData {\n pub fn get_payment_method_type(&self) -> Option {\n self.payment_method\n .pm_type\n .clone()\n .parse_enum(\"ApplePayPaymentMethodType\")\n .ok()\n .and_then(|payment_type| match payment_type {\n common_enums::ApplePayPaymentMethodType::Debit => {\n Some(api_enums::PaymentMethodType::Debit)\n }\n common_enums::ApplePayPaymentMethodType::Credit => {\n Some(api_enums::PaymentMethodType::Credit)\n }\n common_enums::ApplePayPaymentMethodType::Prepaid\n | common_enums::ApplePayPaymentMethodType::Store => None,\n })\n }\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\npub struct ApplepayPaymentMethod {\n pub display_name: String,\n pub network: String,\n pub pm_type: String,\n}\n\n#[derive(Eq, PartialEq, Clone, Default, Debug, serde::Deserialize, serde::Serialize)]\npub struct AmazonPayWalletData {\n pub checkout_session_id: String,\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub enum RealTimePaymentData {\n DuitNow {},\n Fps {},\n PromptPay {},\n VietQr {},\n Qris {},\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub enum BankRedirectData {\n BancontactCard {\n card_number: Option,\n card_exp_month: Option>,\n card_exp_year: Option>,\n card_holder_name: Option>,\n },\n Bizum {},\n Blik {\n blik_code: Option,\n },\n Eps {\n bank_name: Option,\n country: Option,\n },\n Giropay {\n bank_account_bic: Option>,\n bank_account_iban: Option>,\n country: Option,\n },\n Ideal {\n bank_name: Option,\n },\n Interac {\n country: Option,\n email: Option,\n },\n OnlineBankingCzechRepublic {\n issuer: common_enums::BankNames,\n },\n OnlineBankingFinland {\n email: Option,\n },\n OnlineBankingPoland {\n issuer: common_enums::BankNames,\n },\n OnlineBankingSlovakia {\n issuer: common_enums::BankNames,\n },\n OpenBankingUk {\n issuer: Option,\n country: Option,\n },\n Przelewy24 {\n bank_name: Option,\n },\n Sofort {\n country: Option,\n preferred_language: Option,\n },\n Trustly {\n country: Option,\n },\n OnlineBankingFpx {\n issuer: common_enums::BankNames,\n },\n OnlineBankingThailand {\n issuer: common_enums::BankNames,\n },\n LocalBankRedirect {},\n Eft {\n provider: String,\n },\n OpenBanking {},\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub enum OpenBankingData {\n OpenBankingPIS {},\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct CryptoData {\n pub pay_currency: Option,\n pub network: Option,\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub enum UpiData {\n UpiCollect(UpiCollectData),\n UpiIntent(UpiIntentData),\n UpiQr(UpiQrData),\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"SCREAMING_SNAKE_CASE\")]\npub enum UpiSource {\n UpiCc, // UPI Credit Card\n UpiCl, // UPI Credit Line\n UpiAccount, // UPI Bank Account (Savings)\n UpiCcCl, // UPI Credit Card + Credit Line\n UpiPpi, // UPI Prepaid Payment Instrument\n UpiVoucher, // UPI Voucher\n}\n\nimpl From for UpiSource {\n fn from(value: api_models::payments::UpiSource) -> Self {\n match value {\n api_models::payments::UpiSource::UpiCc => Self::UpiCc,\n api_models::payments::UpiSource::UpiCl => Self::UpiCl,\n api_models::payments::UpiSource::UpiAccount => Self::UpiAccount,\n api_models::payments::UpiSource::UpiCcCl => Self::UpiCcCl,\n api_models::payments::UpiSource::UpiPpi => Self::UpiPpi,\n api_models::payments::UpiSource::UpiVoucher => Self::UpiVoucher,\n }\n }\n}\n\nimpl From for api_models::payments::UpiSource {\n fn from(value: UpiSource) -> Self {\n match value {\n UpiSource::UpiCc => Self::UpiCc,\n UpiSource::UpiCl => Self::UpiCl,\n UpiSource::UpiAccount => Self::UpiAccount,\n UpiSource::UpiCcCl => Self::UpiCcCl,\n UpiSource::UpiPpi => Self::UpiPpi,\n UpiSource::UpiVoucher => Self::UpiVoucher,\n }\n }\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub struct UpiCollectData {\n pub vpa_id: Option>,\n pub upi_source: Option,\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub struct UpiIntentData {\n pub upi_source: Option,\n pub app_name: Option,\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub struct UpiQrData {\n pub upi_source: Option,\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\n#[serde(rename_all = \"snake_case\")]\npub enum VoucherData {\n Boleto(Box),\n Efecty,\n PagoEfectivo,\n RedCompra,\n RedPagos,\n Alfamart(Box),\n Indomaret(Box),\n Oxxo,\n SevenEleven(Box),\n Lawson(Box),\n MiniStop(Box),\n FamilyMart(Box),\n Seicomart(Box),\n PayEasy(Box),\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct BoletoVoucherData {\n /// The shopper's social security number\n pub social_security_number: Option>,\n /// The bank number associated with the boleto\n pub bank_number: Option>,\n /// The type of document (e.g., CPF, CNPJ)\n pub document_type: Option,\n /// The percentage of fine applied for late payment\n pub fine_percentage: Option,\n /// The number of days after due date when fine is applied\n pub fine_quantity_days: Option,\n /// The percentage of interest applied for late payment\n pub interest_percentage: Option,\n /// Number of days after which the boleto can be written off\n pub write_off_quantity_days: Option,\n /// Additional messages to display to the shopper\n pub messages: Option>,\n /// The date upon which the boleto is due and is of format: \"YYYY-MM-DD\"\n pub due_date: Option,\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct AlfamartVoucherData {}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct IndomaretVoucherData {}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct JCSVoucherData {}\n\n#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]\n#[serde(rename_all = \"snake_case\")]\npub enum GiftCardData {\n Givex(GiftCardDetails),\n PaySafeCard {},\n BhnCardNetwork(BHNGiftCardDetails),\n}\n\nimpl GiftCardData {\n pub fn is_givex(&self) -> bool {\n matches!(self, Self::Givex(_))\n }\n /// Returns a key that uniquely identifies the gift card. Used in\n /// Payment Method Balance Check Flow for storing the balance\n /// data in Redis.\n ///\n pub fn get_payment_method_key(\n &self,\n ) -> Result, error_stack::Report> {\n match self {\n Self::Givex(givex) => Ok(givex.number.clone()),\n Self::PaySafeCard {} =>\n // Generate a validation error here as we don't support balance check flow for it\n {\n Err(error_stack::Report::new(\n common_utils::errors::ValidationError::InvalidValue {\n message: \"PaySafeCard doesn't support balance check flow\".to_string(),\n },\n ))\n }\n Self::BhnCardNetwork(bhn) => Ok(bhn.account_number.clone()),\n }\n }\n}\n\n#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]\n#[serde(rename_all = \"snake_case\")]\npub struct GiftCardDetails {\n /// The gift card number\n pub number: Secret,\n /// The card verification code.\n pub cvc: Secret,\n}\n\n#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]\n#[serde(rename_all = \"snake_case\")]\npub struct BHNGiftCardDetails {\n /// The gift card or account number\n pub account_number: Secret,\n /// The security PIN for gift cards requiring it\n pub pin: Option>,\n /// The CVV2 code for Open Loop/VPLN products\n pub cvv2: Option>,\n /// The expiration date in MMYYYY format for Open Loop/VPLN products\n pub expiration_date: Option,\n}\n\n#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]\n#[serde(rename_all = \"snake_case\")]\npub struct CardToken {\n /// The card holder's name\n pub card_holder_name: Option>,\n\n /// The CVC number for the card\n pub card_cvc: Option>,\n}\n\n#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]\n#[serde(rename_all = \"snake_case\")]\npub enum BankDebitData {\n AchBankDebit {\n account_number: Secret,\n routing_number: Secret,\n card_holder_name: Option>,\n bank_account_holder_name: Option>,\n bank_name: Option,\n bank_type: Option,\n bank_holder_type: Option,\n },\n SepaBankDebit {\n iban: Secret,\n bank_account_holder_name: Option>,\n },\n SepaGuarenteedBankDebit {\n iban: Secret,\n bank_account_holder_name: Option>,\n },\n BecsBankDebit {\n account_number: Secret,\n bsb_number: Secret,\n bank_account_holder_name: Option>,\n },\n BacsBankDebit {\n account_number: Secret,\n sort_code: Secret,\n bank_account_holder_name: Option>,\n },\n}\n\nimpl BankDebitData {\n pub fn get_bank_debit_details(self) -> Option {\n match self {\n Self::AchBankDebit {\n account_number,\n routing_number,\n card_holder_name,\n bank_account_holder_name,\n bank_name,\n bank_type,\n bank_holder_type,\n } => Some(BankDebitDetailsPaymentMethod::AchBankDebit {\n masked_account_number: account_number\n .peek()\n .chars()\n .rev()\n .take(4)\n .collect::()\n .chars()\n .rev()\n .collect::(),\n masked_routing_number: routing_number\n .peek()\n .chars()\n .rev()\n .take(4)\n .collect::()\n .chars()\n .rev()\n .collect::(),\n card_holder_name,\n bank_account_holder_name,\n bank_name,\n bank_type,\n bank_holder_type,\n }),\n Self::SepaBankDebit { .. }\n | Self::SepaGuarenteedBankDebit { .. }\n | Self::BecsBankDebit { .. }\n | Self::BacsBankDebit { .. } => None,\n }\n }\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]\n#[serde(rename_all = \"snake_case\")]\npub enum BankTransferData {\n AchBankTransfer {},\n SepaBankTransfer {},\n BacsBankTransfer {},\n MultibancoBankTransfer {},\n PermataBankTransfer {},\n BcaBankTransfer {},\n BniVaBankTransfer {},\n BriVaBankTransfer {},\n CimbVaBankTransfer {},\n DanamonVaBankTransfer {},\n MandiriVaBankTransfer {},\n Pix {\n /// Unique key for pix transfer\n pix_key: Option>,\n /// CPF is a Brazilian tax identification number\n cpf: Option>,\n /// CNPJ is a Brazilian company tax identification number\n cnpj: Option>,\n /// Source bank account UUID\n source_bank_account_id: Option,\n /// Destination bank account UUID.\n destination_bank_account_id: Option,\n /// The expiration date and time for the Pix QR code\n expiry_date: Option,\n },\n Pse {},\n LocalBankTransfer {\n bank_code: Option,\n },\n InstantBankTransfer {},\n InstantBankTransferFinland {},\n InstantBankTransferPoland {},\n IndonesianBankTransfer {\n bank_name: Option,\n },\n}\n\n#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub struct SepaAndBacsBillingDetails {\n /// The Email ID for SEPA and BACS billing\n pub email: Email,\n /// The billing name for SEPA and BACS billing\n pub name: Secret,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct NetworkTokenData {\n pub token_number: cards::NetworkToken,\n pub token_exp_month: Secret,\n pub token_exp_year: Secret,\n pub token_cryptogram: Option>,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub bank_code: Option,\n pub nick_name: Option>,\n pub eci: Option,\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct NetworkTokenData {\n pub network_token: cards::NetworkToken,\n pub network_token_exp_month: Secret,\n pub network_token_exp_year: Secret,\n pub cryptogram: Option>,\n pub card_issuer: Option, //since network token is tied to card, so its issuer will be same as card issuer\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub bank_code: Option,\n pub card_holder_name: Option>,\n pub nick_name: Option>,\n pub eci: Option,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]\npub struct NetworkTokenDetails {\n pub network_token: cards::NetworkToken,\n pub network_token_exp_month: Secret,\n pub network_token_exp_year: Secret,\n pub cryptogram: Option>,\n pub card_issuer: Option, //since network token is tied to card, so its issuer will be same as card issuer\n pub card_network: Option,\n pub card_type: Option,\n pub card_issuing_country: Option,\n pub card_holder_name: Option>,\n pub nick_name: Option>,\n}\n\n#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]\n#[serde(rename_all = \"snake_case\")]\npub enum MobilePaymentData {\n DirectCarrierBilling {\n /// The phone number of the user\n msisdn: String,\n /// Unique user identifier\n client_uid: Option,\n },\n}\n\n#[cfg(feature = \"v2\")]\nimpl TryFrom for PaymentMethodData {\n type Error = error_stack::Report;\n\n fn try_from(value: payment_methods::PaymentMethodCreateData) -> Result {\n match value {\n payment_methods::PaymentMethodCreateData::Card(payment_methods::CardDetail {\n card_number,\n card_exp_month,\n card_exp_year,\n card_cvc,\n card_issuer,\n card_network,\n card_type,\n card_issuing_country,\n nick_name,\n card_holder_name,\n }) => Ok(Self::Card(Card {\n card_number,\n card_exp_month,\n card_exp_year,\n card_cvc: card_cvc.get_required_value(\"card_cvc\")?,\n card_issuer,\n card_network,\n card_type: card_type.map(|card_type| card_type.to_string()),\n card_issuing_country: card_issuing_country.map(|country| country.to_string()),\n card_issuing_country_code: None,\n bank_code: None,\n nick_name,\n card_holder_name,\n co_badged_card_data: None,\n })),\n payment_methods::PaymentMethodCreateData::ProxyCard(_) => Err(\n common_utils::errors::ValidationError::IncorrectValueProvided {\n field_name: \"Payment method data\",\n }\n .into(),\n ),\n }\n }\n}\n\nimpl From for PaymentMethodData {\n fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {\n match api_model_payment_method_data {\n api_models::payments::PaymentMethodData::Card(card_data) => {\n Self::Card(Card::from((card_data, None)))\n }\n api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {\n Self::CardRedirect(From::from(card_redirect))\n }\n api_models::payments::PaymentMethodData::Wallet(wallet_data) => {\n Self::Wallet(From::from(wallet_data))\n }\n api_models::payments::PaymentMethodData::PayLater(pay_later_data) => {\n Self::PayLater(From::from(pay_later_data))\n }\n api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {\n Self::BankRedirect(From::from(bank_redirect_data))\n }\n api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {\n Self::BankDebit(From::from(bank_debit_data))\n }\n api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {\n Self::BankTransfer(Box::new(From::from(*bank_transfer_data)))\n }\n api_models::payments::PaymentMethodData::Crypto(crypto_data) => {\n Self::Crypto(From::from(crypto_data))\n }\n api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,\n api_models::payments::PaymentMethodData::Reward => Self::Reward,\n api_models::payments::PaymentMethodData::RealTimePayment(real_time_payment_data) => {\n Self::RealTimePayment(Box::new(From::from(*real_time_payment_data)))\n }\n api_models::payments::PaymentMethodData::Upi(upi_data) => {\n Self::Upi(From::from(upi_data))\n }\n api_models::payments::PaymentMethodData::Voucher(voucher_data) => {\n Self::Voucher(From::from(voucher_data))\n }\n api_models::payments::PaymentMethodData::GiftCard(gift_card) => {\n Self::GiftCard(Box::new(From::from(*gift_card)))\n }\n api_models::payments::PaymentMethodData::CardToken(card_token) => {\n Self::CardToken(From::from(card_token))\n }\n api_models::payments::PaymentMethodData::OpenBanking(ob_data) => {\n Self::OpenBanking(From::from(ob_data))\n }\n api_models::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => {\n Self::MobilePayment(From::from(mobile_payment_data))\n }\n api_models::payments::PaymentMethodData::NetworkToken(network_token_data) => {\n Self::NetworkToken(From::from(network_token_data))\n }\n }\n }\n}\n\nimpl From for ExternalVaultPaymentMethodData {\n fn from(api_model_payment_method_data: api_models::payments::ProxyPaymentMethodData) -> Self {\n match api_model_payment_method_data {\n api_models::payments::ProxyPaymentMethodData::VaultDataCard(card_data) => {\n Self::Card(Box::new(ExternalVaultCard::from(*card_data)))\n }\n api_models::payments::ProxyPaymentMethodData::VaultToken(vault_data) => {\n Self::VaultToken(VaultToken::from(vault_data))\n }\n }\n }\n}\nimpl From for ExternalVaultCard {\n fn from(value: api_models::payments::ProxyCardData) -> Self {\n let api_models::payments::ProxyCardData {\n card_number,\n card_exp_month,\n card_exp_year,\n card_holder_name,\n card_cvc,\n bin_number,\n last_four,\n card_issuer,\n card_network,\n card_type,\n card_issuing_country,\n bank_code,\n nick_name,\n } = value;\n\n Self {\n card_number,\n card_exp_month,\n card_exp_year,\n card_cvc,\n bin_number,\n last_four,\n card_issuer,\n card_network,\n card_type,\n card_issuing_country,\n bank_code,\n nick_name,\n card_holder_name,\n co_badged_card_data: None,\n }\n }\n}\nimpl From for VaultToken {\n fn from(value: api_models::payments::VaultToken) -> Self {\n let api_models::payments::VaultToken {\n card_cvc,\n card_holder_name,\n } = value;\n\n Self {\n card_cvc,\n card_holder_name,\n }\n }\n}\nimpl\n From<(\n api_models::payments::Card,\n Option,\n )> for Card\n{\n fn from(\n (value, co_badged_card_data_optional): (\n api_models::payments::Card,\n Option,\n ),\n ) -> Self {\n let api_models::payments::Card {\n card_number,\n card_exp_month,\n card_exp_year,\n card_holder_name,\n card_cvc,\n card_issuer,\n card_network,\n card_type,\n card_issuing_country,\n card_issuing_country_code,\n bank_code,\n nick_name,\n } = value;\n\n Self {\n card_number,\n card_exp_month,\n card_exp_year,\n card_cvc,\n card_issuer,\n card_network,\n card_type,\n card_issuing_country,\n card_issuing_country_code,\n bank_code,\n nick_name,\n card_holder_name,\n co_badged_card_data: co_badged_card_data_optional,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl\n From<(\n payment_methods::CardDetail,\n Secret,\n Option>,\n )> for Card\n{\n fn from(\n (card_detail, card_cvc, card_holder_name): (\n payment_methods::CardDetail,\n Secret,\n Option>,\n ),\n ) -> Self {\n Self {\n card_number: card_detail.card_number,\n card_exp_month: card_detail.card_exp_month,\n card_exp_year: card_detail.card_exp_year,\n card_cvc,\n card_issuer: card_detail.card_issuer,\n card_network: card_detail.card_network,\n card_type: card_detail.card_type.map(|val| val.to_string()),\n card_issuing_country: card_detail.card_issuing_country.map(|val| val.to_string()),\n card_issuing_country_code: None,\n bank_code: None,\n nick_name: card_detail.nick_name,\n card_holder_name: card_holder_name.or(card_detail.card_holder_name),\n co_badged_card_data: None,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for payment_methods::CardDetail {\n fn from(card: Card) -> Self {\n Self {\n card_number: card.card_number,\n card_exp_month: card.card_exp_month,\n card_exp_year: card.card_exp_year,\n card_holder_name: card.card_holder_name,\n nick_name: card.nick_name,\n card_issuing_country: None,\n card_network: card.card_network,\n card_issuer: card.card_issuer,\n card_type: None,\n card_cvc: Some(card.card_cvc),\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for payment_methods::ProxyCardDetails {\n fn from(card: ExternalVaultCard) -> Self {\n Self {\n card_number: card.card_number,\n card_exp_month: card.card_exp_month,\n card_exp_year: card.card_exp_year,\n card_holder_name: card.card_holder_name,\n nick_name: card.nick_name,\n card_issuing_country: card.card_issuing_country,\n card_network: card.card_network,\n card_issuer: card.card_issuer,\n card_type: card.card_type,\n card_cvc: Some(card.card_cvc),\n bin_number: card.bin_number,\n last_four: card.last_four,\n }\n }\n}\n\nimpl From for CardRedirectData {\n fn from(value: api_models::payments::CardRedirectData) -> Self {\n match value {\n api_models::payments::CardRedirectData::Knet {} => Self::Knet {},\n api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {},\n api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {},\n api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {},\n }\n }\n}\n\nimpl From for api_models::payments::CardRedirectData {\n fn from(value: CardRedirectData) -> Self {\n match value {\n CardRedirectData::Knet {} => Self::Knet {},\n CardRedirectData::Benefit {} => Self::Benefit {},\n CardRedirectData::MomoAtm {} => Self::MomoAtm {},\n CardRedirectData::CardRedirect {} => Self::CardRedirect {},\n }\n }\n}\n\nimpl From for WalletData {\n fn from(value: api_models::payments::WalletData) -> Self {\n match value {\n api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})),\n api_models::payments::WalletData::AliPayRedirect(_) => {\n Self::AliPayRedirect(AliPayRedirection {})\n }\n api_models::payments::WalletData::AliPayHkRedirect(_) => {\n Self::AliPayHkRedirect(AliPayHkRedirection {})\n }\n api_models::payments::WalletData::AmazonPay(amazon_pay_data) => {\n Self::AmazonPay(AmazonPayWalletData::from(amazon_pay_data))\n }\n api_models::payments::WalletData::AmazonPayRedirect(_) => {\n Self::AmazonPayRedirect(Box::new(AmazonPayRedirect {}))\n }\n api_models::payments::WalletData::Skrill(_) => Self::Skrill(Box::new(SkrillData {})),\n api_models::payments::WalletData::Paysera(_) => Self::Paysera(Box::new(PayseraData {})),\n api_models::payments::WalletData::MomoRedirect(_) => {\n Self::MomoRedirect(MomoRedirection {})\n }\n api_models::payments::WalletData::KakaoPayRedirect(_) => {\n Self::KakaoPayRedirect(KakaoPayRedirection {})\n }\n api_models::payments::WalletData::GoPayRedirect(_) => {\n Self::GoPayRedirect(GoPayRedirection {})\n }\n api_models::payments::WalletData::GcashRedirect(_) => {\n Self::GcashRedirect(GcashRedirection {})\n }\n api_models::payments::WalletData::ApplePay(apple_pay_data) => {\n Self::ApplePay(ApplePayWalletData::from(apple_pay_data))\n }\n api_models::payments::WalletData::ApplePayRedirect(_) => {\n Self::ApplePayRedirect(Box::new(ApplePayRedirectData {}))\n }\n api_models::payments::WalletData::ApplePayThirdPartySdk(apple_pay_sdk_data) => {\n Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData {\n token: apple_pay_sdk_data.token,\n }))\n }\n api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {},\n api_models::payments::WalletData::GooglePay(google_pay_data) => {\n Self::GooglePay(GooglePayWalletData::from(google_pay_data))\n }\n api_models::payments::WalletData::GooglePayRedirect(_) => {\n Self::GooglePayRedirect(Box::new(GooglePayRedirectData {}))\n }\n api_models::payments::WalletData::GooglePayThirdPartySdk(google_pay_sdk_data) => {\n Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData {\n token: google_pay_sdk_data.token,\n }))\n }\n api_models::payments::WalletData::MbWayRedirect(..) => {\n Self::MbWayRedirect(Box::new(MbWayRedirection {}))\n }\n api_models::payments::WalletData::MobilePayRedirect(_) => {\n Self::MobilePayRedirect(Box::new(MobilePayRedirection {}))\n }\n api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {\n Self::PaypalRedirect(PaypalRedirection {\n email: paypal_redirect_data.email,\n })\n }\n api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {\n Self::PaypalSdk(PayPalWalletData {\n token: paypal_sdk_data.token,\n })\n }\n api_models::payments::WalletData::Paze(paze_data) => {\n Self::Paze(PazeWalletData::from(paze_data))\n }\n api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {\n Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data)))\n }\n api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},\n api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},\n api_models::payments::WalletData::TouchNGoRedirect(_) => {\n Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {}))\n }\n api_models::payments::WalletData::WeChatPayRedirect(_) => {\n Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {}))\n }\n api_models::payments::WalletData::WeChatPayQr(_) => {\n Self::WeChatPayQr(Box::new(WeChatPayQr {}))\n }\n api_models::payments::WalletData::CashappQr(_) => {\n Self::CashappQr(Box::new(CashappQr {}))\n }\n api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}),\n api_models::payments::WalletData::Mifinity(mifinity_data) => {\n Self::Mifinity(MifinityData {\n date_of_birth: mifinity_data.date_of_birth,\n language_preference: mifinity_data.language_preference,\n })\n }\n api_models::payments::WalletData::BluecodeRedirect {} => Self::BluecodeRedirect {},\n api_models::payments::WalletData::RevolutPay(_) => Self::RevolutPay(RevolutPayData {}),\n }\n }\n}\n\nimpl From for GooglePayWalletData {\n fn from(value: api_models::payments::GooglePayWalletData) -> Self {\n Self {\n pm_type: value.pm_type,\n description: value.description,\n info: GooglePayPaymentMethodInfo {\n card_network: value.info.card_network,\n card_details: value.info.card_details,\n assurance_details: value.info.assurance_details.map(|info| {\n GooglePayAssuranceDetails {\n card_holder_authenticated: info.card_holder_authenticated,\n account_verified: info.account_verified,\n }\n }),\n card_funding_source: value.info.card_funding_source,\n },\n tokenization_data: value.tokenization_data,\n }\n }\n}\n\nimpl From for ApplePayWalletData {\n fn from(value: api_models::payments::ApplePayWalletData) -> Self {\n Self {\n payment_data: value.payment_data,\n payment_method: ApplepayPaymentMethod {\n display_name: value.payment_method.display_name,\n network: value.payment_method.network,\n pm_type: value.payment_method.pm_type,\n },\n transaction_identifier: value.transaction_identifier,\n }\n }\n}\n\nimpl From for AmazonPayWalletData {\n fn from(value: api_models::payments::AmazonPayWalletData) -> Self {\n Self {\n checkout_session_id: value.checkout_session_id,\n }\n }\n}\n\nimpl From for SamsungPayTokenData {\n fn from(samsung_pay_token_data: api_models::payments::SamsungPayTokenData) -> Self {\n Self {\n three_ds_type: samsung_pay_token_data.three_ds_type,\n version: samsung_pay_token_data.version,\n data: samsung_pay_token_data.data,\n }\n }\n}\n\nimpl From for PazeWalletData {\n fn from(value: api_models::payments::PazeWalletData) -> Self {\n Self {\n complete_response: value.complete_response,\n }\n }\n}\n\nimpl From> for SamsungPayWalletData {\n fn from(value: Box) -> Self {\n match value.payment_credential {\n api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForApp(\n samsung_pay_app_wallet_data,\n ) => Self {\n payment_credential: SamsungPayWalletCredentials {\n method: samsung_pay_app_wallet_data.method,\n recurring_payment: samsung_pay_app_wallet_data.recurring_payment,\n card_brand: samsung_pay_app_wallet_data.payment_card_brand.into(),\n dpan_last_four_digits: samsung_pay_app_wallet_data.payment_last4_dpan,\n card_last_four_digits: samsung_pay_app_wallet_data.payment_last4_fpan,\n token_data: samsung_pay_app_wallet_data.token_data.into(),\n },\n },\n api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForWeb(\n samsung_pay_web_wallet_data,\n ) => Self {\n payment_credential: SamsungPayWalletCredentials {\n method: samsung_pay_web_wallet_data.method,\n recurring_payment: samsung_pay_web_wallet_data.recurring_payment,\n card_brand: samsung_pay_web_wallet_data.card_brand.into(),\n dpan_last_four_digits: None,\n card_last_four_digits: samsung_pay_web_wallet_data.card_last_four_digits,\n token_data: samsung_pay_web_wallet_data.token_data.into(),\n },\n },\n }\n }\n}\n\nimpl From for PayLaterData {\n fn from(value: api_models::payments::PayLaterData) -> Self {\n match value {\n api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},\n api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },\n api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},\n api_models::payments::PayLaterData::FlexitiRedirect {} => Self::FlexitiRedirect {},\n api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {\n Self::AfterpayClearpayRedirect {}\n }\n api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {},\n api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {},\n api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {},\n api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {},\n api_models::payments::PayLaterData::BreadpayRedirect {} => Self::BreadpayRedirect {},\n api_models::payments::PayLaterData::PayjustnowRedirect {} => {\n Self::PayjustnowRedirect {}\n }\n }\n }\n}\n\nimpl From for BankRedirectData {\n fn from(value: api_models::payments::BankRedirectData) -> Self {\n match value {\n api_models::payments::BankRedirectData::BancontactCard {\n card_number,\n card_exp_month,\n card_exp_year,\n card_holder_name,\n ..\n } => Self::BancontactCard {\n card_number,\n card_exp_month,\n card_exp_year,\n card_holder_name,\n },\n api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},\n api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },\n api_models::payments::BankRedirectData::Eps {\n bank_name, country, ..\n } => Self::Eps { bank_name, country },\n api_models::payments::BankRedirectData::Giropay {\n bank_account_bic,\n bank_account_iban,\n country,\n ..\n } => Self::Giropay {\n bank_account_bic,\n bank_account_iban,\n country,\n },\n api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {\n Self::Ideal { bank_name }\n }\n api_models::payments::BankRedirectData::Interac { country, email } => {\n Self::Interac { country, email }\n }\n api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {\n Self::OnlineBankingCzechRepublic { issuer }\n }\n api_models::payments::BankRedirectData::OnlineBankingFinland { email } => {\n Self::OnlineBankingFinland { email }\n }\n api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {\n Self::OnlineBankingPoland { issuer }\n }\n api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {\n Self::OnlineBankingSlovakia { issuer }\n }\n api_models::payments::BankRedirectData::OpenBankingUk {\n country, issuer, ..\n } => Self::OpenBankingUk { country, issuer },\n api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => {\n Self::Przelewy24 { bank_name }\n }\n api_models::payments::BankRedirectData::Sofort {\n preferred_language,\n country,\n ..\n } => Self::Sofort {\n country,\n preferred_language,\n },\n api_models::payments::BankRedirectData::Trustly { country } => Self::Trustly {\n country: Some(country),\n },\n api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {\n Self::OnlineBankingFpx { issuer }\n }\n api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {\n Self::OnlineBankingThailand { issuer }\n }\n api_models::payments::BankRedirectData::LocalBankRedirect { .. } => {\n Self::LocalBankRedirect {}\n }\n api_models::payments::BankRedirectData::Eft { provider } => Self::Eft { provider },\n api_models::payments::BankRedirectData::OpenBanking { .. } => Self::OpenBanking {},\n }\n }\n}\n\nimpl From for CryptoData {\n fn from(value: api_models::payments::CryptoData) -> Self {\n let api_models::payments::CryptoData {\n pay_currency,\n network,\n } = value;\n Self {\n pay_currency,\n network,\n }\n }\n}\n\nimpl From for api_models::payments::CryptoData {\n fn from(value: CryptoData) -> Self {\n let CryptoData {\n pay_currency,\n network,\n } = value;\n Self {\n pay_currency,\n network,\n }\n }\n}\n\nimpl From for UpiData {\n fn from(value: api_models::payments::UpiData) -> Self {\n match value {\n api_models::payments::UpiData::UpiCollect(upi) => Self::UpiCollect(UpiCollectData {\n vpa_id: upi.vpa_id,\n upi_source: upi.upi_source.map(UpiSource::from),\n }),\n api_models::payments::UpiData::UpiIntent(upi) => Self::UpiIntent(UpiIntentData {\n upi_source: upi.upi_source.map(UpiSource::from),\n app_name: upi.app_name,\n }),\n api_models::payments::UpiData::UpiQr(upi) => Self::UpiQr(UpiQrData {\n upi_source: upi.upi_source.map(UpiSource::from),\n }),\n }\n }\n}\n\nimpl From for api_models::payments::additional_info::UpiAdditionalData {\n fn from(value: UpiData) -> Self {\n match value {\n UpiData::UpiCollect(upi) => Self::UpiCollect(Box::new(\n payment_additional_types::UpiCollectAdditionalData {\n vpa_id: upi.vpa_id.map(MaskedUpiVpaId::from),\n upi_source: upi.upi_source.map(api_models::payments::UpiSource::from),\n },\n )),\n UpiData::UpiIntent(upi) => {\n Self::UpiIntent(Box::new(api_models::payments::UpiIntentData {\n upi_source: upi.upi_source.map(api_models::payments::UpiSource::from),\n app_name: upi.app_name,\n }))\n }\n UpiData::UpiQr(upi) => Self::UpiQr(Box::new(api_models::payments::UpiQrData {\n upi_source: upi.upi_source.map(api_models::payments::UpiSource::from),\n })),\n }\n }\n}\n\nimpl From for VoucherData {\n fn from(value: api_models::payments::VoucherData) -> Self {\n match value {\n api_models::payments::VoucherData::Boleto(boleto_data) => {\n Self::Boleto(Box::new(BoletoVoucherData {\n social_security_number: boleto_data.social_security_number,\n bank_number: boleto_data.bank_number,\n document_type: boleto_data.document_type,\n fine_percentage: boleto_data.fine_percentage,\n fine_quantity_days: boleto_data.fine_quantity_days,\n interest_percentage: boleto_data.interest_percentage,\n write_off_quantity_days: boleto_data.write_off_quantity_days,\n messages: boleto_data.messages,\n due_date: boleto_data.due_date,\n }))\n }\n api_models::payments::VoucherData::Alfamart(_) => {\n Self::Alfamart(Box::new(AlfamartVoucherData {}))\n }\n api_models::payments::VoucherData::Indomaret(_) => {\n Self::Indomaret(Box::new(IndomaretVoucherData {}))\n }\n api_models::payments::VoucherData::SevenEleven(_)\n | api_models::payments::VoucherData::Lawson(_)\n | api_models::payments::VoucherData::MiniStop(_)\n | api_models::payments::VoucherData::FamilyMart(_)\n | api_models::payments::VoucherData::Seicomart(_)\n | api_models::payments::VoucherData::PayEasy(_) => {\n Self::SevenEleven(Box::new(JCSVoucherData {}))\n }\n api_models::payments::VoucherData::Efecty => Self::Efecty,\n api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,\n api_models::payments::VoucherData::RedCompra => Self::RedCompra,\n api_models::payments::VoucherData::RedPagos => Self::RedPagos,\n api_models::payments::VoucherData::Oxxo => Self::Oxxo,\n }\n }\n}\n\nimpl From> for Box {\n fn from(value: Box) -> Self {\n Self::new(api_models::payments::BoletoVoucherData {\n social_security_number: value.social_security_number,\n bank_number: value.bank_number,\n document_type: value.document_type,\n fine_percentage: value.fine_percentage,\n fine_quantity_days: value.fine_quantity_days,\n interest_percentage: value.interest_percentage,\n write_off_quantity_days: value.write_off_quantity_days,\n messages: value.messages,\n due_date: value.due_date,\n })\n }\n}\n\nimpl From> for Box {\n fn from(_value: Box) -> Self {\n Self::new(api_models::payments::AlfamartVoucherData {\n first_name: None,\n last_name: None,\n email: None,\n })\n }\n}\n\nimpl From> for Box {\n fn from(_value: Box) -> Self {\n Self::new(api_models::payments::IndomaretVoucherData {\n first_name: None,\n last_name: None,\n email: None,\n })\n }\n}\n\nimpl From> for Box {\n fn from(_value: Box) -> Self {\n Self::new(api_models::payments::JCSVoucherData {\n first_name: None,\n last_name: None,\n email: None,\n phone_number: None,\n })\n }\n}\n\nimpl From for api_models::payments::VoucherData {\n fn from(value: VoucherData) -> Self {\n match value {\n VoucherData::Boleto(boleto_data) => Self::Boleto(boleto_data.into()),\n VoucherData::Alfamart(alfa_mart) => Self::Alfamart(alfa_mart.into()),\n VoucherData::Indomaret(info_maret) => Self::Indomaret(info_maret.into()),\n VoucherData::SevenEleven(jcs_data)\n | VoucherData::Lawson(jcs_data)\n | VoucherData::MiniStop(jcs_data)\n | VoucherData::FamilyMart(jcs_data)\n | VoucherData::Seicomart(jcs_data)\n | VoucherData::PayEasy(jcs_data) => Self::SevenEleven(jcs_data.into()),\n VoucherData::Efecty => Self::Efecty,\n VoucherData::PagoEfectivo => Self::PagoEfectivo,\n VoucherData::RedCompra => Self::RedCompra,\n VoucherData::RedPagos => Self::RedPagos,\n VoucherData::Oxxo => Self::Oxxo,\n }\n }\n}\n\nimpl From for GiftCardData {\n fn from(value: api_models::payments::GiftCardData) -> Self {\n match value {\n api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {\n number: details.number,\n cvc: details.cvc,\n }),\n api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},\n api_models::payments::GiftCardData::BhnCardNetwork(details) => {\n Self::BhnCardNetwork(BHNGiftCardDetails {\n account_number: details.account_number,\n pin: details.pin,\n cvv2: details.cvv2,\n expiration_date: details.expiration_date,\n })\n }\n }\n }\n}\n\nimpl From for payment_additional_types::GiftCardAdditionalData {\n fn from(value: GiftCardData) -> Self {\n match value {\n GiftCardData::Givex(details) => Self::Givex(Box::new(\n payment_additional_types::GivexGiftCardAdditionalData {\n last4: details\n .number\n .peek()\n .chars()\n .rev()\n .take(4)\n .collect::()\n .chars()\n .rev()\n .collect::()\n .into(),\n },\n )),\n GiftCardData::PaySafeCard {} => Self::PaySafeCard {},\n GiftCardData::BhnCardNetwork(_) => Self::BhnCardNetwork {},\n }\n }\n}\n\nimpl From for CardToken {\n fn from(value: api_models::payments::CardToken) -> Self {\n let api_models::payments::CardToken {\n card_holder_name,\n card_cvc,\n } = value;\n Self {\n card_holder_name,\n card_cvc,\n }\n }\n}\n\nimpl From for payment_additional_types::CardTokenAdditionalData {\n fn from(value: CardToken) -> Self {\n let CardToken {\n card_holder_name, ..\n } = value;\n Self { card_holder_name }\n }\n}\n\nimpl From for BankDebitData {\n fn from(value: api_models::payments::BankDebitData) -> Self {\n match value {\n api_models::payments::BankDebitData::AchBankDebit {\n account_number,\n routing_number,\n card_holder_name,\n bank_account_holder_name,\n bank_name,\n bank_type,\n bank_holder_type,\n ..\n } => Self::AchBankDebit {\n account_number,\n routing_number,\n card_holder_name,\n bank_account_holder_name,\n bank_name,\n bank_type,\n bank_holder_type,\n },\n api_models::payments::BankDebitData::SepaBankDebit {\n iban,\n bank_account_holder_name,\n ..\n } => Self::SepaBankDebit {\n iban,\n bank_account_holder_name,\n },\n api_models::payments::BankDebitData::SepaGuarenteedBankDebit {\n iban,\n bank_account_holder_name,\n ..\n } => Self::SepaBankDebit {\n iban,\n bank_account_holder_name,\n },\n api_models::payments::BankDebitData::BecsBankDebit {\n account_number,\n bsb_number,\n bank_account_holder_name,\n ..\n } => Self::BecsBankDebit {\n account_number,\n bsb_number,\n bank_account_holder_name,\n },\n api_models::payments::BankDebitData::BacsBankDebit {\n account_number,\n sort_code,\n bank_account_holder_name,\n ..\n } => Self::BacsBankDebit {\n account_number,\n sort_code,\n bank_account_holder_name,\n },\n }\n }\n}\n\nimpl From for api_models::payments::additional_info::BankDebitAdditionalData {\n fn from(value: BankDebitData) -> Self {\n match value {\n BankDebitData::AchBankDebit {\n account_number,\n routing_number,\n bank_name,\n bank_type,\n bank_holder_type,\n card_holder_name,\n bank_account_holder_name,\n } => Self::Ach(Box::new(\n payment_additional_types::AchBankDebitAdditionalData {\n account_number: MaskedBankAccount::from(account_number),\n routing_number: MaskedRoutingNumber::from(routing_number),\n bank_name,\n bank_type,\n bank_holder_type,\n card_holder_name,\n bank_account_holder_name,\n },\n )),\n BankDebitData::SepaBankDebit {\n iban,\n bank_account_holder_name,\n } => Self::Sepa(Box::new(\n payment_additional_types::SepaBankDebitAdditionalData {\n iban: MaskedIban::from(iban),\n bank_account_holder_name,\n },\n )),\n BankDebitData::SepaGuarenteedBankDebit {\n iban,\n bank_account_holder_name,\n } => Self::SepaGuarenteedDebit(Box::new(\n payment_additional_types::SepaBankDebitAdditionalData {\n iban: MaskedIban::from(iban),\n bank_account_holder_name,\n },\n )),\n BankDebitData::BecsBankDebit {\n account_number,\n bsb_number,\n bank_account_holder_name,\n } => Self::Becs(Box::new(\n payment_additional_types::BecsBankDebitAdditionalData {\n account_number: MaskedBankAccount::from(account_number),\n bsb_number,\n bank_account_holder_name,\n },\n )),\n BankDebitData::BacsBankDebit {\n account_number,\n sort_code,\n bank_account_holder_name,\n } => Self::Bacs(Box::new(\n payment_additional_types::BacsBankDebitAdditionalData {\n account_number: MaskedBankAccount::from(account_number),\n sort_code: MaskedSortCode::from(sort_code),\n bank_account_holder_name,\n },\n )),\n }\n }\n}\n\nimpl From for BankTransferData {\n fn from(value: api_models::payments::BankTransferData) -> Self {\n match value {\n api_models::payments::BankTransferData::AchBankTransfer { .. } => {\n Self::AchBankTransfer {}\n }\n api_models::payments::BankTransferData::SepaBankTransfer { .. } => {\n Self::SepaBankTransfer {}\n }\n api_models::payments::BankTransferData::BacsBankTransfer { .. } => {\n Self::BacsBankTransfer {}\n }\n api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {\n Self::MultibancoBankTransfer {}\n }\n api_models::payments::BankTransferData::PermataBankTransfer { .. } => {\n Self::PermataBankTransfer {}\n }\n api_models::payments::BankTransferData::BcaBankTransfer { .. } => {\n Self::BcaBankTransfer {}\n }\n api_models::payments::BankTransferData::BniVaBankTransfer { .. } => {\n Self::BniVaBankTransfer {}\n }\n api_models::payments::BankTransferData::BriVaBankTransfer { .. } => {\n Self::BriVaBankTransfer {}\n }\n api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => {\n Self::CimbVaBankTransfer {}\n }\n api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => {\n Self::DanamonVaBankTransfer {}\n }\n api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => {\n Self::MandiriVaBankTransfer {}\n }\n api_models::payments::BankTransferData::Pix {\n pix_key,\n cpf,\n cnpj,\n source_bank_account_id,\n destination_bank_account_id,\n expiry_date,\n } => Self::Pix {\n pix_key,\n cpf,\n cnpj,\n source_bank_account_id,\n destination_bank_account_id,\n expiry_date,\n },\n api_models::payments::BankTransferData::Pse {} => Self::Pse {},\n api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => {\n Self::LocalBankTransfer { bank_code }\n }\n api_models::payments::BankTransferData::InstantBankTransfer {} => {\n Self::InstantBankTransfer {}\n }\n api_models::payments::BankTransferData::InstantBankTransferFinland {} => {\n Self::InstantBankTransferFinland {}\n }\n api_models::payments::BankTransferData::InstantBankTransferPoland {} => {\n Self::InstantBankTransferPoland {}\n }\n api_models::payments::BankTransferData::IndonesianBankTransfer { bank_name } => {\n Self::IndonesianBankTransfer { bank_name }\n }\n }\n }\n}\n\nimpl From for api_models::payments::additional_info::BankTransferAdditionalData {\n fn from(value: BankTransferData) -> Self {\n match value {\n BankTransferData::AchBankTransfer {} => Self::Ach {},\n\n BankTransferData::SepaBankTransfer {} => Self::Sepa(Box::new(\n api_models::payments::additional_info::SepaBankTransferPaymentAdditionalData {\n debitor_iban: None,\n debitor_bic: None,\n debitor_name: None,\n debitor_email: None,\n },\n )),\n BankTransferData::BacsBankTransfer {} => Self::Bacs {},\n BankTransferData::MultibancoBankTransfer {} => Self::Multibanco {},\n BankTransferData::PermataBankTransfer {} => Self::Permata {},\n BankTransferData::BcaBankTransfer {} => Self::Bca {},\n BankTransferData::BniVaBankTransfer {} => Self::BniVa {},\n BankTransferData::BriVaBankTransfer {} => Self::BriVa {},\n BankTransferData::CimbVaBankTransfer {} => Self::CimbVa {},\n BankTransferData::DanamonVaBankTransfer {} => Self::DanamonVa {},\n BankTransferData::MandiriVaBankTransfer {} => Self::MandiriVa {},\n BankTransferData::Pix {\n pix_key,\n cpf,\n cnpj,\n source_bank_account_id,\n destination_bank_account_id,\n expiry_date,\n } => Self::Pix(Box::new(\n api_models::payments::additional_info::PixBankTransferAdditionalData {\n pix_key: pix_key.map(MaskedBankAccount::from),\n cpf: cpf.map(MaskedBankAccount::from),\n cnpj: cnpj.map(MaskedBankAccount::from),\n source_bank_account_id,\n destination_bank_account_id,\n expiry_date,\n },\n )),\n BankTransferData::Pse {} => Self::Pse {},\n BankTransferData::LocalBankTransfer { bank_code } => Self::LocalBankTransfer(Box::new(\n api_models::payments::additional_info::LocalBankTransferAdditionalData {\n bank_code: bank_code.map(MaskedBankAccount::from),\n },\n )),\n BankTransferData::InstantBankTransfer {} => Self::InstantBankTransfer {},\n BankTransferData::InstantBankTransferFinland {} => Self::InstantBankTransferFinland {},\n BankTransferData::InstantBankTransferPoland {} => Self::InstantBankTransferPoland {},\n BankTransferData::IndonesianBankTransfer { bank_name } => {\n Self::IndonesianBankTransfer { bank_name }\n }\n }\n }\n}\n\nimpl From for RealTimePaymentData {\n fn from(value: api_models::payments::RealTimePaymentData) -> Self {\n match value {\n api_models::payments::RealTimePaymentData::Fps {} => Self::Fps {},\n api_models::payments::RealTimePaymentData::DuitNow {} => Self::DuitNow {},\n api_models::payments::RealTimePaymentData::PromptPay {} => Self::PromptPay {},\n api_models::payments::RealTimePaymentData::VietQr {} => Self::VietQr {},\n api_models::payments::RealTimePaymentData::Qris {} => Self::VietQr {},\n }\n }\n}\n\nimpl From for api_models::payments::RealTimePaymentData {\n fn from(value: RealTimePaymentData) -> Self {\n match value {\n RealTimePaymentData::Fps {} => Self::Fps {},\n RealTimePaymentData::DuitNow {} => Self::DuitNow {},\n RealTimePaymentData::PromptPay {} => Self::PromptPay {},\n RealTimePaymentData::VietQr {} => Self::VietQr {},\n RealTimePaymentData::Qris {} => Self::Qris {},\n }\n }\n}\n\nimpl From for OpenBankingData {\n fn from(value: api_models::payments::OpenBankingData) -> Self {\n match value {\n api_models::payments::OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},\n }\n }\n}\n\nimpl From for api_models::payments::OpenBankingData {\n fn from(value: OpenBankingData) -> Self {\n match value {\n OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},\n }\n }\n}\n\nimpl From for MobilePaymentData {\n fn from(value: api_models::payments::MobilePaymentData) -> Self {\n match value {\n api_models::payments::MobilePaymentData::DirectCarrierBilling {\n msisdn,\n client_uid,\n } => Self::DirectCarrierBilling { msisdn, client_uid },\n }\n }\n}\n\nimpl From for api_models::payments::MobilePaymentData {\n fn from(value: MobilePaymentData) -> Self {\n match value {\n MobilePaymentData::DirectCarrierBilling { msisdn, client_uid } => {\n Self::DirectCarrierBilling { msisdn, client_uid }\n }\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for NetworkTokenData {\n fn from(network_token_data: api_models::payments::NetworkTokenData) -> Self {\n Self {\n token_number: network_token_data.network_token,\n token_exp_month: network_token_data.token_exp_month,\n token_exp_year: network_token_data.token_exp_year,\n token_cryptogram: Some(network_token_data.token_cryptogram),\n card_issuer: network_token_data.card_issuer,\n card_network: network_token_data.card_network,\n card_type: network_token_data.card_type,\n card_issuing_country: network_token_data.card_issuing_country,\n bank_code: network_token_data.bank_code,\n nick_name: network_token_data.nick_name,\n eci: network_token_data.eci,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for NetworkTokenData {\n fn from(network_token_data: api_models::payments::NetworkTokenData) -> Self {\n Self {\n network_token: network_token_data.network_token,\n network_token_exp_month: network_token_data.token_exp_month,\n network_token_exp_year: network_token_data.token_exp_year,\n cryptogram: Some(network_token_data.token_cryptogram),\n card_issuer: network_token_data.card_issuer,\n card_network: network_token_data.card_network,\n card_type: network_token_data\n .card_type\n .and_then(|ct| payment_methods::CardType::from_str(&ct).ok()),\n card_issuing_country: network_token_data\n .card_issuing_country\n .and_then(|country| api_enums::CountryAlpha2::from_str(&country).ok()),\n bank_code: network_token_data.bank_code,\n card_holder_name: network_token_data.card_holder_name,\n nick_name: network_token_data.nick_name,\n eci: network_token_data.eci,\n }\n }\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct TokenizedCardValue1 {\n pub card_number: String,\n pub exp_year: String,\n pub exp_month: String,\n pub nickname: Option,\n pub card_last_four: Option,\n pub card_token: Option,\n pub card_holder_name: Option>,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct TokenizedCardValue2 {\n pub card_security_code: Option,\n pub card_fingerprint: Option,\n pub external_id: Option,\n pub customer_id: Option,\n pub payment_method_id: Option,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedWalletValue1 {\n pub data: WalletData,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedWalletValue2 {\n pub customer_id: Option,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedBankTransferValue1 {\n pub data: BankTransferData,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedBankTransferValue2 {\n pub customer_id: Option,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedBankRedirectValue1 {\n pub data: BankRedirectData,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedBankRedirectValue2 {\n pub customer_id: Option,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedBankDebitValue2 {\n pub customer_id: Option,\n}\n\n#[derive(Debug, serde::Serialize, serde::Deserialize)]\npub struct TokenizedBankDebitValue1 {\n pub data: BankDebitData,\n}\n\npub trait GetPaymentMethodType {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType;\n}\n\nimpl GetPaymentMethodType for CardRedirectData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::Knet {} => api_enums::PaymentMethodType::Knet,\n Self::Benefit {} => api_enums::PaymentMethodType::Benefit,\n Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm,\n Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect,\n }\n }\n}\n\nimpl GetPaymentMethodType for WalletData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay,\n Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk,\n Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay,\n Self::Skrill(_) => api_enums::PaymentMethodType::Skrill,\n Self::Paysera(_) => api_enums::PaymentMethodType::Paysera,\n Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo,\n Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay,\n Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay,\n Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash,\n Self::AmazonPay(_) => api_enums::PaymentMethodType::AmazonPay,\n Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => {\n api_enums::PaymentMethodType::ApplePay\n }\n Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana,\n Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => {\n api_enums::PaymentMethodType::GooglePay\n }\n Self::BluecodeRedirect {} => api_enums::PaymentMethodType::Bluecode,\n Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay,\n Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay,\n Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal,\n Self::Paze(_) => api_enums::PaymentMethodType::Paze,\n Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay,\n Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint,\n Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps,\n Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo,\n Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => {\n api_enums::PaymentMethodType::WeChatPay\n }\n Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp,\n Self::SwishQr(_) => api_enums::PaymentMethodType::Swish,\n Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity,\n Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay,\n }\n }\n}\n\nimpl GetPaymentMethodType for PayLaterData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna,\n Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna,\n Self::FlexitiRedirect { .. } => api_enums::PaymentMethodType::Flexiti,\n Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm,\n Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay,\n Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright,\n Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley,\n Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma,\n Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome,\n Self::BreadpayRedirect {} => api_enums::PaymentMethodType::Breadpay,\n Self::PayjustnowRedirect {} => api_enums::PaymentMethodType::Payjustnow,\n }\n }\n}\n\nimpl GetPaymentMethodType for BankRedirectData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard,\n Self::Bizum {} => api_enums::PaymentMethodType::Bizum,\n Self::Blik { .. } => api_enums::PaymentMethodType::Blik,\n Self::Eft { .. } => api_enums::PaymentMethodType::Eft,\n Self::Eps { .. } => api_enums::PaymentMethodType::Eps,\n Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay,\n Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal,\n Self::Interac { .. } => api_enums::PaymentMethodType::Interac,\n Self::OnlineBankingCzechRepublic { .. } => {\n api_enums::PaymentMethodType::OnlineBankingCzechRepublic\n }\n Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland,\n Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland,\n Self::OnlineBankingSlovakia { .. } => {\n api_enums::PaymentMethodType::OnlineBankingSlovakia\n }\n Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk,\n Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24,\n Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort,\n Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly,\n Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx,\n Self::OnlineBankingThailand { .. } => {\n api_enums::PaymentMethodType::OnlineBankingThailand\n }\n Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect,\n Self::OpenBanking { .. } => api_enums::PaymentMethodType::OpenBanking,\n }\n }\n}\n\nimpl GetPaymentMethodType for BankDebitData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach,\n Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa,\n Self::SepaGuarenteedBankDebit { .. } => {\n api_enums::PaymentMethodType::SepaGuarenteedDebit\n }\n Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs,\n Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs,\n }\n }\n}\n\nimpl GetPaymentMethodType for BankTransferData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach,\n Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::Sepa,\n Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs,\n Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco,\n Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer,\n Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer,\n Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa,\n Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa,\n Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa,\n Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa,\n Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa,\n Self::Pix { .. } => api_enums::PaymentMethodType::Pix,\n Self::Pse {} => api_enums::PaymentMethodType::Pse,\n Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer,\n Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer,\n Self::InstantBankTransferFinland {} => {\n api_enums::PaymentMethodType::InstantBankTransferFinland\n }\n Self::InstantBankTransferPoland {} => {\n api_enums::PaymentMethodType::InstantBankTransferPoland\n }\n Self::IndonesianBankTransfer { .. } => {\n api_enums::PaymentMethodType::IndonesianBankTransfer\n }\n }\n }\n}\n\nimpl GetPaymentMethodType for CryptoData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n api_enums::PaymentMethodType::CryptoCurrency\n }\n}\n\nimpl GetPaymentMethodType for RealTimePaymentData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::Fps {} => api_enums::PaymentMethodType::Fps,\n Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow,\n Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay,\n Self::VietQr {} => api_enums::PaymentMethodType::VietQr,\n Self::Qris {} => api_enums::PaymentMethodType::Qris {},\n }\n }\n}\n\nimpl GetPaymentMethodType for UpiData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect,\n Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent,\n Self::UpiQr(_) => api_enums::PaymentMethodType::UpiQr,\n }\n }\n}\nimpl GetPaymentMethodType for VoucherData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::Boleto(_) => api_enums::PaymentMethodType::Boleto,\n Self::Efecty => api_enums::PaymentMethodType::Efecty,\n Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo,\n Self::RedCompra => api_enums::PaymentMethodType::RedCompra,\n Self::RedPagos => api_enums::PaymentMethodType::RedPagos,\n Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart,\n Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret,\n Self::Oxxo => api_enums::PaymentMethodType::Oxxo,\n Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven,\n Self::Lawson(_) => api_enums::PaymentMethodType::Lawson,\n Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop,\n Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart,\n Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart,\n Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy,\n }\n }\n}\nimpl GetPaymentMethodType for GiftCardData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::Givex(_) => api_enums::PaymentMethodType::Givex,\n Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard,\n Self::BhnCardNetwork(_) => api_enums::PaymentMethodType::BhnCardNetwork,\n }\n }\n}\n\nimpl GetPaymentMethodType for OpenBankingData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS,\n }\n }\n}\n\nimpl GetPaymentMethodType for MobilePaymentData {\n fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {\n match self {\n Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling,\n }\n }\n}\n\nimpl From for ExtendedCardInfo {\n fn from(value: Card) -> Self {\n Self {\n card_number: value.card_number,\n card_exp_month: value.card_exp_month,\n card_exp_year: value.card_exp_year,\n card_holder_name: None,\n card_cvc: value.card_cvc,\n card_issuer: value.card_issuer,\n card_network: value.card_network,\n card_type: value.card_type,\n card_issuing_country: value.card_issuing_country,\n bank_code: value.bank_code,\n }\n }\n}\n\npub fn get_applepay_wallet_info(\n item: ApplePayWalletData,\n payment_method_token: Option,\n) -> payment_methods::PaymentMethodDataWalletInfo {\n let (card_exp_month, card_exp_year) = match payment_method_token {\n Some(PaymentMethodToken::ApplePayDecrypt(token)) => (\n Some(token.application_expiration_month.clone()),\n Some(token.application_expiration_year.clone()),\n ),\n _ => (None, None),\n };\n payment_methods::PaymentMethodDataWalletInfo {\n last4: item\n .payment_method\n .display_name\n .chars()\n .rev()\n .take(4)\n .collect::>()\n .into_iter()\n .rev()\n .collect(),\n card_network: item.payment_method.network,\n card_type: Some(item.payment_method.pm_type),\n card_exp_month,\n card_exp_year,\n // To be populated after connector response\n auth_code: None,\n }\n}\n\npub fn get_googlepay_wallet_info(\n item: GooglePayWalletData,\n payment_method_token: Option,\n) -> payment_methods::PaymentMethodDataWalletInfo {\n let (card_exp_month, card_exp_year) = match payment_method_token {\n Some(PaymentMethodToken::GooglePayDecrypt(token)) => (\n Some(token.card_exp_month.clone()),\n Some(token.card_exp_year.clone()),\n ),\n _ => (None, None),\n };\n payment_methods::PaymentMethodDataWalletInfo {\n last4: item.info.card_details,\n card_network: item.info.card_network,\n card_type: Some(item.pm_type),\n card_exp_month,\n card_exp_year,\n // to be populated after connector response\n auth_code: None,\n }\n}\n\n#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]\npub enum PaymentMethodsData {\n Card(CardDetailsPaymentMethod),\n BankDetails(payment_methods::PaymentMethodDataBankCreds), //PaymentMethodDataBankCreds and its transformations should be moved to the domain models\n WalletDetails(payment_methods::PaymentMethodDataWalletInfo), //PaymentMethodDataWalletInfo and its transformations should be moved to the domain models\n NetworkToken(NetworkTokenDetailsPaymentMethod),\n BankDebit(BankDebitDetailsPaymentMethod),\n}\n\nimpl PaymentMethodsData {\n #[cfg(feature = \"v1\")]\n pub fn get_co_badged_card_data(&self) -> Option {\n if let Self::Card(card) = self {\n card.co_badged_card_data\n .clone()\n .map(|co_badged_card_data_to_be_saved| co_badged_card_data_to_be_saved.into())\n } else {\n None\n }\n }\n #[cfg(feature = \"v2\")]\n pub fn get_co_badged_card_data(&self) -> Option {\n todo!()\n }\n\n #[cfg(feature = \"v1\")]\n pub fn get_additional_payout_method_data(\n &self,\n ) -> Option {\n match self {\n Self::Card(card_details) => {\n router_env::logger::info!(\"Populating AdditionalPayoutMethodData from Card payment method data for recurring payout\");\n Some(payout_method_utils::AdditionalPayoutMethodData::Card(\n Box::new(payout_method_utils::CardAdditionalData {\n card_issuer: card_details.card_issuer.clone(),\n card_network: card_details.card_network.clone(),\n bank_code: None,\n card_type: card_details.card_type.clone(),\n card_issuing_country: card_details.issuer_country.clone(),\n last4: card_details.last4_digits.clone(),\n card_isin: card_details.card_isin.clone(),\n card_extended_bin: None,\n card_exp_month: card_details.expiry_month.clone(),\n card_exp_year: card_details.expiry_year.clone(),\n card_holder_name: card_details.card_holder_name.clone(),\n }),\n ))\n }\n Self::BankDetails(_)\n | Self::WalletDetails(_)\n | Self::NetworkToken(_)\n | Self::BankDebit(_) => None,\n }\n }\n pub fn get_card_details(&self) -> Option {\n if let Self::Card(card) = self {\n Some(card.clone())\n } else {\n None\n }\n }\n}\n\n#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub struct NetworkTokenDetailsPaymentMethod {\n pub last4_digits: Option,\n pub issuer_country: Option,\n pub network_token_expiry_month: Option>,\n pub network_token_expiry_year: Option>,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub card_isin: Option,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n #[serde(default = \"saved_in_locker_default\")]\n pub saved_to_locker: bool,\n}\n\nfn saved_in_locker_default() -> bool {\n true\n}\n\n#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]\n#[serde(rename_all = \"snake_case\")]\npub enum BankDebitDetailsPaymentMethod {\n AchBankDebit {\n masked_account_number: String,\n masked_routing_number: String,\n card_holder_name: Option>,\n bank_account_holder_name: Option>,\n bank_name: Option,\n bank_type: Option,\n bank_holder_type: Option,\n },\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]\npub struct CardDetailsPaymentMethod {\n pub last4_digits: Option,\n pub issuer_country: Option,\n pub issuer_country_code: Option,\n pub expiry_month: Option>,\n pub expiry_year: Option>,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub card_isin: Option,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n #[serde(default = \"saved_in_locker_default\")]\n pub saved_to_locker: bool,\n pub co_badged_card_data: Option,\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub struct CardDetailsPaymentMethod {\n pub last4_digits: Option,\n pub issuer_country: Option,\n pub expiry_month: Option>,\n pub expiry_year: Option>,\n pub nick_name: Option>,\n pub card_holder_name: Option>,\n pub card_isin: Option,\n pub card_issuer: Option,\n pub card_network: Option,\n pub card_type: Option,\n #[serde(default = \"saved_in_locker_default\")]\n pub saved_to_locker: bool,\n}\n\n#[cfg(feature = \"v2\")]\npub struct CardNumberWithStoredDetails {\n pub card_number: cards::CardNumber,\n pub card_details: CardDetailsPaymentMethod,\n}\n\n#[cfg(feature = \"v2\")]\nimpl CardNumberWithStoredDetails {\n pub fn new(card_number: cards::CardNumber, card_details: CardDetailsPaymentMethod) -> Self {\n Self {\n card_number,\n card_details,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl TryFrom for payment_methods::CardDetail {\n type Error = error_stack::Report;\n\n fn try_from(testing: CardNumberWithStoredDetails) -> Result {\n let card_number = testing.card_number;\n let item = testing.card_details;\n Ok(Self {\n card_number,\n card_exp_month: item\n .expiry_month\n .get_required_value(\"expiry_month\")?\n .clone(),\n card_exp_year: item.expiry_year.get_required_value(\"expiry_year\")?.clone(),\n card_holder_name: item.card_holder_name,\n nick_name: item.nick_name,\n card_issuing_country: item\n .issuer_country\n .as_ref()\n .map(|country| api_enums::CountryAlpha2::from_str(country))\n .transpose()\n .ok()\n .flatten(),\n card_network: item.card_network,\n card_issuer: item.card_issuer,\n card_type: item\n .card_type\n .and_then(|card_type| payment_methods::CardType::from_str(&card_type).ok()),\n card_cvc: None,\n })\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl CardDetailsPaymentMethod {\n pub fn to_card_details_from_locker(self) -> payment_methods::CardDetailFromLocker {\n payment_methods::CardDetailFromLocker {\n card_number: None,\n card_holder_name: self.card_holder_name.clone(),\n card_issuer: self.card_issuer.clone(),\n card_network: self.card_network.clone(),\n card_type: self.card_type.clone(),\n issuer_country: self.clone().get_issuer_country_alpha2(),\n last4_digits: self.last4_digits,\n expiry_month: self.expiry_month,\n expiry_year: self.expiry_year,\n card_fingerprint: None,\n nick_name: self.nick_name,\n card_isin: self.card_isin,\n saved_to_locker: self.saved_to_locker,\n }\n }\n\n pub fn get_issuer_country_alpha2(self) -> Option {\n self.issuer_country\n .as_ref()\n .map(|c| api_enums::CountryAlpha2::from_str(c))\n .transpose()\n .ok()\n .flatten()\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for CardDetailsPaymentMethod {\n fn from(item: payment_methods::CardDetail) -> Self {\n Self {\n issuer_country: item.card_issuing_country.map(|c| c.to_string()),\n issuer_country_code: item\n .card_issuing_country_code\n .map(|country_code| country_code.to_string()),\n last4_digits: Some(item.card_number.get_last4()),\n expiry_month: Some(item.card_exp_month),\n expiry_year: Some(item.card_exp_year),\n card_holder_name: item.card_holder_name,\n nick_name: item.nick_name,\n card_isin: None,\n card_issuer: item.card_issuer,\n card_network: item.card_network,\n card_type: item.card_type.map(|card| card.to_string()),\n saved_to_locker: true,\n co_badged_card_data: None,\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl\n From<(\n payment_methods::CardDetailFromLocker,\n Option<&payment_methods::CoBadgedCardData>,\n )> for CardDetailsPaymentMethod\n{\n fn from(\n (item, co_badged_card_data): (\n payment_methods::CardDetailFromLocker,\n Option<&payment_methods::CoBadgedCardData>,\n ),\n ) -> Self {\n Self {\n issuer_country: item.issuer_country,\n last4_digits: item.last4_digits,\n expiry_month: item.expiry_month,\n issuer_country_code: item.issuer_country_code,\n expiry_year: item.expiry_year,\n nick_name: item.nick_name,\n card_holder_name: item.card_holder_name,\n card_isin: item.card_isin,\n card_issuer: item.card_issuer,\n card_network: item.card_network,\n card_type: item.card_type,\n saved_to_locker: item.saved_to_locker,\n co_badged_card_data: co_badged_card_data\n .map(payment_methods::CoBadgedCardDataToBeSaved::from),\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for CardDetailsPaymentMethod {\n fn from(item: payment_methods::CardDetailsPaymentMethod) -> Self {\n Self {\n issuer_country: item.issuer_country,\n last4_digits: item.last4_digits,\n expiry_month: item.expiry_month,\n expiry_year: item.expiry_year,\n nick_name: item.nick_name,\n card_holder_name: item.card_holder_name,\n card_isin: item.card_isin,\n card_issuer: item.card_issuer,\n card_network: item.card_network,\n card_type: item.card_type,\n saved_to_locker: item.saved_to_locker,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for CardDetailsPaymentMethod {\n fn from(item: payment_methods::CardDetail) -> Self {\n Self {\n issuer_country: item.card_issuing_country.map(|c| c.to_string()),\n last4_digits: Some(item.card_number.get_last4()),\n expiry_month: Some(item.card_exp_month),\n expiry_year: Some(item.card_exp_year),\n card_holder_name: item.card_holder_name,\n nick_name: item.nick_name,\n card_isin: None,\n card_issuer: item.card_issuer,\n card_network: item.card_network,\n card_type: item.card_type.map(|card| card.to_string()),\n saved_to_locker: true,\n }\n }\n}\n\nimpl From for NetworkTokenDetailsPaymentMethod {\n fn from(item: NetworkTokenDetails) -> Self {\n Self {\n issuer_country: item.card_issuing_country,\n last4_digits: Some(item.network_token.get_last4()),\n network_token_expiry_month: Some(item.network_token_exp_month),\n network_token_expiry_year: Some(item.network_token_exp_year),\n card_holder_name: item.card_holder_name,\n nick_name: item.nick_name,\n card_isin: None,\n card_issuer: item.card_issuer,\n card_network: item.card_network,\n card_type: item.card_type.map(|card| card.to_string()),\n saved_to_locker: true,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]\npub struct SingleUsePaymentMethodToken {\n pub token: Secret,\n pub merchant_connector_id: id_type::MerchantConnectorAccountId,\n}\n\n#[cfg(feature = \"v2\")]\nimpl SingleUsePaymentMethodToken {\n pub fn get_single_use_token_from_payment_method_token(\n token: Secret,\n mca_id: id_type::MerchantConnectorAccountId,\n ) -> Self {\n Self {\n token,\n merchant_connector_id: mca_id,\n }\n }\n}\n\nimpl From for payment_methods::NetworkTokenDetailsPaymentMethod {\n fn from(item: NetworkTokenDetailsPaymentMethod) -> Self {\n Self {\n last4_digits: item.last4_digits,\n issuer_country: item.issuer_country,\n network_token_expiry_month: item.network_token_expiry_month,\n network_token_expiry_year: item.network_token_expiry_year,\n nick_name: item.nick_name,\n card_holder_name: item.card_holder_name,\n card_isin: item.card_isin,\n card_issuer: item.card_issuer,\n card_network: item.card_network,\n card_type: item.card_type,\n saved_to_locker: item.saved_to_locker,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]\npub struct SingleUseTokenKey(String);\n\n#[cfg(feature = \"v2\")]\nimpl SingleUseTokenKey {\n pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self {\n let new_token = format!(\"single_use_token_{}\", payment_method_id.get_string_repr());\n Self(new_token)\n }\n\n pub fn get_store_key(&self) -> &str {\n &self.0\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for payment_methods::CardDetail {\n fn from(card_data: Card) -> Self {\n Self {\n card_number: card_data.card_number.clone(),\n card_exp_month: card_data.card_exp_month.clone(),\n card_exp_year: card_data.card_exp_year.clone(),\n card_cvc: None, // DO NOT POPULATE CVC FOR ADDITIONAL PAYMENT METHOD DATA\n card_holder_name: None,\n nick_name: None,\n card_issuing_country: None,\n card_issuing_country_code: None,\n card_network: card_data.card_network.clone(),\n card_issuer: None,\n card_type: None,\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for payment_methods::CardDetail {\n fn from(network_token_data: NetworkTokenData) -> Self {\n Self {\n card_number: network_token_data.token_number.into(),\n card_exp_month: network_token_data.token_exp_month.clone(),\n card_exp_year: network_token_data.token_exp_year.clone(),\n card_cvc: None,\n card_holder_name: None,\n nick_name: None,\n card_issuing_country: None,\n card_issuing_country_code: None,\n card_network: network_token_data.card_network.clone(),\n card_issuer: None,\n card_type: None,\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for AdditionalNetworkTokenInfo {\n fn from(network_token_data: NetworkTokenData) -> Self {\n Self {\n card_issuer: network_token_data.card_issuer.to_owned(),\n card_network: network_token_data.card_network.to_owned(),\n card_type: network_token_data.card_type.to_owned(),\n card_issuing_country: network_token_data.card_issuing_country.to_owned(),\n bank_code: network_token_data.bank_code.to_owned(),\n token_exp_month: Some(network_token_data.token_exp_month.clone()),\n token_exp_year: Some(network_token_data.token_exp_year.clone()),\n card_holder_name: None,\n last4: Some(network_token_data.token_number.get_last4().clone()),\n token_isin: Some(network_token_data.token_number.get_card_isin().clone()),\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for AdditionalNetworkTokenInfo {\n fn from(network_token_data: NetworkTokenData) -> Self {\n Self {\n card_issuer: network_token_data.card_issuer.to_owned(),\n card_network: network_token_data.card_network.to_owned(),\n card_type: network_token_data.card_type.map(|ct| ct.to_string()),\n card_issuing_country: network_token_data\n .card_issuing_country\n .map(|country| country.to_string()),\n bank_code: network_token_data.bank_code.to_owned(),\n token_exp_month: Some(network_token_data.network_token_exp_month.clone()),\n token_exp_year: Some(network_token_data.network_token_exp_year.clone()),\n card_holder_name: network_token_data.card_holder_name.to_owned(),\n last4: Some(network_token_data.network_token.get_last4().clone()),\n token_isin: Some(network_token_data.network_token.get_card_isin().clone()),\n }\n }\n}\n\nimpl From for AdditionalNetworkTokenInfo {\n fn from(network_token_with_ntid: NetworkTokenDetailsForNetworkTransactionId) -> Self {\n Self {\n card_issuer: network_token_with_ntid.card_issuer.to_owned(),\n card_network: network_token_with_ntid.card_network.to_owned(),\n card_type: network_token_with_ntid.card_type.to_owned(),\n card_issuing_country: network_token_with_ntid.card_issuing_country.to_owned(),\n bank_code: network_token_with_ntid.bank_code.to_owned(),\n token_exp_month: Some(network_token_with_ntid.token_exp_month.clone()),\n token_exp_year: Some(network_token_with_ntid.token_exp_year.clone()),\n card_holder_name: network_token_with_ntid.card_holder_name.clone(),\n last4: Some(network_token_with_ntid.network_token.get_last4().clone()),\n token_isin: Some(\n network_token_with_ntid\n .network_token\n .get_card_isin()\n .clone(),\n ),\n }\n }\n}\n\nimpl From for AdditionalNetworkTokenInfo {\n fn from(network_token_with_ntid: DecryptedWalletTokenDetailsForNetworkTransactionId) -> Self {\n Self {\n card_issuer: None,\n card_network: None,\n card_type: None,\n card_issuing_country: None,\n bank_code: None,\n token_exp_month: Some(network_token_with_ntid.token_exp_month.clone()),\n token_exp_year: Some(network_token_with_ntid.token_exp_year.clone()),\n card_holder_name: network_token_with_ntid.card_holder_name.clone(),\n last4: Some(network_token_with_ntid.decrypted_token.get_last4().clone()),\n token_isin: Some(\n network_token_with_ntid\n .decrypted_token\n .get_card_isin()\n .clone(),\n ),\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl\n From<(\n payment_methods::CardDetail,\n Option<&CardToken>,\n Option,\n )> for Card\n{\n fn from(\n value: (\n payment_methods::CardDetail,\n Option<&CardToken>,\n Option,\n ),\n ) -> Self {\n let (\n payment_methods::CardDetail {\n card_number,\n card_exp_month,\n card_exp_year,\n card_holder_name,\n nick_name,\n card_network,\n card_issuer,\n card_issuing_country,\n card_issuing_country_code,\n card_type,\n ..\n },\n card_token_data,\n co_badged_card_data,\n ) = value;\n\n // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked\n let name_on_card = if let Some(name) = card_holder_name.clone() {\n if name.clone().expose().is_empty() {\n card_token_data\n .and_then(|token_data| token_data.card_holder_name.clone())\n .or(Some(name))\n } else {\n card_holder_name\n }\n } else {\n card_token_data.and_then(|token_data| token_data.card_holder_name.clone())\n };\n\n Self {\n card_number,\n card_exp_month,\n card_exp_year,\n card_holder_name: name_on_card,\n card_cvc: card_token_data\n .cloned()\n .unwrap_or_default()\n .card_cvc\n .unwrap_or_default(),\n card_issuer,\n card_network,\n card_type,\n card_issuing_country,\n card_issuing_country_code,\n bank_code: None,\n nick_name,\n co_badged_card_data,\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl\n TryFrom<(\n cards::CardNumber,\n Option<&CardToken>,\n Option,\n CardDetailsPaymentMethod,\n )> for Card\n{\n type Error = error_stack::Report;\n fn try_from(\n value: (\n cards::CardNumber,\n Option<&CardToken>,\n Option,\n CardDetailsPaymentMethod,\n ),\n ) -> Result {\n let (card_number, card_token_data, co_badged_card_data, card_details) = value;\n\n // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked\n let name_on_card = if let Some(name) = card_details.card_holder_name.clone() {\n if name.clone().expose().is_empty() {\n card_token_data\n .and_then(|token_data| token_data.card_holder_name.clone())\n .or(Some(name))\n } else {\n Some(name)\n }\n } else {\n card_token_data.and_then(|token_data| token_data.card_holder_name.clone())\n };\n\n Ok(Self {\n card_number,\n card_exp_month: card_details\n .expiry_month\n .get_required_value(\"expiry_month\")?\n .clone(),\n card_exp_year: card_details\n .expiry_year\n .get_required_value(\"expiry_year\")?\n .clone(),\n card_holder_name: name_on_card,\n card_cvc: card_token_data\n .cloned()\n .unwrap_or_default()\n .card_cvc\n .unwrap_or_default(),\n card_issuer: card_details.card_issuer,\n card_network: card_details.card_network,\n card_type: card_details.card_type,\n card_issuing_country: card_details.issuer_country,\n card_issuing_country_code: card_details.issuer_country_code,\n bank_code: None,\n nick_name: card_details.nick_name,\n co_badged_card_data,\n })\n }\n}\n\nimpl From for RecurringDetails {\n fn from(value: mandates::RecurringDetails) -> Self {\n match value {\n mandates::RecurringDetails::MandateId(mandate_id) => Self::MandateId(mandate_id),\n mandates::RecurringDetails::PaymentMethodId(payment_method_id) => {\n Self::PaymentMethodId(payment_method_id)\n }\n mandates::RecurringDetails::ProcessorPaymentToken(token) => {\n Self::ProcessorPaymentToken(ProcessorPaymentToken {\n processor_payment_token: token.processor_payment_token,\n merchant_connector_id: token.merchant_connector_id,\n })\n }\n mandates::RecurringDetails::NetworkTransactionIdAndCardDetails(\n network_transaction_id_and_card_details,\n ) => Self::NetworkTransactionIdAndCardDetails(Box::new(\n (*network_transaction_id_and_card_details).into(),\n )),\n mandates::RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(\n network_transaction_id_and_network_token_details,\n ) => Self::NetworkTransactionIdAndNetworkTokenDetails(Box::new(\n (*network_transaction_id_and_network_token_details).into(),\n )),\n mandates::RecurringDetails::NetworkTransactionIdAndDecryptedWalletTokenDetails(\n network_transaction_id_and_decrypted_wallet_token_details,\n ) => Self::NetworkTransactionIdAndDecryptedWalletTokenDetails(Box::new(\n *network_transaction_id_and_decrypted_wallet_token_details,\n )),\n mandates::RecurringDetails::CardWithLimitedData(card_with_limited_data) => {\n Self::CardWithLimitedData(Box::new((*card_with_limited_data).into()))\n }\n }\n }\n}\n\nimpl From for NetworkTransactionIdAndCardDetails {\n fn from(value: mandates::NetworkTransactionIdAndCardDetails) -> Self {\n Self {\n card_number: value.card_number,\n card_exp_month: value.card_exp_month,\n card_exp_year: value.card_exp_year,\n network_transaction_id: value.network_transaction_id,\n card_holder_name: value.card_holder_name,\n card_issuer: value.card_issuer,\n card_network: value.card_network,\n card_type: value.card_type,\n card_issuing_country: value.card_issuing_country,\n card_issuing_country_code: value.card_issuing_country_code,\n bank_code: value.bank_code,\n nick_name: value.nick_name,\n }\n }\n}\n\nimpl From\n for NetworkTransactionIdAndNetworkTokenDetails\n{\n fn from(value: mandates::NetworkTransactionIdAndNetworkTokenDetails) -> Self {\n Self {\n network_token: value.network_token,\n token_exp_month: value.token_exp_month,\n token_exp_year: value.token_exp_year,\n network_transaction_id: value.network_transaction_id,\n card_holder_name: value.card_holder_name,\n card_issuer: value.card_issuer,\n card_network: value.card_network,\n card_type: value.card_type,\n card_issuing_country: value.card_issuing_country,\n bank_code: value.bank_code,\n nick_name: value.nick_name,\n eci: value.eci,\n }\n }\n}\n\nimpl From for CardWithLimitedData {\n fn from(card_with_limited_data: mandates::CardWithLimitedData) -> Self {\n Self {\n card_number: card_with_limited_data.card_number,\n card_exp_month: card_with_limited_data.card_exp_month,\n card_exp_year: card_with_limited_data.card_exp_year,\n card_holder_name: card_with_limited_data.card_holder_name,\n eci: card_with_limited_data.eci,\n }\n }\n}\n\nimpl RecurringDetails {\n pub fn get_mandate_reference_id_and_payment_method_data_for_proxy_flow(\n &self,\n ) -> Option<(api_models::payments::MandateReferenceId, PaymentMethodData)> {\n match self.clone() {\n Self::NetworkTransactionIdAndCardDetails(network_transaction_id_and_card_details) => {\n Some(CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(*network_transaction_id_and_card_details))\n }\n Self::NetworkTransactionIdAndNetworkTokenDetails(network_transaction_id_and_network_token_details) => {\n Some(NetworkTokenDetailsForNetworkTransactionId::get_nti_and_network_token_details_for_mit_flow(*network_transaction_id_and_network_token_details))\n }\n Self::CardWithLimitedData(card_with_limited_data) => {\n Some(CardWithLimitedDetails::get_card_details_for_mit_flow(*card_with_limited_data))\n }\n Self::NetworkTransactionIdAndDecryptedWalletTokenDetails(network_transaction_id_and_decrypted_wallet_token_details) => {\n Some(DecryptedWalletTokenDetailsForNetworkTransactionId::get_nti_and_decrypted_wallet_token_details_for_mit_flow(*network_transaction_id_and_decrypted_wallet_token_details))\n }\n Self::PaymentMethodId(_)\n | Self::MandateId(_)\n | Self::ProcessorPaymentToken(_) => None,\n }\n }\n}\n"} {"file_name": "crates__hyperswitch_domain_models__src__payments__payment_intent.rs", "text": "use api_models::customers::CustomerDocumentDetails;\nuse common_types::primitive_wrappers;\n#[cfg(feature = \"v1\")]\nuse common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2;\n#[cfg(feature = \"v2\")]\nuse common_utils::errors::ParsingError;\n#[cfg(feature = \"v2\")]\nuse common_utils::ext_traits::{Encode, ValueExt};\nuse common_utils::{\n consts::PAYMENTS_LIST_MAX_LIMIT_V1,\n crypto::Encryptable,\n encryption::Encryption,\n errors::{CustomResult, ValidationError},\n id_type,\n pii::{self, Email},\n type_name,\n types::{\n keymanager::{self, KeyManagerState, ToEncryptable},\n CreatedBy, MinorUnit,\n },\n};\nuse diesel_models::{\n PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew,\n};\nuse error_stack::ResultExt;\n#[cfg(feature = \"v2\")]\nuse masking::ExposeInterface;\nuse masking::{Deserialize, PeekInterface, Secret};\nuse serde::Serialize;\nuse time::PrimitiveDateTime;\n\n#[cfg(all(feature = \"v1\", feature = \"olap\"))]\nuse super::payment_attempt::PaymentAttempt;\nuse super::PaymentIntent;\n#[cfg(feature = \"v2\")]\nuse crate::address::Address;\n#[cfg(feature = \"v2\")]\nuse crate::routing;\nuse crate::{\n behaviour,\n merchant_key_store::MerchantKeyStore,\n type_encryption::{crypto_operation, CryptoOperation},\n};\n#[cfg(feature = \"v1\")]\nuse crate::{errors, RemoteStorageObject};\n\n#[async_trait::async_trait]\npub trait PaymentIntentInterface {\n type Error;\n async fn update_payment_intent(\n &self,\n this: PaymentIntent,\n payment_intent: PaymentIntentUpdate,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result;\n\n async fn insert_payment_intent(\n &self,\n new: PaymentIntent,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result;\n\n #[cfg(feature = \"v1\")]\n async fn find_payment_intent_by_payment_id_processor_merchant_id(\n &self,\n payment_id: &id_type::PaymentId,\n processor_merchant_id: &id_type::MerchantId,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result;\n #[cfg(feature = \"v2\")]\n async fn find_payment_intent_by_merchant_reference_id_profile_id(\n &self,\n merchant_reference_id: &id_type::PaymentReferenceId,\n profile_id: &id_type::ProfileId,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: &common_enums::MerchantStorageScheme,\n ) -> error_stack::Result;\n\n #[cfg(feature = \"v2\")]\n async fn find_payment_intent_by_id(\n &self,\n id: &id_type::GlobalPaymentId,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result;\n\n #[cfg(all(feature = \"v1\", feature = \"olap\"))]\n async fn filter_payment_intent_by_constraints(\n &self,\n processor_merchant_id: &id_type::MerchantId,\n filters: &PaymentIntentFetchConstraints,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result, Self::Error>;\n\n #[cfg(all(feature = \"v1\", feature = \"olap\"))]\n async fn filter_payment_intents_by_time_range_constraints(\n &self,\n processor_merchant_id: &id_type::MerchantId,\n time_range: &common_utils::types::TimeRange,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result, Self::Error>;\n\n #[cfg(feature = \"olap\")]\n async fn get_intent_status_with_count(\n &self,\n processor_merchant_id: &id_type::MerchantId,\n profile_id_list: Option>,\n constraints: &common_utils::types::TimeRange,\n ) -> error_stack::Result, Self::Error>;\n\n #[cfg(all(feature = \"v1\", feature = \"olap\"))]\n async fn get_filtered_payment_intents_attempt(\n &self,\n processor_merchant_id: &id_type::MerchantId,\n constraints: &PaymentIntentFetchConstraints,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result, Self::Error>;\n\n #[cfg(all(feature = \"v2\", feature = \"olap\"))]\n async fn get_filtered_payment_intents_attempt(\n &self,\n merchant_id: &id_type::MerchantId,\n constraints: &PaymentIntentFetchConstraints,\n merchant_key_store: &MerchantKeyStore,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result<\n Vec<(\n PaymentIntent,\n Option,\n )>,\n Self::Error,\n >;\n\n #[cfg(all(feature = \"v2\", feature = \"olap\"))]\n async fn get_filtered_active_attempt_ids_for_total_count(\n &self,\n merchant_id: &id_type::MerchantId,\n constraints: &PaymentIntentFetchConstraints,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result>, Self::Error>;\n\n #[cfg(all(feature = \"v1\", feature = \"olap\"))]\n async fn get_filtered_active_attempt_ids_for_total_count(\n &self,\n processor_merchant_id: &id_type::MerchantId,\n constraints: &PaymentIntentFetchConstraints,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> error_stack::Result, Self::Error>;\n}\n\n#[derive(Clone, Debug, PartialEq, router_derive::DebugAsDisplay, Serialize, Deserialize)]\npub struct CustomerData {\n pub name: Option>,\n pub email: Option,\n pub phone: Option>,\n pub phone_country_code: Option,\n pub tax_registration_id: Option>,\n pub customer_document_details: Option,\n}\n\nimpl CustomerData {\n pub fn fill_missing_fields(&mut self, other: &Self) {\n self.name = self.name.clone().or_else(|| other.name.clone());\n self.email = self.email.clone().or_else(|| other.email.clone());\n self.phone = self.phone.clone().or_else(|| other.phone.clone());\n self.phone_country_code = self\n .phone_country_code\n .clone()\n .or_else(|| other.phone_country_code.clone());\n self.tax_registration_id = self\n .tax_registration_id\n .clone()\n .or_else(|| other.tax_registration_id.clone());\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Debug, Clone, Serialize)]\npub struct PaymentIntentUpdateFields {\n pub amount: Option,\n pub currency: Option,\n pub shipping_cost: Option,\n pub tax_details: Option,\n pub skip_external_tax_calculation: Option,\n pub skip_surcharge_calculation: Option,\n pub surcharge_amount: Option,\n pub tax_on_surcharge: Option,\n pub routing_algorithm_id: Option,\n pub capture_method: Option,\n pub authentication_type: Option,\n pub billing_address: Option>,\n pub shipping_address: Option>,\n pub customer_present: Option,\n pub description: Option,\n pub return_url: Option,\n pub setup_future_usage: Option,\n pub apply_mit_exemption: Option,\n pub statement_descriptor: Option,\n pub order_details: Option>>,\n pub allowed_payment_method_types: Option>,\n pub metadata: Option,\n pub connector_metadata: Option,\n pub feature_metadata: Option,\n pub payment_link_config: Option,\n pub request_incremental_authorization: Option,\n pub session_expiry: Option,\n pub frm_metadata: Option,\n pub request_external_three_ds_authentication:\n Option,\n pub active_attempt_id: Option>,\n // updated_by is set internally, field not present in request\n pub updated_by: String,\n pub force_3ds_challenge: Option,\n pub is_iframe_redirection_enabled: Option,\n pub enable_partial_authorization: Option,\n pub active_attempt_id_type: Option,\n pub active_attempts_group_id: Option,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Clone, Serialize)]\npub struct PaymentIntentUpdateFields {\n pub amount: MinorUnit,\n pub currency: common_enums::Currency,\n pub setup_future_usage: Option,\n pub status: common_enums::IntentStatus,\n pub customer_id: Option,\n pub shipping_address_id: Option,\n pub billing_address_id: Option,\n pub return_url: Option,\n pub business_country: Option,\n pub business_label: Option,\n pub description: Option,\n pub statement_descriptor_name: Option,\n pub statement_descriptor_suffix: Option,\n pub order_details: Option>,\n pub metadata: Option,\n pub frm_metadata: Option,\n pub payment_confirm_source: Option,\n pub updated_by: String,\n pub fingerprint_id: Option,\n pub session_expiry: Option,\n pub request_external_three_ds_authentication: Option,\n pub customer_details: Option>>,\n pub billing_details: Option>>,\n pub merchant_order_reference_id: Option,\n pub shipping_details: Option>>,\n pub is_payment_processor_token_flow: Option,\n pub tax_details: Option,\n pub force_3ds_challenge: Option,\n pub is_iframe_redirection_enabled: Option,\n pub tax_status: Option,\n pub discount_amount: Option,\n pub order_date: Option,\n pub shipping_amount_tax: Option,\n pub duty_amount: Option,\n pub is_confirm_operation: bool,\n pub payment_channel: Option,\n pub feature_metadata: Option>,\n pub enable_partial_authorization: Option,\n pub enable_overcapture: Option,\n pub shipping_cost: Option,\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Debug, Clone, Serialize)]\npub enum PaymentIntentUpdate {\n ResponseUpdate {\n status: common_enums::IntentStatus,\n amount_captured: Option,\n updated_by: String,\n fingerprint_id: Option,\n incremental_authorization_allowed: Option,\n feature_metadata: Option>,\n },\n MetadataUpdate {\n metadata: Option,\n updated_by: String,\n feature_metadata: Option>,\n },\n Update(Box),\n PaymentCreateUpdate {\n return_url: Option,\n status: Option,\n customer_id: Option,\n shipping_address_id: Option,\n billing_address_id: Option,\n customer_details: Option>>,\n updated_by: String,\n },\n MerchantStatusUpdate {\n status: common_enums::IntentStatus,\n shipping_address_id: Option,\n billing_address_id: Option,\n updated_by: String,\n },\n PGStatusUpdate {\n status: common_enums::IntentStatus,\n incremental_authorization_allowed: Option,\n updated_by: String,\n feature_metadata: Option>,\n },\n PaymentAttemptAndAttemptCountUpdate {\n active_attempt_id: String,\n attempt_count: i16,\n updated_by: String,\n },\n StatusAndAttemptUpdate {\n status: common_enums::IntentStatus,\n active_attempt_id: String,\n attempt_count: i16,\n updated_by: String,\n },\n ApproveUpdate {\n status: common_enums::IntentStatus,\n merchant_decision: Option,\n updated_by: String,\n },\n RejectUpdate {\n status: common_enums::IntentStatus,\n merchant_decision: Option,\n updated_by: String,\n },\n SurchargeApplicableUpdate {\n surcharge_applicable: bool,\n updated_by: String,\n },\n IncrementalAuthorizationAmountUpdate {\n amount: MinorUnit,\n },\n AuthorizationCountUpdate {\n authorization_count: i32,\n },\n CompleteAuthorizeUpdate {\n shipping_address_id: Option,\n },\n ManualUpdate {\n status: Option,\n updated_by: String,\n },\n SessionResponseUpdate {\n tax_details: diesel_models::TaxDetails,\n shipping_address_id: Option,\n updated_by: String,\n shipping_details: Option>>,\n },\n StateMetadataUpdate {\n state_metadata: common_types::payments::PaymentIntentStateMetadata,\n updated_by: String,\n },\n}\n\n#[cfg(feature = \"v1\")]\nimpl PaymentIntentUpdate {\n pub fn is_confirm_operation(&self) -> bool {\n match self {\n Self::Update(value) => value.is_confirm_operation,\n _ => false,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[derive(Debug, Clone, Serialize)]\npub enum PaymentIntentUpdate {\n /// PreUpdate tracker of ConfirmIntent\n ConfirmIntent {\n status: common_enums::IntentStatus,\n active_attempt_id: Option,\n updated_by: String,\n },\n /// PostUpdate tracker of ConfirmIntent\n ConfirmIntentPostUpdate {\n status: common_enums::IntentStatus,\n amount_captured: Option,\n updated_by: String,\n feature_metadata: Option>,\n },\n /// SyncUpdate of ConfirmIntent in PostUpdateTrackers\n SyncUpdate {\n status: common_enums::IntentStatus,\n amount_captured: Option,\n updated_by: String,\n },\n CaptureUpdate {\n status: common_enums::IntentStatus,\n amount_captured: Option,\n updated_by: String,\n },\n /// Update the payment intent details on payment sdk session call, before calling the connector.\n SessionIntentUpdate {\n prerouting_algorithm: routing::PaymentRoutingInfo,\n updated_by: String,\n },\n RecordUpdate {\n status: common_enums::IntentStatus,\n feature_metadata: Box>,\n updated_by: String,\n active_attempt_id: Option,\n active_attempts_group_id: Option,\n },\n /// UpdateIntent\n UpdateIntent(Box),\n /// VoidUpdate for payment cancellation\n VoidUpdate {\n status: common_enums::IntentStatus,\n updated_by: String,\n },\n AttemptGroupUpdate {\n active_attempts_group_id: id_type::GlobalAttemptGroupId,\n active_attempt_id_type: common_enums::ActiveAttemptIDType,\n updated_by: String,\n },\n SplitPaymentStatusUpdate {\n status: common_enums::IntentStatus,\n updated_by: String,\n },\n}\n\n#[cfg(feature = \"v2\")]\nimpl PaymentIntentUpdate {\n pub fn is_confirm_operation(&self) -> bool {\n matches!(self, Self::ConfirmIntent { .. })\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[derive(Clone, Debug, Default)]\npub struct PaymentIntentUpdateInternal {\n pub amount: Option,\n pub currency: Option,\n pub status: Option,\n pub amount_captured: Option,\n pub customer_id: Option,\n pub return_url: Option,\n pub setup_future_usage: Option,\n pub off_session: Option,\n pub metadata: Option,\n pub billing_address_id: Option,\n pub shipping_address_id: Option,\n pub modified_at: Option,\n pub active_attempt_id: Option,\n pub business_country: Option,\n pub business_label: Option,\n pub description: Option,\n pub statement_descriptor_name: Option,\n pub statement_descriptor_suffix: Option,\n pub order_details: Option>,\n pub attempt_count: Option,\n // Denotes the action(approve or reject) taken by merchant in case of manual review.\n // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment\n pub merchant_decision: Option,\n pub payment_confirm_source: Option,\n\n pub updated_by: String,\n pub surcharge_applicable: Option,\n pub incremental_authorization_allowed: Option,\n pub authorization_count: Option,\n pub fingerprint_id: Option,\n pub session_expiry: Option,\n pub request_external_three_ds_authentication: Option,\n pub frm_metadata: Option,\n pub customer_details: Option>>,\n pub billing_details: Option>>,\n pub merchant_order_reference_id: Option,\n pub shipping_details: Option>>,\n pub is_payment_processor_token_flow: Option,\n pub tax_details: Option,\n pub force_3ds_challenge: Option,\n pub is_iframe_redirection_enabled: Option,\n pub payment_channel: Option,\n pub feature_metadata: Option>,\n pub tax_status: Option,\n pub discount_amount: Option,\n pub order_date: Option,\n pub shipping_amount_tax: Option,\n pub duty_amount: Option,\n pub enable_partial_authorization: Option,\n pub enable_overcapture: Option,\n pub shipping_cost: Option,\n pub state_metadata: Option,\n}\n\n// This conversion is used in the `update_payment_intent` function\n#[cfg(feature = \"v2\")]\nimpl TryFrom for diesel_models::PaymentIntentUpdateInternal {\n type Error = error_stack::Report;\n fn try_from(payment_intent_update: PaymentIntentUpdate) -> Result {\n match payment_intent_update {\n PaymentIntentUpdate::ConfirmIntent {\n status,\n active_attempt_id,\n updated_by,\n } => Ok(Self {\n status: Some(status),\n active_attempt_id: Some(active_attempt_id),\n active_attempt_id_type: None,\n active_attempts_group_id: None,\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount: None,\n amount_captured: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: None,\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n\n PaymentIntentUpdate::ConfirmIntentPostUpdate {\n status,\n updated_by,\n amount_captured,\n feature_metadata,\n } => Ok(Self {\n status: Some(status),\n active_attempt_id: None,\n active_attempt_id_type: None,\n active_attempts_group_id: None,\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount_captured,\n amount: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: feature_metadata.map(|val| *val),\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n PaymentIntentUpdate::SyncUpdate {\n status,\n amount_captured,\n updated_by,\n } => Ok(Self {\n status: Some(status),\n active_attempt_id: None,\n active_attempt_id_type: None,\n active_attempts_group_id: None,\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount: None,\n currency: None,\n amount_captured,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: None,\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n PaymentIntentUpdate::CaptureUpdate {\n status,\n amount_captured,\n updated_by,\n } => Ok(Self {\n status: Some(status),\n amount_captured,\n active_attempt_id: None,\n active_attempt_id_type: None,\n active_attempts_group_id: None,\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: None,\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n PaymentIntentUpdate::SessionIntentUpdate {\n prerouting_algorithm,\n updated_by,\n } => Ok(Self {\n status: None,\n active_attempt_id: None,\n active_attempt_id_type: None,\n active_attempts_group_id: None,\n modified_at: common_utils::date_time::now(),\n amount_captured: None,\n prerouting_algorithm: Some(\n prerouting_algorithm\n .encode_to_value()\n .attach_printable(\"Failed to Serialize prerouting_algorithm\")?,\n ),\n amount: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: None,\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n PaymentIntentUpdate::UpdateIntent(boxed_intent) => {\n let PaymentIntentUpdateFields {\n amount,\n currency,\n shipping_cost,\n tax_details,\n skip_external_tax_calculation,\n skip_surcharge_calculation,\n surcharge_amount,\n tax_on_surcharge,\n routing_algorithm_id,\n capture_method,\n authentication_type,\n billing_address,\n shipping_address,\n customer_present,\n description,\n return_url,\n setup_future_usage,\n apply_mit_exemption,\n statement_descriptor,\n order_details,\n allowed_payment_method_types,\n metadata,\n connector_metadata,\n feature_metadata,\n payment_link_config,\n request_incremental_authorization,\n session_expiry,\n frm_metadata,\n request_external_three_ds_authentication,\n active_attempt_id,\n\n updated_by,\n force_3ds_challenge,\n is_iframe_redirection_enabled,\n enable_partial_authorization,\n active_attempt_id_type,\n active_attempts_group_id,\n } = *boxed_intent;\n Ok(Self {\n status: None,\n active_attempt_id,\n active_attempt_id_type,\n active_attempts_group_id,\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount_captured: None,\n amount,\n currency,\n shipping_cost,\n tax_details,\n skip_external_tax_calculation: skip_external_tax_calculation\n .map(|val| val.as_bool()),\n surcharge_applicable: skip_surcharge_calculation.map(|val| val.as_bool()),\n surcharge_amount,\n tax_on_surcharge,\n routing_algorithm_id,\n capture_method,\n authentication_type,\n billing_address: billing_address.map(Encryption::from),\n shipping_address: shipping_address.map(Encryption::from),\n customer_present: customer_present.map(|val| val.as_bool()),\n description,\n return_url,\n setup_future_usage,\n apply_mit_exemption: apply_mit_exemption.map(|val| val.as_bool()),\n statement_descriptor,\n order_details,\n allowed_payment_method_types: allowed_payment_method_types\n .map(|allowed_payment_method_types| {\n allowed_payment_method_types.encode_to_value()\n })\n .and_then(|r| r.ok().map(Secret::new)),\n metadata,\n connector_metadata,\n feature_metadata,\n payment_link_config,\n request_incremental_authorization,\n session_expiry,\n frm_metadata,\n request_external_three_ds_authentication:\n request_external_three_ds_authentication.map(|val| val.as_bool()),\n updated_by,\n force_3ds_challenge,\n is_iframe_redirection_enabled,\n enable_partial_authorization,\n state_metadata: None,\n })\n }\n PaymentIntentUpdate::RecordUpdate {\n status,\n feature_metadata,\n updated_by,\n active_attempt_id,\n active_attempts_group_id,\n } => Ok(Self {\n status: Some(status),\n amount_captured: None,\n active_attempt_id: Some(active_attempt_id),\n active_attempt_id_type: None,\n active_attempts_group_id,\n modified_at: common_utils::date_time::now(),\n amount: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: *feature_metadata,\n payment_link_config: None,\n request_incremental_authorization: None,\n prerouting_algorithm: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n PaymentIntentUpdate::VoidUpdate { status, updated_by } => Ok(Self {\n status: Some(status),\n amount_captured: None,\n active_attempt_id: None,\n active_attempt_id_type: None,\n active_attempts_group_id: None,\n\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: None,\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n PaymentIntentUpdate::AttemptGroupUpdate {\n updated_by,\n active_attempts_group_id,\n active_attempt_id_type,\n } => Ok(Self {\n status: None,\n amount_captured: None,\n active_attempt_id: None,\n active_attempt_id_type: Some(active_attempt_id_type),\n active_attempts_group_id: Some(active_attempts_group_id),\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: None,\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n PaymentIntentUpdate::SplitPaymentStatusUpdate { status, updated_by } => Ok(Self {\n status: Some(status),\n amount_captured: None,\n active_attempt_id: None,\n active_attempt_id_type: None,\n active_attempts_group_id: None,\n prerouting_algorithm: None,\n modified_at: common_utils::date_time::now(),\n amount: None,\n currency: None,\n shipping_cost: None,\n tax_details: None,\n skip_external_tax_calculation: None,\n surcharge_applicable: None,\n surcharge_amount: None,\n tax_on_surcharge: None,\n routing_algorithm_id: None,\n capture_method: None,\n authentication_type: None,\n billing_address: None,\n shipping_address: None,\n customer_present: None,\n description: None,\n return_url: None,\n setup_future_usage: None,\n apply_mit_exemption: None,\n statement_descriptor: None,\n order_details: None,\n allowed_payment_method_types: None,\n metadata: None,\n connector_metadata: None,\n feature_metadata: None,\n payment_link_config: None,\n request_incremental_authorization: None,\n session_expiry: None,\n frm_metadata: None,\n request_external_three_ds_authentication: None,\n updated_by,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n enable_partial_authorization: None,\n state_metadata: None,\n }),\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for PaymentIntentUpdateInternal {\n fn from(payment_intent_update: PaymentIntentUpdate) -> Self {\n match payment_intent_update {\n PaymentIntentUpdate::MetadataUpdate {\n metadata,\n updated_by,\n feature_metadata,\n } => Self {\n metadata,\n modified_at: Some(common_utils::date_time::now()),\n updated_by,\n feature_metadata,\n ..Default::default()\n },\n PaymentIntentUpdate::Update(value) => Self {\n amount: Some(value.amount),\n currency: Some(value.currency),\n setup_future_usage: value.setup_future_usage,\n status: Some(value.status),\n customer_id: value.customer_id,\n shipping_address_id: value.shipping_address_id,\n billing_address_id: value.billing_address_id,\n return_url: value.return_url,\n business_country: value.business_country,\n business_label: value.business_label,\n description: value.description,\n statement_descriptor_name: value.statement_descriptor_name,\n statement_descriptor_suffix: value.statement_descriptor_suffix,\n order_details: value.order_details,\n metadata: value.metadata,\n payment_confirm_source: value.payment_confirm_source,\n updated_by: value.updated_by,\n session_expiry: value.session_expiry,\n fingerprint_id: value.fingerprint_id,\n request_external_three_ds_authentication: value\n .request_external_three_ds_authentication,\n frm_metadata: value.frm_metadata,\n customer_details: value.customer_details,\n billing_details: value.billing_details,\n merchant_order_reference_id: value.merchant_order_reference_id,\n shipping_details: value.shipping_details,\n is_payment_processor_token_flow: value.is_payment_processor_token_flow,\n tax_details: value.tax_details,\n tax_status: value.tax_status,\n discount_amount: value.discount_amount,\n order_date: value.order_date,\n shipping_amount_tax: value.shipping_amount_tax,\n duty_amount: value.duty_amount,\n ..Default::default()\n },\n PaymentIntentUpdate::PaymentCreateUpdate {\n return_url,\n status,\n customer_id,\n shipping_address_id,\n billing_address_id,\n customer_details,\n updated_by,\n } => Self {\n return_url,\n status,\n customer_id,\n shipping_address_id,\n billing_address_id,\n customer_details,\n modified_at: Some(common_utils::date_time::now()),\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::PGStatusUpdate {\n status,\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n } => Self {\n status: Some(status),\n modified_at: Some(common_utils::date_time::now()),\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n ..Default::default()\n },\n PaymentIntentUpdate::MerchantStatusUpdate {\n status,\n shipping_address_id,\n billing_address_id,\n updated_by,\n } => Self {\n status: Some(status),\n shipping_address_id,\n billing_address_id,\n modified_at: Some(common_utils::date_time::now()),\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::ResponseUpdate {\n // amount,\n // currency,\n status,\n amount_captured,\n fingerprint_id,\n // customer_id,\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n } => Self {\n // amount,\n // currency: Some(currency),\n status: Some(status),\n amount_captured,\n fingerprint_id,\n // customer_id,\n modified_at: Some(common_utils::date_time::now()),\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n ..Default::default()\n },\n PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {\n active_attempt_id,\n attempt_count,\n updated_by,\n } => Self {\n active_attempt_id: Some(active_attempt_id),\n attempt_count: Some(attempt_count),\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::StatusAndAttemptUpdate {\n status,\n active_attempt_id,\n attempt_count,\n updated_by,\n } => Self {\n status: Some(status),\n active_attempt_id: Some(active_attempt_id),\n attempt_count: Some(attempt_count),\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::ApproveUpdate {\n status,\n merchant_decision,\n updated_by,\n } => Self {\n status: Some(status),\n merchant_decision,\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::RejectUpdate {\n status,\n merchant_decision,\n updated_by,\n } => Self {\n status: Some(status),\n merchant_decision,\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::SurchargeApplicableUpdate {\n surcharge_applicable,\n updated_by,\n } => Self {\n surcharge_applicable: Some(surcharge_applicable),\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self {\n amount: Some(amount),\n ..Default::default()\n },\n PaymentIntentUpdate::AuthorizationCountUpdate {\n authorization_count,\n } => Self {\n authorization_count: Some(authorization_count),\n ..Default::default()\n },\n PaymentIntentUpdate::CompleteAuthorizeUpdate {\n shipping_address_id,\n } => Self {\n shipping_address_id,\n ..Default::default()\n },\n PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self {\n status,\n modified_at: Some(common_utils::date_time::now()),\n updated_by,\n ..Default::default()\n },\n PaymentIntentUpdate::SessionResponseUpdate {\n tax_details,\n shipping_address_id,\n updated_by,\n shipping_details,\n } => Self {\n tax_details: Some(tax_details),\n shipping_address_id,\n updated_by,\n shipping_details,\n ..Default::default()\n },\n PaymentIntentUpdate::StateMetadataUpdate {\n state_metadata,\n updated_by,\n } => Self {\n state_metadata: Some(state_metadata),\n updated_by,\n amount: None,\n currency: None,\n status: None,\n amount_captured: None,\n customer_id: None,\n return_url: None,\n setup_future_usage: None,\n off_session: None,\n metadata: None,\n billing_address_id: None,\n shipping_address_id: None,\n modified_at: None,\n active_attempt_id: None,\n business_country: None,\n business_label: None,\n description: None,\n statement_descriptor_name: None,\n statement_descriptor_suffix: None,\n order_details: None,\n attempt_count: None,\n merchant_decision: None,\n payment_confirm_source: None,\n surcharge_applicable: None,\n incremental_authorization_allowed: None,\n authorization_count: None,\n fingerprint_id: None,\n session_expiry: None,\n request_external_three_ds_authentication: None,\n frm_metadata: None,\n customer_details: None,\n billing_details: None,\n merchant_order_reference_id: None,\n shipping_details: None,\n is_payment_processor_token_flow: None,\n tax_details: None,\n force_3ds_challenge: None,\n is_iframe_redirection_enabled: None,\n payment_channel: None,\n feature_metadata: None,\n tax_status: None,\n discount_amount: None,\n order_date: None,\n shipping_amount_tax: None,\n duty_amount: None,\n enable_partial_authorization: None,\n enable_overcapture: None,\n shipping_cost: None,\n },\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nuse diesel_models::{\n PaymentIntentUpdate as DieselPaymentIntentUpdate,\n PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields,\n};\n\n// TODO: check where this conversion is used\n// #[cfg(feature = \"v2\")]\n// impl From for DieselPaymentIntentUpdate {\n// fn from(value: PaymentIntentUpdate) -> Self {\n// match value {\n// PaymentIntentUpdate::ConfirmIntent { status, updated_by } => {\n// Self::ConfirmIntent { status, updated_by }\n// }\n// PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => {\n// Self::ConfirmIntentPostUpdate { status, updated_by }\n// }\n// }\n// }\n// }\n\n#[cfg(feature = \"v1\")]\nimpl From for DieselPaymentIntentUpdate {\n fn from(value: PaymentIntentUpdate) -> Self {\n match value {\n PaymentIntentUpdate::ResponseUpdate {\n status,\n amount_captured,\n fingerprint_id,\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n } => Self::ResponseUpdate {\n status,\n amount_captured,\n fingerprint_id,\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n },\n PaymentIntentUpdate::MetadataUpdate {\n metadata,\n updated_by,\n feature_metadata,\n } => Self::MetadataUpdate {\n metadata,\n updated_by,\n feature_metadata,\n },\n PaymentIntentUpdate::StateMetadataUpdate {\n state_metadata,\n updated_by,\n } => Self::StateMetadataUpdate {\n state_metadata,\n updated_by,\n },\n PaymentIntentUpdate::Update(value) => {\n Self::Update(Box::new(DieselPaymentIntentUpdateFields {\n amount: value.amount,\n currency: value.currency,\n setup_future_usage: value.setup_future_usage,\n status: value.status,\n customer_id: value.customer_id,\n shipping_address_id: value.shipping_address_id,\n billing_address_id: value.billing_address_id,\n return_url: value.return_url,\n business_country: value.business_country,\n business_label: value.business_label,\n description: value.description,\n statement_descriptor_name: value.statement_descriptor_name,\n statement_descriptor_suffix: value.statement_descriptor_suffix,\n order_details: value.order_details,\n metadata: value.metadata,\n payment_confirm_source: value.payment_confirm_source,\n updated_by: value.updated_by,\n session_expiry: value.session_expiry,\n fingerprint_id: value.fingerprint_id,\n request_external_three_ds_authentication: value\n .request_external_three_ds_authentication,\n frm_metadata: value.frm_metadata,\n customer_details: value.customer_details.map(Encryption::from),\n billing_details: value.billing_details.map(Encryption::from),\n merchant_order_reference_id: value.merchant_order_reference_id,\n shipping_details: value.shipping_details.map(Encryption::from),\n is_payment_processor_token_flow: value.is_payment_processor_token_flow,\n tax_details: value.tax_details,\n force_3ds_challenge: value.force_3ds_challenge,\n is_iframe_redirection_enabled: value.is_iframe_redirection_enabled,\n payment_channel: value.payment_channel,\n feature_metadata: value.feature_metadata,\n tax_status: value.tax_status,\n discount_amount: value.discount_amount,\n order_date: value.order_date,\n shipping_amount_tax: value.shipping_amount_tax,\n duty_amount: value.duty_amount,\n enable_partial_authorization: value.enable_partial_authorization,\n enable_overcapture: value.enable_overcapture,\n shipping_cost: value.shipping_cost,\n }))\n }\n PaymentIntentUpdate::PaymentCreateUpdate {\n return_url,\n status,\n customer_id,\n shipping_address_id,\n billing_address_id,\n customer_details,\n updated_by,\n } => Self::PaymentCreateUpdate {\n return_url,\n status,\n customer_id,\n shipping_address_id,\n billing_address_id,\n customer_details: customer_details.map(Encryption::from),\n updated_by,\n },\n PaymentIntentUpdate::MerchantStatusUpdate {\n status,\n shipping_address_id,\n billing_address_id,\n updated_by,\n } => Self::MerchantStatusUpdate {\n status,\n shipping_address_id,\n billing_address_id,\n updated_by,\n },\n PaymentIntentUpdate::PGStatusUpdate {\n status,\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n } => Self::PGStatusUpdate {\n status,\n updated_by,\n incremental_authorization_allowed,\n feature_metadata,\n },\n PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {\n active_attempt_id,\n attempt_count,\n updated_by,\n } => Self::PaymentAttemptAndAttemptCountUpdate {\n active_attempt_id,\n attempt_count,\n updated_by,\n },\n PaymentIntentUpdate::StatusAndAttemptUpdate {\n status,\n active_attempt_id,\n attempt_count,\n updated_by,\n } => Self::StatusAndAttemptUpdate {\n status,\n active_attempt_id,\n attempt_count,\n updated_by,\n },\n PaymentIntentUpdate::ApproveUpdate {\n status,\n merchant_decision,\n updated_by,\n } => Self::ApproveUpdate {\n status,\n merchant_decision,\n updated_by,\n },\n PaymentIntentUpdate::RejectUpdate {\n status,\n merchant_decision,\n updated_by,\n } => Self::RejectUpdate {\n status,\n merchant_decision,\n updated_by,\n },\n PaymentIntentUpdate::SurchargeApplicableUpdate {\n surcharge_applicable,\n updated_by,\n } => Self::SurchargeApplicableUpdate {\n surcharge_applicable: Some(surcharge_applicable),\n updated_by,\n },\n PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => {\n Self::IncrementalAuthorizationAmountUpdate { amount }\n }\n PaymentIntentUpdate::AuthorizationCountUpdate {\n authorization_count,\n } => Self::AuthorizationCountUpdate {\n authorization_count,\n },\n PaymentIntentUpdate::CompleteAuthorizeUpdate {\n shipping_address_id,\n } => Self::CompleteAuthorizeUpdate {\n shipping_address_id,\n },\n PaymentIntentUpdate::ManualUpdate { status, updated_by } => {\n Self::ManualUpdate { status, updated_by }\n }\n PaymentIntentUpdate::SessionResponseUpdate {\n tax_details,\n shipping_address_id,\n updated_by,\n shipping_details,\n } => Self::SessionResponseUpdate {\n tax_details,\n shipping_address_id,\n updated_by,\n shipping_details: shipping_details.map(Encryption::from),\n },\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for diesel_models::PaymentIntentUpdateInternal {\n fn from(value: PaymentIntentUpdateInternal) -> Self {\n let modified_at = common_utils::date_time::now();\n let PaymentIntentUpdateInternal {\n amount,\n currency,\n status,\n amount_captured,\n customer_id,\n return_url,\n setup_future_usage,\n off_session,\n metadata,\n billing_address_id,\n shipping_address_id,\n modified_at: _,\n active_attempt_id,\n business_country,\n business_label,\n description,\n statement_descriptor_name,\n statement_descriptor_suffix,\n order_details,\n attempt_count,\n merchant_decision,\n payment_confirm_source,\n updated_by,\n surcharge_applicable,\n incremental_authorization_allowed,\n authorization_count,\n session_expiry,\n fingerprint_id,\n request_external_three_ds_authentication,\n frm_metadata,\n customer_details,\n billing_details,\n merchant_order_reference_id,\n shipping_details,\n is_payment_processor_token_flow,\n tax_details,\n force_3ds_challenge,\n is_iframe_redirection_enabled,\n payment_channel,\n feature_metadata,\n tax_status,\n discount_amount,\n order_date,\n shipping_amount_tax,\n duty_amount,\n enable_partial_authorization,\n enable_overcapture,\n shipping_cost,\n state_metadata,\n } = value;\n Self {\n amount,\n currency,\n status,\n amount_captured,\n customer_id,\n return_url: None, // deprecated\n setup_future_usage,\n off_session,\n metadata,\n billing_address_id,\n shipping_address_id,\n modified_at,\n active_attempt_id,\n business_country,\n business_label,\n description,\n statement_descriptor_name,\n statement_descriptor_suffix,\n order_details,\n attempt_count,\n merchant_decision,\n payment_confirm_source,\n updated_by,\n surcharge_applicable,\n incremental_authorization_allowed,\n authorization_count,\n session_expiry,\n fingerprint_id,\n request_external_three_ds_authentication,\n frm_metadata,\n customer_details: customer_details.map(Encryption::from),\n billing_details: billing_details.map(Encryption::from),\n merchant_order_reference_id,\n shipping_details: shipping_details.map(Encryption::from),\n is_payment_processor_token_flow,\n tax_details,\n force_3ds_challenge,\n is_iframe_redirection_enabled,\n extended_return_url: return_url,\n payment_channel,\n feature_metadata,\n tax_status,\n discount_amount,\n order_date,\n shipping_amount_tax,\n duty_amount,\n enable_partial_authorization,\n enable_overcapture,\n shipping_cost,\n state_metadata,\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\npub enum PaymentIntentFetchConstraints {\n Single {\n payment_intent_id: id_type::PaymentId,\n },\n List(Box),\n}\n\n#[cfg(feature = \"v1\")]\nimpl PaymentIntentFetchConstraints {\n pub fn get_profile_id_list(&self) -> Option> {\n if let Self::List(pi_list_params) = self {\n pi_list_params.profile_id.clone()\n } else {\n None\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\npub enum PaymentIntentFetchConstraints {\n List(Box),\n}\n\n#[cfg(feature = \"v2\")]\nimpl PaymentIntentFetchConstraints {\n pub fn get_profile_id(&self) -> Option {\n let Self::List(pi_list_params) = self;\n pi_list_params.profile_id.clone()\n }\n}\n\n#[cfg(feature = \"v1\")]\npub struct PaymentIntentListParams {\n pub offset: u32,\n pub starting_at: Option,\n pub ending_at: Option,\n pub amount_filter: Option,\n pub connector: Option>,\n pub currency: Option>,\n pub status: Option>,\n pub payment_method: Option>,\n pub payment_method_type: Option>,\n pub authentication_type: Option>,\n pub merchant_connector_id: Option>,\n pub profile_id: Option>,\n pub customer_id: Option,\n pub starting_after_id: Option,\n pub ending_before_id: Option,\n pub limit: Option,\n pub order: api_models::payments::Order,\n pub card_network: Option>,\n pub card_discovery: Option>,\n pub merchant_order_reference_id: Option,\n}\n\n#[cfg(feature = \"v2\")]\npub struct PaymentIntentListParams {\n pub offset: u32,\n pub starting_at: Option,\n pub ending_at: Option,\n pub amount_filter: Option,\n pub connector: Option>,\n pub currency: Option>,\n pub status: Option>,\n pub payment_method_type: Option>,\n pub payment_method_subtype: Option>,\n pub authentication_type: Option>,\n pub merchant_connector_id: Option>,\n pub profile_id: Option,\n pub customer_id: Option,\n pub starting_after_id: Option,\n pub ending_before_id: Option,\n pub limit: Option,\n pub order: api_models::payments::Order,\n pub card_network: Option>,\n pub merchant_order_reference_id: Option,\n pub payment_id: Option,\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for PaymentIntentFetchConstraints {\n fn from(value: api_models::payments::PaymentListConstraints) -> Self {\n let api_models::payments::PaymentListConstraints {\n customer_id,\n starting_after,\n ending_before,\n limit,\n created,\n created_lt,\n created_gt,\n created_lte,\n created_gte,\n } = value;\n Self::List(Box::new(PaymentIntentListParams {\n offset: 0,\n starting_at: created_gte.or(created_gt).or(created),\n ending_at: created_lte.or(created_lt).or(created),\n amount_filter: None,\n connector: None,\n currency: None,\n status: None,\n payment_method: None,\n payment_method_type: None,\n authentication_type: None,\n merchant_connector_id: None,\n profile_id: None,\n customer_id,\n starting_after_id: starting_after,\n ending_before_id: ending_before,\n limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),\n order: Default::default(),\n card_network: None,\n card_discovery: None,\n merchant_order_reference_id: None,\n }))\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl From for PaymentIntentFetchConstraints {\n fn from(value: api_models::payments::PaymentListConstraints) -> Self {\n let api_models::payments::PaymentListConstraints {\n customer_id,\n starting_after,\n ending_before,\n limit,\n created,\n created_lt,\n created_gt,\n created_lte,\n created_gte,\n payment_id,\n profile_id,\n start_amount,\n end_amount,\n connector,\n currency,\n status,\n payment_method_type,\n payment_method_subtype,\n authentication_type,\n merchant_connector_id,\n order_on,\n order_by,\n card_network,\n merchant_order_reference_id,\n offset,\n } = value;\n Self::List(Box::new(PaymentIntentListParams {\n offset: offset.unwrap_or_default(),\n starting_at: created_gte.or(created_gt).or(created),\n ending_at: created_lte.or(created_lt).or(created),\n amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some({\n api_models::payments::AmountFilter {\n start_amount,\n end_amount,\n }\n }),\n connector,\n currency,\n status,\n payment_method_type,\n payment_method_subtype,\n authentication_type,\n merchant_connector_id,\n profile_id,\n customer_id,\n starting_after_id: starting_after,\n ending_before_id: ending_before,\n limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),\n order: api_models::payments::Order {\n on: order_on,\n by: order_by,\n },\n card_network,\n merchant_order_reference_id,\n payment_id,\n }))\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for PaymentIntentFetchConstraints {\n fn from(value: common_utils::types::TimeRange) -> Self {\n Self::List(Box::new(PaymentIntentListParams {\n offset: 0,\n starting_at: Some(value.start_time),\n ending_at: value.end_time,\n amount_filter: None,\n connector: None,\n currency: None,\n status: None,\n payment_method: None,\n payment_method_type: None,\n authentication_type: None,\n merchant_connector_id: None,\n profile_id: None,\n customer_id: None,\n starting_after_id: None,\n ending_before_id: None,\n limit: None,\n order: Default::default(),\n card_network: None,\n card_discovery: None,\n merchant_order_reference_id: None,\n }))\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl From for PaymentIntentFetchConstraints {\n fn from(value: api_models::payments::PaymentListFilterConstraints) -> Self {\n let api_models::payments::PaymentListFilterConstraints {\n payment_id,\n profile_id,\n customer_id,\n limit,\n offset,\n amount_filter,\n time_range,\n connector,\n currency,\n status,\n payment_method,\n payment_method_type,\n authentication_type,\n merchant_connector_id,\n order,\n card_network,\n card_discovery,\n merchant_order_reference_id,\n } = value;\n if let Some(payment_intent_id) = payment_id {\n Self::Single { payment_intent_id }\n } else {\n Self::List(Box::new(PaymentIntentListParams {\n offset: offset.unwrap_or_default(),\n starting_at: time_range.map(|t| t.start_time),\n ending_at: time_range.and_then(|t| t.end_time),\n amount_filter,\n connector,\n currency,\n status,\n payment_method,\n payment_method_type,\n authentication_type,\n merchant_connector_id,\n profile_id: profile_id.map(|profile_id| vec![profile_id]),\n customer_id,\n starting_after_id: None,\n ending_before_id: None,\n limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)),\n order,\n card_network,\n card_discovery,\n merchant_order_reference_id,\n }))\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\nimpl TryFrom<(T, Option>)> for PaymentIntentFetchConstraints\nwhere\n Self: From,\n{\n type Error = error_stack::Report;\n fn try_from(\n (constraints, auth_profile_id_list): (T, Option>),\n ) -> Result {\n let payment_intent_constraints = Self::from(constraints);\n if let Self::List(mut pi_list_params) = payment_intent_constraints {\n let profile_id_from_request_body = pi_list_params.profile_id;\n match (profile_id_from_request_body, auth_profile_id_list) {\n (None, None) => pi_list_params.profile_id = None,\n (None, Some(auth_profile_id_list)) => {\n pi_list_params.profile_id = Some(auth_profile_id_list)\n }\n (Some(profile_id_from_request_body), None) => {\n pi_list_params.profile_id = Some(profile_id_from_request_body)\n }\n (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {\n let profile_id_from_request_body_is_available_in_auth_profile_id_list =\n profile_id_from_request_body\n .iter()\n .all(|profile_id| auth_profile_id_list.contains(profile_id));\n\n if profile_id_from_request_body_is_available_in_auth_profile_id_list {\n pi_list_params.profile_id = Some(profile_id_from_request_body)\n } else {\n // This scenario is very unlikely to happen\n let inaccessible_profile_ids: Vec<_> = profile_id_from_request_body\n .iter()\n .filter(|profile_id| !auth_profile_id_list.contains(profile_id))\n .collect();\n return Err(error_stack::Report::new(\n errors::api_error_response::ApiErrorResponse::PreconditionFailed {\n message: format!(\n \"Access not available for the given profile_id {inaccessible_profile_ids:?}\",\n\n ),\n },\n ));\n }\n }\n }\n Ok(Self::List(pi_list_params))\n } else {\n Ok(payment_intent_constraints)\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\n#[async_trait::async_trait]\nimpl behaviour::Conversion for PaymentIntent {\n type DstType = DieselPaymentIntent;\n type NewDstType = DieselPaymentIntentNew;\n\n async fn convert(self) -> CustomResult {\n let Self {\n merchant_id,\n amount_details,\n status,\n amount_captured,\n customer_id,\n description,\n return_url,\n metadata,\n statement_descriptor,\n created_at,\n modified_at,\n last_synced,\n setup_future_usage,\n active_attempt_id,\n active_attempt_id_type,\n active_attempts_group_id,\n order_details,\n allowed_payment_method_types,\n connector_metadata,\n feature_metadata,\n attempt_count,\n profile_id,\n payment_link_id,\n frm_merchant_decision,\n updated_by,\n request_incremental_authorization,\n split_txns_enabled,\n authorization_count,\n session_expiry,\n request_external_three_ds_authentication,\n frm_metadata,\n customer_details,\n merchant_reference_id,\n billing_address,\n shipping_address,\n capture_method,\n id,\n authentication_type,\n prerouting_algorithm,\n organization_id,\n enable_payment_link,\n apply_mit_exemption,\n customer_present,\n routing_algorithm_id,\n payment_link_config,\n split_payments,\n force_3ds_challenge,\n force_3ds_challenge_trigger,\n processor_merchant_id,\n created_by,\n is_iframe_redirection_enabled,\n is_payment_id_from_merchant,\n enable_partial_authorization,\n } = self;\n Ok(DieselPaymentIntent {\n skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()),\n surcharge_applicable: Some(amount_details.get_surcharge_action_as_bool()),\n merchant_id,\n status,\n amount: amount_details.order_amount,\n currency: amount_details.currency,\n amount_captured,\n customer_id,\n description,\n return_url,\n metadata,\n statement_descriptor,\n created_at,\n modified_at,\n last_synced,\n setup_future_usage: Some(setup_future_usage),\n active_attempt_id,\n active_attempt_id_type: Some(active_attempt_id_type),\n active_attempts_group_id,\n order_details: order_details.map(|order_details| {\n order_details\n .into_iter()\n .map(|order_detail| Secret::new(order_detail.expose()))\n .collect::>()\n }),\n allowed_payment_method_types: allowed_payment_method_types\n .map(|allowed_payment_method_types| {\n allowed_payment_method_types\n .encode_to_value()\n .change_context(ValidationError::InvalidValue {\n message: \"Failed to serialize allowed_payment_method_types\".to_string(),\n })\n })\n .transpose()?\n .map(Secret::new),\n connector_metadata: connector_metadata\n .map(|cm| {\n cm.encode_to_value()\n .change_context(ValidationError::InvalidValue {\n message: \"Failed to serialize connector_metadata\".to_string(),\n })\n })\n .transpose()?\n .map(Secret::new),\n feature_metadata,\n attempt_count,\n profile_id,\n frm_merchant_decision,\n payment_link_id,\n updated_by,\n\n request_incremental_authorization: Some(request_incremental_authorization),\n split_txns_enabled: Some(split_txns_enabled),\n authorization_count,\n session_expiry,\n request_external_three_ds_authentication: Some(\n request_external_three_ds_authentication.as_bool(),\n ),\n frm_metadata,\n customer_details: customer_details.map(Encryption::from),\n billing_address: billing_address.map(Encryption::from),\n shipping_address: shipping_address.map(Encryption::from),\n capture_method: Some(capture_method),\n id,\n authentication_type,\n prerouting_algorithm: prerouting_algorithm\n .map(|prerouting_algorithm| {\n prerouting_algorithm.encode_to_value().change_context(\n ValidationError::InvalidValue {\n message: \"Failed to serialize prerouting_algorithm\".to_string(),\n },\n )\n })\n .transpose()?,\n merchant_reference_id,\n surcharge_amount: amount_details.surcharge_amount,\n tax_on_surcharge: amount_details.tax_on_surcharge,\n organization_id,\n shipping_cost: amount_details.shipping_cost,\n tax_details: amount_details.tax_details,\n enable_payment_link: Some(enable_payment_link.as_bool()),\n apply_mit_exemption: Some(apply_mit_exemption.as_bool()),\n customer_present: Some(customer_present.as_bool()),\n payment_link_config,\n routing_algorithm_id,\n psd2_sca_exemption_type: None,\n request_extended_authorization: None,\n platform_merchant_id: None,\n split_payments,\n force_3ds_challenge,\n force_3ds_challenge_trigger,\n processor_merchant_id: Some(processor_merchant_id),\n created_by: created_by.map(|created_by| created_by.to_string()),\n is_iframe_redirection_enabled,\n is_payment_id_from_merchant,\n payment_channel: None,\n tax_status: None,\n discount_amount: None,\n shipping_amount_tax: None,\n duty_amount: None,\n order_date: None,\n enable_partial_authorization: Some(enable_partial_authorization),\n enable_overcapture: None,\n mit_category: None,\n billing_descriptor: None,\n tokenization: None,\n partner_merchant_identifier_details: None,\n state_metadata: None,\n })\n }\n async fn convert_back(\n state: &KeyManagerState,\n storage_model: Self::DstType,\n key: &Secret>,\n key_manager_identifier: keymanager::Identifier,\n ) -> CustomResult\n where\n Self: Sized,\n {\n async {\n let decrypted_data = crypto_operation(\n state,\n type_name!(Self::DstType),\n CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable(\n super::EncryptedPaymentIntent {\n billing_address: storage_model.billing_address,\n shipping_address: storage_model.shipping_address,\n customer_details: storage_model.customer_details,\n },\n )),\n key_manager_identifier,\n key.peek(),\n )\n .await\n .and_then(|val| val.try_into_batchoperation())?;\n\n let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data)\n .change_context(common_utils::errors::CryptoError::DecodingFailed)\n .attach_printable(\"Invalid batch operation data\")?;\n\n let amount_details = super::AmountDetails {\n order_amount: storage_model.amount,\n currency: storage_model.currency,\n surcharge_amount: storage_model.surcharge_amount,\n tax_on_surcharge: storage_model.tax_on_surcharge,\n shipping_cost: storage_model.shipping_cost,\n tax_details: storage_model.tax_details,\n skip_external_tax_calculation: common_enums::TaxCalculationOverride::from(\n storage_model.skip_external_tax_calculation,\n ),\n skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::from(\n storage_model.surcharge_applicable,\n ),\n amount_captured: storage_model.amount_captured,\n };\n\n let billing_address = data\n .billing_address\n .map(|billing| {\n billing.deserialize_inner_value(|value| value.parse_value(\"Address\"))\n })\n .transpose()\n .change_context(common_utils::errors::CryptoError::DecodingFailed)\n .attach_printable(\"Error while deserializing Address\")?;\n\n let shipping_address = data\n .shipping_address\n .map(|shipping| {\n shipping.deserialize_inner_value(|value| value.parse_value(\"Address\"))\n })\n .transpose()\n .change_context(common_utils::errors::CryptoError::DecodingFailed)\n .attach_printable(\"Error while deserializing Address\")?;\n let allowed_payment_method_types = storage_model\n .allowed_payment_method_types\n .map(|allowed_payment_method_types| {\n allowed_payment_method_types.parse_value(\"Vec\")\n })\n .transpose()\n .change_context(common_utils::errors::CryptoError::DecodingFailed)?;\n Ok::>(Self {\n merchant_id: storage_model.merchant_id.clone(),\n status: storage_model.status,\n amount_details,\n amount_captured: storage_model.amount_captured,\n customer_id: storage_model.customer_id,\n description: storage_model.description,\n return_url: storage_model.return_url,\n metadata: storage_model.metadata,\n statement_descriptor: storage_model.statement_descriptor,\n created_at: storage_model.created_at,\n modified_at: storage_model.modified_at,\n last_synced: storage_model.last_synced,\n setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(),\n active_attempt_id: storage_model.active_attempt_id,\n active_attempt_id_type: storage_model.active_attempt_id_type.unwrap_or_default(),\n active_attempts_group_id: storage_model.active_attempts_group_id,\n order_details: storage_model.order_details.map(|order_details| {\n order_details\n .into_iter()\n .map(|order_detail| Secret::new(order_detail.expose()))\n .collect::>()\n }),\n allowed_payment_method_types,\n connector_metadata: storage_model\n .connector_metadata\n .map(|cm| cm.parse_value(\"ConnectorMetadata\"))\n .transpose()\n .change_context(common_utils::errors::CryptoError::DecodingFailed)\n .attach_printable(\"Failed to deserialize connector_metadata\")?,\n feature_metadata: storage_model.feature_metadata,\n attempt_count: storage_model.attempt_count,\n profile_id: storage_model.profile_id,\n frm_merchant_decision: storage_model.frm_merchant_decision,\n payment_link_id: storage_model.payment_link_id,\n updated_by: storage_model.updated_by,\n request_incremental_authorization: storage_model\n .request_incremental_authorization\n .unwrap_or_default(),\n split_txns_enabled: storage_model.split_txns_enabled.unwrap_or_default(),\n authorization_count: storage_model.authorization_count,\n session_expiry: storage_model.session_expiry,\n request_external_three_ds_authentication: storage_model\n .request_external_three_ds_authentication\n .into(),\n frm_metadata: storage_model.frm_metadata,\n customer_details: data.customer_details,\n billing_address,\n shipping_address,\n capture_method: storage_model.capture_method.unwrap_or_default(),\n id: storage_model.id,\n merchant_reference_id: storage_model.merchant_reference_id,\n organization_id: storage_model.organization_id,\n authentication_type: storage_model.authentication_type,\n prerouting_algorithm: storage_model\n .prerouting_algorithm\n .map(|prerouting_algorithm_value| {\n prerouting_algorithm_value\n .parse_value(\"PaymentRoutingInfo\")\n .change_context(common_utils::errors::CryptoError::DecodingFailed)\n })\n .transpose()?,\n enable_payment_link: storage_model.enable_payment_link.into(),\n apply_mit_exemption: storage_model.apply_mit_exemption.into(),\n customer_present: storage_model.customer_present.into(),\n payment_link_config: storage_model.payment_link_config,\n routing_algorithm_id: storage_model.routing_algorithm_id,\n split_payments: storage_model.split_payments,\n force_3ds_challenge: storage_model.force_3ds_challenge,\n force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger,\n processor_merchant_id: storage_model\n .processor_merchant_id\n .unwrap_or(storage_model.merchant_id),\n created_by: storage_model\n .created_by\n .and_then(|created_by| created_by.parse::().ok()),\n is_iframe_redirection_enabled: storage_model.is_iframe_redirection_enabled,\n is_payment_id_from_merchant: storage_model.is_payment_id_from_merchant,\n enable_partial_authorization: storage_model\n .enable_partial_authorization\n .unwrap_or(false.into()),\n })\n }\n .await\n .change_context(ValidationError::InvalidValue {\n message: \"Failed while decrypting payment intent\".to_string(),\n })\n }\n\n async fn construct_new(self) -> CustomResult {\n let amount_details = self.amount_details;\n\n Ok(DieselPaymentIntentNew {\n surcharge_applicable: Some(amount_details.get_surcharge_action_as_bool()),\n skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()),\n merchant_id: self.merchant_id,\n status: self.status,\n amount: amount_details.order_amount,\n currency: amount_details.currency,\n amount_captured: self.amount_captured,\n customer_id: self.customer_id,\n description: self.description,\n return_url: self.return_url,\n metadata: self.metadata,\n statement_descriptor: self.statement_descriptor,\n created_at: self.created_at,\n modified_at: self.modified_at,\n last_synced: self.last_synced,\n setup_future_usage: Some(self.setup_future_usage),\n active_attempt_id: self.active_attempt_id,\n order_details: self.order_details,\n allowed_payment_method_types: self\n .allowed_payment_method_types\n .map(|allowed_payment_method_types| {\n allowed_payment_method_types\n .encode_to_value()\n .change_context(ValidationError::InvalidValue {\n message: \"Failed to serialize allowed_payment_method_types\".to_string(),\n })\n })\n .transpose()?\n .map(Secret::new),\n connector_metadata: self\n .connector_metadata\n .map(|cm| {\n cm.encode_to_value()\n .change_context(ValidationError::InvalidValue {\n message: \"Failed to serialize connector_metadata\".to_string(),\n })\n })\n .transpose()?\n .map(Secret::new),\n feature_metadata: self.feature_metadata,\n attempt_count: self.attempt_count,\n profile_id: self.profile_id,\n frm_merchant_decision: self.frm_merchant_decision,\n payment_link_id: self.payment_link_id,\n updated_by: self.updated_by,\n\n request_incremental_authorization: Some(self.request_incremental_authorization),\n split_txns_enabled: Some(self.split_txns_enabled),\n authorization_count: self.authorization_count,\n session_expiry: self.session_expiry,\n request_external_three_ds_authentication: Some(\n self.request_external_three_ds_authentication.as_bool(),\n ),\n frm_metadata: self.frm_metadata,\n customer_details: self.customer_details.map(Encryption::from),\n billing_address: self.billing_address.map(Encryption::from),\n shipping_address: self.shipping_address.map(Encryption::from),\n capture_method: Some(self.capture_method),\n id: self.id,\n merchant_reference_id: self.merchant_reference_id,\n authentication_type: self.authentication_type,\n prerouting_algorithm: self\n .prerouting_algorithm\n .map(|prerouting_algorithm| {\n prerouting_algorithm.encode_to_value().change_context(\n ValidationError::InvalidValue {\n message: \"Failed to serialize prerouting_algorithm\".to_string(),\n },\n )\n })\n .transpose()?,\n surcharge_amount: amount_details.surcharge_amount,\n tax_on_surcharge: amount_details.tax_on_surcharge,\n organization_id: self.organization_id,\n shipping_cost: amount_details.shipping_cost,\n tax_details: amount_details.tax_details,\n enable_payment_link: Some(self.enable_payment_link.as_bool()),\n apply_mit_exemption: Some(self.apply_mit_exemption.as_bool()),\n platform_merchant_id: None,\n force_3ds_challenge: self.force_3ds_challenge,\n force_3ds_challenge_trigger: self.force_3ds_challenge_trigger,\n processor_merchant_id: Some(self.processor_merchant_id),\n created_by: self.created_by.map(|created_by| created_by.to_string()),\n is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,\n routing_algorithm_id: self.routing_algorithm_id,\n is_payment_id_from_merchant: self.is_payment_id_from_merchant,\n payment_channel: None,\n tax_status: None,\n discount_amount: None,\n mit_category: None,\n shipping_amount_tax: None,\n duty_amount: None,\n order_date: None,\n enable_partial_authorization: Some(self.enable_partial_authorization),\n tokenization: None,\n active_attempt_id_type: Some(self.active_attempt_id_type),\n active_attempts_group_id: self.active_attempts_group_id,\n state_metadata: None,\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[async_trait::async_trait]\nimpl behaviour::Conversion for PaymentIntent {\n type DstType = DieselPaymentIntent;\n type NewDstType = DieselPaymentIntentNew;\n\n async fn convert(self) -> CustomResult {\n Ok(DieselPaymentIntent {\n payment_id: self.payment_id,\n merchant_id: self.merchant_id,\n status: self.status,\n amount: self.amount,\n currency: self.currency,\n amount_captured: self.amount_captured,\n customer_id: self.customer_id,\n description: self.description,\n return_url: None, // deprecated\n metadata: self.metadata,\n connector_id: self.connector_id,\n shipping_address_id: self.shipping_address_id,\n billing_address_id: self.billing_address_id,\n statement_descriptor_name: self.statement_descriptor_name,\n statement_descriptor_suffix: self.statement_descriptor_suffix,\n created_at: self.created_at,\n modified_at: self.modified_at,\n last_synced: self.last_synced,\n setup_future_usage: self.setup_future_usage,\n off_session: self.off_session,\n client_secret: self.client_secret,\n active_attempt_id: self.active_attempt.get_id(),\n business_country: self.business_country,\n business_label: self.business_label,\n order_details: self.order_details,\n allowed_payment_method_types: self.allowed_payment_method_types,\n connector_metadata: self.connector_metadata,\n feature_metadata: self.feature_metadata,\n attempt_count: self.attempt_count,\n profile_id: self.profile_id,\n merchant_decision: self.merchant_decision,\n payment_link_id: self.payment_link_id,\n payment_confirm_source: self.payment_confirm_source,\n updated_by: self.updated_by,\n surcharge_applicable: self.surcharge_applicable,\n request_incremental_authorization: self.request_incremental_authorization,\n incremental_authorization_allowed: self.incremental_authorization_allowed,\n authorization_count: self.authorization_count,\n fingerprint_id: self.fingerprint_id,\n session_expiry: self.session_expiry,\n request_external_three_ds_authentication: self.request_external_three_ds_authentication,\n charges: None,\n split_payments: self.split_payments,\n frm_metadata: self.frm_metadata,\n customer_details: self.customer_details.map(Encryption::from),\n billing_details: self.billing_details.map(Encryption::from),\n merchant_order_reference_id: self.merchant_order_reference_id,\n shipping_details: self.shipping_details.map(Encryption::from),\n is_payment_processor_token_flow: self.is_payment_processor_token_flow,\n organization_id: self.organization_id,\n shipping_cost: self.shipping_cost,\n tax_details: self.tax_details,\n skip_external_tax_calculation: self.skip_external_tax_calculation,\n request_extended_authorization: self.request_extended_authorization,\n psd2_sca_exemption_type: self.psd2_sca_exemption_type,\n platform_merchant_id: None,\n processor_merchant_id: Some(self.processor_merchant_id),\n created_by: self.created_by.map(|created_by| created_by.to_string()),\n force_3ds_challenge: self.force_3ds_challenge,\n force_3ds_challenge_trigger: self.force_3ds_challenge_trigger,\n is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,\n extended_return_url: self.return_url,\n is_payment_id_from_merchant: self.is_payment_id_from_merchant,\n payment_channel: self.payment_channel,\n tax_status: self.tax_status,\n discount_amount: self.discount_amount,\n order_date: self.order_date,\n shipping_amount_tax: self.shipping_amount_tax,\n duty_amount: self.duty_amount,\n enable_partial_authorization: self.enable_partial_authorization,\n enable_overcapture: self.enable_overcapture,\n mit_category: self.mit_category,\n billing_descriptor: self.billing_descriptor,\n tokenization: self.tokenization,\n partner_merchant_identifier_details: self.partner_merchant_identifier_details,\n state_metadata: self.state_metadata,\n })\n }\n\n async fn convert_back(\n state: &KeyManagerState,\n storage_model: Self::DstType,\n key: &Secret>,\n key_manager_identifier: keymanager::Identifier,\n ) -> CustomResult\n where\n Self: Sized,\n {\n async {\n let decrypted_data = crypto_operation(\n state,\n type_name!(Self::DstType),\n CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable(\n super::EncryptedPaymentIntent {\n billing_details: storage_model.billing_details,\n shipping_details: storage_model.shipping_details,\n customer_details: storage_model.customer_details,\n },\n )),\n key_manager_identifier,\n key.peek(),\n )\n .await\n .and_then(|val| val.try_into_batchoperation())?;\n\n let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data)\n .change_context(common_utils::errors::CryptoError::DecodingFailed)\n .attach_printable(\"Invalid batch operation data\")?;\n\n Ok::>(Self {\n payment_id: storage_model.payment_id,\n merchant_id: storage_model.merchant_id.clone(),\n status: storage_model.status,\n amount: storage_model.amount,\n currency: storage_model.currency,\n amount_captured: storage_model.amount_captured,\n customer_id: storage_model.customer_id,\n description: storage_model.description,\n return_url: storage_model\n .extended_return_url\n .or(storage_model.return_url), // fallback to legacy\n metadata: storage_model.metadata,\n connector_id: storage_model.connector_id,\n shipping_address_id: storage_model.shipping_address_id,\n billing_address_id: storage_model.billing_address_id,\n statement_descriptor_name: storage_model.statement_descriptor_name,\n statement_descriptor_suffix: storage_model.statement_descriptor_suffix,\n created_at: storage_model.created_at,\n modified_at: storage_model.modified_at,\n last_synced: storage_model.last_synced,\n setup_future_usage: storage_model.setup_future_usage,\n off_session: storage_model.off_session,\n client_secret: storage_model.client_secret,\n active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id),\n business_country: storage_model.business_country,\n business_label: storage_model.business_label,\n order_details: storage_model.order_details,\n allowed_payment_method_types: storage_model.allowed_payment_method_types,\n connector_metadata: storage_model.connector_metadata,\n feature_metadata: storage_model.feature_metadata,\n attempt_count: storage_model.attempt_count,\n profile_id: storage_model.profile_id,\n merchant_decision: storage_model.merchant_decision,\n payment_link_id: storage_model.payment_link_id,\n payment_confirm_source: storage_model.payment_confirm_source,\n updated_by: storage_model.updated_by,\n surcharge_applicable: storage_model.surcharge_applicable,\n request_incremental_authorization: storage_model.request_incremental_authorization,\n incremental_authorization_allowed: storage_model.incremental_authorization_allowed,\n authorization_count: storage_model.authorization_count,\n fingerprint_id: storage_model.fingerprint_id,\n session_expiry: storage_model.session_expiry,\n request_external_three_ds_authentication: storage_model\n .request_external_three_ds_authentication,\n split_payments: storage_model.split_payments,\n frm_metadata: storage_model.frm_metadata,\n shipping_cost: storage_model.shipping_cost,\n tax_details: storage_model.tax_details,\n customer_details: data.customer_details,\n billing_details: data.billing_details,\n merchant_order_reference_id: storage_model.merchant_order_reference_id,\n shipping_details: data.shipping_details,\n is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,\n organization_id: storage_model.organization_id,\n skip_external_tax_calculation: storage_model.skip_external_tax_calculation,\n request_extended_authorization: storage_model.request_extended_authorization,\n psd2_sca_exemption_type: storage_model.psd2_sca_exemption_type,\n processor_merchant_id: storage_model\n .processor_merchant_id\n .unwrap_or(storage_model.merchant_id),\n created_by: storage_model\n .created_by\n .and_then(|created_by| created_by.parse::().ok()),\n force_3ds_challenge: storage_model.force_3ds_challenge,\n force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger,\n is_iframe_redirection_enabled: storage_model.is_iframe_redirection_enabled,\n is_payment_id_from_merchant: storage_model.is_payment_id_from_merchant,\n payment_channel: storage_model.payment_channel,\n tax_status: storage_model.tax_status,\n discount_amount: storage_model.discount_amount,\n shipping_amount_tax: storage_model.shipping_amount_tax,\n duty_amount: storage_model.duty_amount,\n order_date: storage_model.order_date,\n enable_partial_authorization: storage_model.enable_partial_authorization,\n enable_overcapture: storage_model.enable_overcapture,\n mit_category: storage_model.mit_category,\n billing_descriptor: storage_model.billing_descriptor,\n tokenization: storage_model.tokenization,\n partner_merchant_identifier_details: storage_model\n .partner_merchant_identifier_details,\n state_metadata: storage_model.state_metadata,\n })\n }\n .await\n .change_context(ValidationError::InvalidValue {\n message: \"Failed while decrypting payment intent\".to_string(),\n })\n }\n\n async fn construct_new(self) -> CustomResult {\n Ok(DieselPaymentIntentNew {\n payment_id: self.payment_id,\n merchant_id: self.merchant_id,\n status: self.status,\n amount: self.amount,\n currency: self.currency,\n amount_captured: self.amount_captured,\n customer_id: self.customer_id,\n description: self.description,\n return_url: None, // deprecated\n metadata: self.metadata,\n connector_id: self.connector_id,\n shipping_address_id: self.shipping_address_id,\n billing_address_id: self.billing_address_id,\n statement_descriptor_name: self.statement_descriptor_name,\n statement_descriptor_suffix: self.statement_descriptor_suffix,\n created_at: self.created_at,\n modified_at: self.modified_at,\n last_synced: self.last_synced,\n setup_future_usage: self.setup_future_usage,\n off_session: self.off_session,\n client_secret: self.client_secret,\n active_attempt_id: self.active_attempt.get_id(),\n business_country: self.business_country,\n business_label: self.business_label,\n order_details: self.order_details,\n allowed_payment_method_types: self.allowed_payment_method_types,\n connector_metadata: self.connector_metadata,\n feature_metadata: self.feature_metadata,\n attempt_count: self.attempt_count,\n profile_id: self.profile_id,\n merchant_decision: self.merchant_decision,\n payment_link_id: self.payment_link_id,\n payment_confirm_source: self.payment_confirm_source,\n updated_by: self.updated_by,\n surcharge_applicable: self.surcharge_applicable,\n request_incremental_authorization: self.request_incremental_authorization,\n incremental_authorization_allowed: self.incremental_authorization_allowed,\n authorization_count: self.authorization_count,\n fingerprint_id: self.fingerprint_id,\n session_expiry: self.session_expiry,\n request_external_three_ds_authentication: self.request_external_three_ds_authentication,\n charges: None,\n split_payments: self.split_payments,\n frm_metadata: self.frm_metadata,\n customer_details: self.customer_details.map(Encryption::from),\n billing_details: self.billing_details.map(Encryption::from),\n merchant_order_reference_id: self.merchant_order_reference_id,\n shipping_details: self.shipping_details.map(Encryption::from),\n is_payment_processor_token_flow: self.is_payment_processor_token_flow,\n organization_id: self.organization_id,\n shipping_cost: self.shipping_cost,\n tax_details: self.tax_details,\n skip_external_tax_calculation: self.skip_external_tax_calculation,\n request_extended_authorization: self.request_extended_authorization,\n psd2_sca_exemption_type: self.psd2_sca_exemption_type,\n platform_merchant_id: None,\n processor_merchant_id: Some(self.processor_merchant_id),\n created_by: self.created_by.map(|created_by| created_by.to_string()),\n force_3ds_challenge: self.force_3ds_challenge,\n force_3ds_challenge_trigger: self.force_3ds_challenge_trigger,\n is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,\n extended_return_url: self.return_url,\n is_payment_id_from_merchant: self.is_payment_id_from_merchant,\n payment_channel: self.payment_channel,\n tax_status: self.tax_status,\n discount_amount: self.discount_amount,\n order_date: self.order_date,\n shipping_amount_tax: self.shipping_amount_tax,\n duty_amount: self.duty_amount,\n enable_partial_authorization: self.enable_partial_authorization,\n enable_overcapture: self.enable_overcapture,\n mit_category: self.mit_category,\n billing_descriptor: self.billing_descriptor,\n tokenization: self.tokenization,\n partner_merchant_identifier_details: self.partner_merchant_identifier_details,\n state_metadata: self.state_metadata,\n })\n }\n}\n"} {"file_name": "crates__hyperswitch_domain_models__src__router_data.rs", "text": "use std::{collections::HashMap, marker::PhantomData};\n\nuse api_models::customers::CustomerDocumentDetails;\nuse cards::NetworkToken;\nuse common_types::{payments as common_payment_types, primitive_wrappers};\nuse common_utils::{\n errors::IntegrityCheckError,\n ext_traits::{OptionExt, ValueExt},\n id_type::{self},\n types::MinorUnit,\n};\nuse error_stack::ResultExt;\nuse masking::{ExposeInterface, Secret};\nuse serde::{Deserialize, Serialize};\n\nuse crate::{\n address::AddressDetails, payment_address::PaymentAddress, payment_method_data, payments,\n router_response_types,\n};\n#[cfg(feature = \"v2\")]\nuse crate::{\n payments::{\n payment_attempt::{ErrorDetails, PaymentAttemptUpdate},\n payment_intent::PaymentIntentUpdate,\n },\n router_flow_types, router_request_types,\n};\n\n#[derive(Debug, Clone, Serialize)]\npub struct RouterData {\n pub flow: PhantomData,\n pub merchant_id: id_type::MerchantId,\n pub customer_id: Option,\n pub connector_customer: Option,\n pub connector: String,\n // TODO: This should be a PaymentId type.\n // Make this change after all the connector dependency has been removed from connectors\n pub payment_id: String,\n pub attempt_id: String,\n pub tenant_id: id_type::TenantId,\n pub status: common_enums::enums::AttemptStatus,\n pub payment_method: common_enums::enums::PaymentMethod,\n pub payment_method_type: Option,\n pub connector_auth_type: ConnectorAuthType,\n pub description: Option,\n pub address: PaymentAddress,\n pub auth_type: common_enums::enums::AuthenticationType,\n pub connector_meta_data: Option,\n pub connector_wallets_details: Option,\n pub amount_captured: Option,\n pub access_token: Option,\n pub session_token: Option,\n pub reference_id: Option,\n pub payment_method_token: Option,\n pub recurring_mandate_payment_data: Option,\n pub preprocessing_id: Option,\n /// This is the balance amount for gift cards or voucher\n pub payment_method_balance: Option,\n\n ///for switching between two different versions of the same connector\n pub connector_api_version: Option,\n\n /// Contains flow-specific data required to construct a request and send it to the connector.\n pub request: Request,\n\n /// Contains flow-specific data that the connector responds with.\n pub response: Result,\n\n /// Contains a reference ID that should be sent in the connector request\n pub connector_request_reference_id: String,\n\n #[cfg(feature = \"payouts\")]\n /// Contains payout method data\n pub payout_method_data: Option,\n\n #[cfg(feature = \"payouts\")]\n /// Contains payout's quote ID\n pub quote_id: Option,\n\n pub test_mode: Option,\n pub connector_http_status_code: Option,\n pub external_latency: Option,\n /// Contains apple pay flow type simplified or manual\n pub apple_pay_flow: Option,\n\n pub frm_metadata: Option,\n\n pub dispute_id: Option,\n pub refund_id: Option,\n pub payout_id: Option,\n\n /// This field is used to store various data regarding the response from connector\n pub connector_response: Option,\n pub payment_method_status: Option,\n\n // minor amount for amount framework\n pub minor_amount_captured: Option,\n pub minor_amount_capturable: Option,\n\n // stores the authorized amount in case of partial authorization\n pub authorized_amount: Option,\n\n pub integrity_check: Result<(), IntegrityCheckError>,\n\n pub additional_merchant_data: Option,\n\n pub header_payload: Option,\n\n pub connector_mandate_request_reference_id: Option,\n\n pub l2_l3_data: Option>,\n\n pub authentication_id: Option,\n /// Contains the type of sca exemption required for the transaction\n pub psd2_sca_exemption_type: Option,\n\n /// Contains stringified connector raw response body\n pub raw_connector_response: Option>,\n\n /// Indicates whether the payment ID was provided by the merchant (true),\n /// or generated internally by Hyperswitch (false)\n pub is_payment_id_from_merchant: Option,\n\n // Document details of the customer consisting of document number and type\n pub customer_document_details: Option,\n}\n\n#[derive(Debug, Clone, Default, Serialize, Deserialize)]\npub struct L2L3Data {\n pub order_info: Option,\n pub tax_info: Option,\n pub customer_info: Option,\n pub shipping_details: Option,\n pub billing_details: Option,\n}\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct OrderInfo {\n pub order_date: Option,\n pub order_details: Option>,\n pub merchant_order_reference_id: Option,\n pub discount_amount: Option,\n pub shipping_cost: Option,\n pub duty_amount: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct TaxInfo {\n pub tax_status: Option,\n pub customer_tax_registration_id: Option>,\n pub merchant_tax_registration_id: Option>,\n pub shipping_amount_tax: Option,\n pub order_tax_amount: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct CustomerInfo {\n pub customer_id: Option,\n pub customer_email: Option,\n pub customer_name: Option>,\n pub customer_phone_number: Option>,\n pub customer_phone_country_code: Option,\n}\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct BillingDetails {\n pub address_city: Option,\n}\nimpl L2L3Data {\n pub fn get_shipping_country(&self) -> Option {\n self.shipping_details\n .as_ref()\n .and_then(|address| address.country)\n }\n\n pub fn get_shipping_city(&self) -> Option {\n self.shipping_details\n .as_ref()\n .and_then(|address| address.city.clone())\n }\n\n pub fn get_shipping_state(&self) -> Option> {\n self.shipping_details\n .as_ref()\n .and_then(|address| address.state.clone())\n }\n\n pub fn get_shipping_origin_zip(&self) -> Option> {\n self.shipping_details\n .as_ref()\n .and_then(|address| address.origin_zip.clone())\n }\n\n pub fn get_shipping_zip(&self) -> Option> {\n self.shipping_details\n .as_ref()\n .and_then(|address| address.zip.clone())\n }\n\n pub fn get_shipping_address_line1(&self) -> Option> {\n self.shipping_details\n .as_ref()\n .and_then(|address| address.line1.clone())\n }\n\n pub fn get_shipping_address_line2(&self) -> Option> {\n self.shipping_details\n .as_ref()\n .and_then(|address| address.line2.clone())\n }\n\n pub fn get_order_date(&self) -> Option {\n self.order_info.as_ref().and_then(|order| order.order_date)\n }\n\n pub fn get_order_details(&self) -> Option> {\n self.order_info\n .as_ref()\n .and_then(|order| order.order_details.clone())\n }\n\n pub fn get_merchant_order_reference_id(&self) -> Option {\n self.order_info\n .as_ref()\n .and_then(|order| order.merchant_order_reference_id.clone())\n }\n\n pub fn get_discount_amount(&self) -> Option {\n self.order_info\n .as_ref()\n .and_then(|order| order.discount_amount)\n }\n\n pub fn get_shipping_cost(&self) -> Option {\n self.order_info\n .as_ref()\n .and_then(|order| order.shipping_cost)\n }\n\n pub fn get_duty_amount(&self) -> Option {\n self.order_info.as_ref().and_then(|order| order.duty_amount)\n }\n\n pub fn get_tax_status(&self) -> Option {\n self.tax_info.as_ref().and_then(|tax| tax.tax_status)\n }\n\n pub fn get_customer_tax_registration_id(&self) -> Option> {\n self.tax_info\n .as_ref()\n .and_then(|tax| tax.customer_tax_registration_id.clone())\n }\n\n pub fn get_merchant_tax_registration_id(&self) -> Option> {\n self.tax_info\n .as_ref()\n .and_then(|tax| tax.merchant_tax_registration_id.clone())\n }\n\n pub fn get_shipping_amount_tax(&self) -> Option {\n self.tax_info\n .as_ref()\n .and_then(|tax| tax.shipping_amount_tax)\n }\n\n pub fn get_order_tax_amount(&self) -> Option {\n self.tax_info.as_ref().and_then(|tax| tax.order_tax_amount)\n }\n\n pub fn get_customer_id(&self) -> Option {\n self.customer_info\n .as_ref()\n .and_then(|customer| customer.customer_id.clone())\n }\n\n pub fn get_customer_email(&self) -> Option {\n self.customer_info\n .as_ref()\n .and_then(|customer| customer.customer_email.clone())\n }\n\n pub fn get_customer_name(&self) -> Option> {\n self.customer_info\n .as_ref()\n .and_then(|customer| customer.customer_name.clone())\n }\n\n pub fn get_customer_phone_number(&self) -> Option> {\n self.customer_info\n .as_ref()\n .and_then(|customer| customer.customer_phone_number.clone())\n }\n\n pub fn get_customer_phone_country_code(&self) -> Option {\n self.customer_info\n .as_ref()\n .and_then(|customer| customer.customer_phone_country_code.clone())\n }\n pub fn get_billing_city(&self) -> Option {\n self.billing_details\n .as_ref()\n .and_then(|billing| billing.address_city.clone())\n }\n}\n// Different patterns of authentication.\n#[derive(Default, Debug, Clone, Deserialize, Serialize)]\n#[serde(tag = \"auth_type\")]\npub enum ConnectorAuthType {\n TemporaryAuth,\n HeaderKey {\n api_key: Secret,\n },\n BodyKey {\n api_key: Secret,\n key1: Secret,\n },\n SignatureKey {\n api_key: Secret,\n key1: Secret,\n api_secret: Secret,\n },\n MultiAuthKey {\n api_key: Secret,\n key1: Secret,\n api_secret: Secret,\n key2: Secret,\n },\n CurrencyAuthKey {\n auth_key_map: HashMap,\n },\n CertificateAuth {\n certificate: Secret,\n private_key: Secret,\n },\n #[default]\n NoKey,\n}\n\nimpl ConnectorAuthType {\n pub fn from_option_secret_value(\n value: Option,\n ) -> common_utils::errors::CustomResult {\n value\n .parse_value::(\"ConnectorAuthType\")\n .change_context(common_utils::errors::ParsingError::StructParseFailure(\n \"ConnectorAuthType\",\n ))\n }\n\n pub fn from_secret_value(\n value: common_utils::pii::SecretSerdeValue,\n ) -> common_utils::errors::CustomResult {\n value\n .parse_value::(\"ConnectorAuthType\")\n .change_context(common_utils::errors::ParsingError::StructParseFailure(\n \"ConnectorAuthType\",\n ))\n }\n\n // show only first and last two digits of the key and mask others with *\n // mask the entire key if it's length is less than or equal to 4\n fn mask_key(&self, key: String) -> Secret {\n let key_len = key.len();\n let masked_key = if key_len <= 4 {\n \"*\".repeat(key_len)\n } else {\n // Show the first two and last two characters, mask the rest with '*'\n let mut masked_key = String::new();\n let key_len = key.len();\n // Iterate through characters by their index\n for (index, character) in key.chars().enumerate() {\n if index < 2 || index >= key_len - 2 {\n masked_key.push(character); // Keep the first two and last two characters\n } else {\n masked_key.push('*'); // Mask the middle characters\n }\n }\n masked_key\n };\n Secret::new(masked_key)\n }\n\n // Mask the keys in the auth_type\n pub fn get_masked_keys(&self) -> Self {\n match self {\n Self::TemporaryAuth => Self::TemporaryAuth,\n Self::NoKey => Self::NoKey,\n Self::HeaderKey { api_key } => Self::HeaderKey {\n api_key: self.mask_key(api_key.clone().expose()),\n },\n Self::BodyKey { api_key, key1 } => Self::BodyKey {\n api_key: self.mask_key(api_key.clone().expose()),\n key1: self.mask_key(key1.clone().expose()),\n },\n Self::SignatureKey {\n api_key,\n key1,\n api_secret,\n } => Self::SignatureKey {\n api_key: self.mask_key(api_key.clone().expose()),\n key1: self.mask_key(key1.clone().expose()),\n api_secret: self.mask_key(api_secret.clone().expose()),\n },\n Self::MultiAuthKey {\n api_key,\n key1,\n api_secret,\n key2,\n } => Self::MultiAuthKey {\n api_key: self.mask_key(api_key.clone().expose()),\n key1: self.mask_key(key1.clone().expose()),\n api_secret: self.mask_key(api_secret.clone().expose()),\n key2: self.mask_key(key2.clone().expose()),\n },\n Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey {\n auth_key_map: auth_key_map.clone(),\n },\n Self::CertificateAuth {\n certificate,\n private_key,\n } => Self::CertificateAuth {\n certificate: self.mask_key(certificate.clone().expose()),\n private_key: self.mask_key(private_key.clone().expose()),\n },\n }\n }\n}\n\n#[derive(Deserialize, Serialize, Debug, Clone)]\npub struct AccessTokenAuthenticationResponse {\n pub code: Secret,\n pub expires: i64,\n}\n\n#[derive(Deserialize, Serialize, Debug, Clone)]\npub struct AccessToken {\n pub token: Secret,\n pub expires: i64,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub enum PaymentMethodToken {\n Token(Secret),\n ApplePayDecrypt(Box),\n GooglePayDecrypt(Box),\n PazeDecrypt(Box),\n}\n\nimpl PaymentMethodToken {\n pub fn get_payment_method_token(&self) -> Option> {\n match self {\n Self::Token(secret_token) => Some(secret_token.clone()),\n _ => None,\n }\n }\n}\n\n#[derive(Debug, Clone, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct ApplePayPredecryptDataInternal {\n pub application_primary_account_number: cards::CardNumber,\n pub application_expiration_date: String,\n pub currency_code: String,\n pub transaction_amount: i64,\n pub device_manufacturer_identifier: Secret,\n pub payment_data_type: Secret,\n pub payment_data: ApplePayCryptogramDataInternal,\n}\n\n#[derive(Debug, Clone, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct ApplePayCryptogramDataInternal {\n pub online_payment_cryptogram: Secret,\n pub eci_indicator: Option,\n}\n\nimpl TryFrom for common_payment_types::ApplePayPredecryptData {\n type Error = common_utils::errors::ValidationError;\n fn try_from(data: ApplePayPredecryptDataInternal) -> Result {\n let application_expiration_month = data.clone().get_expiry_month()?;\n let application_expiration_year = data.clone().get_four_digit_expiry_year()?;\n\n Ok(Self {\n application_primary_account_number: data.application_primary_account_number.clone(),\n application_expiration_month,\n application_expiration_year,\n payment_data: data.payment_data.into(),\n })\n }\n}\n\nimpl From for common_payment_types::GPayPredecryptData {\n fn from(data: GooglePayPredecryptDataInternal) -> Self {\n Self {\n card_exp_month: Secret::new(data.payment_method_details.expiration_month.two_digits()),\n card_exp_year: Secret::new(data.payment_method_details.expiration_year.four_digits()),\n application_primary_account_number: data.payment_method_details.pan.clone(),\n cryptogram: data.payment_method_details.cryptogram.clone(),\n eci_indicator: data.payment_method_details.eci_indicator.clone(),\n }\n }\n}\n\nimpl From for common_payment_types::ApplePayCryptogramData {\n fn from(payment_data: ApplePayCryptogramDataInternal) -> Self {\n Self {\n online_payment_cryptogram: payment_data.online_payment_cryptogram,\n eci_indicator: payment_data.eci_indicator,\n }\n }\n}\n\nimpl ApplePayPredecryptDataInternal {\n /// This logic being applied as apple pay provides application_expiration_date in the YYMMDD format\n fn get_four_digit_expiry_year(\n &self,\n ) -> Result, common_utils::errors::ValidationError> {\n Ok(Secret::new(format!(\n \"20{}\",\n self.application_expiration_date.get(0..2).ok_or(\n common_utils::errors::ValidationError::InvalidValue {\n message: \"Invalid two-digit year\".to_string(),\n }\n )?\n )))\n }\n\n fn get_expiry_month(&self) -> Result, common_utils::errors::ValidationError> {\n Ok(Secret::new(\n self.application_expiration_date\n .get(2..4)\n .ok_or(common_utils::errors::ValidationError::InvalidValue {\n message: \"Invalid two-digit month\".to_string(),\n })?\n .to_owned(),\n ))\n }\n}\n\n#[derive(Debug, Clone, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct GooglePayPredecryptDataInternal {\n pub message_expiration: String,\n pub message_id: String,\n #[serde(rename = \"paymentMethod\")]\n pub payment_method_type: String,\n pub payment_method_details: GooglePayPaymentMethodDetails,\n}\n\n#[derive(Debug, Clone, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct GooglePayPaymentMethodDetails {\n pub auth_method: common_enums::enums::GooglePayAuthMethod,\n pub expiration_month: cards::CardExpirationMonth,\n pub expiration_year: cards::CardExpirationYear,\n pub pan: cards::CardNumber,\n pub cryptogram: Option>,\n pub eci_indicator: Option,\n pub card_network: Option,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct PazeDecryptedData {\n pub client_id: Secret,\n pub profile_id: String,\n pub token: PazeToken,\n pub payment_card_network: common_enums::enums::CardNetwork,\n pub dynamic_data: Vec,\n pub billing_address: PazeAddress,\n pub consumer: PazeConsumer,\n pub eci: Option,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct PazeToken {\n pub payment_token: NetworkToken,\n pub token_expiration_month: Secret,\n pub token_expiration_year: Secret,\n pub payment_account_reference: Secret,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct PazeDynamicData {\n pub dynamic_data_value: Option>,\n pub dynamic_data_type: Option,\n pub dynamic_data_expiration: Option,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct PazeAddress {\n pub name: Option>,\n pub line1: Option>,\n pub line2: Option>,\n pub line3: Option>,\n pub city: Option>,\n pub state: Option>,\n pub zip: Option>,\n pub country_code: Option,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct PazeConsumer {\n // This is consumer data not customer data.\n pub first_name: Option>,\n pub last_name: Option>,\n pub full_name: Secret,\n pub email_address: common_utils::pii::Email,\n pub mobile_number: Option,\n pub country_code: Option,\n pub language_code: Option,\n}\n\n#[derive(Debug, Clone, Deserialize, Serialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct PazePhoneNumber {\n pub country_code: Secret,\n pub phone_number: Secret,\n}\n\n#[derive(Debug, Default, Clone, Serialize)]\npub struct RecurringMandatePaymentData {\n pub payment_method_type: Option, //required for making recurring payment using saved payment method through stripe\n pub original_payment_authorized_amount: Option,\n pub original_payment_authorized_currency: Option,\n pub mandate_metadata: Option,\n}\n\n#[derive(Debug, Clone, Serialize)]\npub struct PaymentMethodBalance {\n pub amount: MinorUnit,\n pub currency: common_enums::enums::Currency,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ConnectorResponseData {\n pub additional_payment_method_data: Option,\n extended_authorization_response_data: Option,\n is_overcapture_enabled: Option,\n pub mandate_reference: Option,\n}\n\nimpl ConnectorResponseData {\n pub fn with_auth_code(auth_code: String, pmt: common_enums::PaymentMethodType) -> Self {\n let additional_payment_method_data = match pmt {\n common_enums::PaymentMethodType::GooglePay => {\n AdditionalPaymentMethodConnectorResponse::GooglePay {\n auth_code: Some(auth_code),\n }\n }\n common_enums::PaymentMethodType::ApplePay => {\n AdditionalPaymentMethodConnectorResponse::ApplePay {\n auth_code: Some(auth_code),\n }\n }\n _ => AdditionalPaymentMethodConnectorResponse::Card {\n authentication_data: None,\n payment_checks: None,\n card_network: None,\n domestic_network: None,\n auth_code: Some(auth_code),\n },\n };\n Self {\n additional_payment_method_data: Some(additional_payment_method_data),\n extended_authorization_response_data: None,\n is_overcapture_enabled: None,\n mandate_reference: None,\n }\n }\n pub fn with_additional_payment_method_data(\n additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,\n ) -> Self {\n Self {\n additional_payment_method_data: Some(additional_payment_method_data),\n extended_authorization_response_data: None,\n is_overcapture_enabled: None,\n mandate_reference: None,\n }\n }\n pub fn new(\n additional_payment_method_data: Option,\n is_overcapture_enabled: Option,\n extended_authorization_response_data: Option,\n mandate_reference: Option,\n ) -> Self {\n Self {\n additional_payment_method_data,\n extended_authorization_response_data,\n is_overcapture_enabled,\n mandate_reference,\n }\n }\n\n pub fn get_extended_authorization_response_data(\n &self,\n ) -> Option<&ExtendedAuthorizationResponseData> {\n self.extended_authorization_response_data.as_ref()\n }\n\n pub fn is_overcapture_enabled(&self) -> Option {\n self.is_overcapture_enabled\n }\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub enum AdditionalPaymentMethodConnectorResponse {\n Card {\n /// Details regarding the authentication details of the connector, if this is a 3ds payment.\n authentication_data: Option,\n /// Various payment checks that are done for a payment\n payment_checks: Option,\n /// Card Network returned by the processor\n card_network: Option,\n /// Domestic(Co-Branded) Card network returned by the processor\n domestic_network: Option,\n /// auth code returned by the processor\n auth_code: Option,\n },\n PayLater {\n klarna_sdk: Option,\n },\n BankRedirect {\n interac: Option,\n },\n Upi {\n /// UPI mode detected from the connector response\n upi_mode: Option,\n },\n GooglePay {\n auth_code: Option,\n },\n ApplePay {\n auth_code: Option,\n },\n SepaBankTransfer {\n debitor_iban: Option>,\n debitor_bic: Option>,\n debitor_name: Option>,\n debitor_email: Option>,\n },\n}\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct ExtendedAuthorizationResponseData {\n pub extended_authentication_applied:\n Option,\n pub extended_authorization_last_applied_at: Option,\n pub capture_before: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct KlarnaSdkResponse {\n pub payment_type: Option,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct InteracCustomerInfo {\n pub customer_info: Option,\n}\n\n#[derive(Clone, Debug, Serialize)]\npub struct ErrorResponse {\n pub code: String,\n pub message: String,\n pub reason: Option,\n pub status_code: u16,\n pub attempt_status: Option,\n pub connector_transaction_id: Option,\n pub connector_response_reference_id: Option,\n pub network_decline_code: Option,\n pub network_advice_code: Option,\n pub network_error_message: Option,\n pub connector_metadata: Option>,\n}\n\nimpl Default for ErrorResponse {\n fn default() -> Self {\n Self {\n code: \"HE_00\".to_string(),\n message: \"Something went wrong\".to_string(),\n reason: None,\n status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_decline_code: None,\n network_advice_code: None,\n network_error_message: None,\n connector_metadata: None,\n }\n }\n}\n\nimpl ErrorResponse {\n pub fn get_not_implemented() -> Self {\n Self {\n code: \"IR_00\".to_string(),\n message: \"This API is under development and will be made available soon.\".to_string(),\n reason: None,\n status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_decline_code: None,\n network_advice_code: None,\n network_error_message: None,\n connector_metadata: None,\n }\n }\n}\n\n/// Get updatable trakcer objects of payment intent and payment attempt\n#[cfg(feature = \"v2\")]\npub trait TrackerPostUpdateObjects {\n fn get_payment_intent_update(\n &self,\n payment_data: &D,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentIntentUpdate;\n\n fn get_payment_attempt_update(\n &self,\n payment_data: &D,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentAttemptUpdate;\n\n /// Get the amount that can be captured for the payment\n fn get_amount_capturable(&self, payment_data: &D) -> Option;\n\n /// Get the amount that has been captured for the payment\n fn get_captured_amount(&self, payment_data: &D) -> Option;\n\n /// Get the intent status based on parameters like captured amount and amount capturable\n fn get_intent_status_for_db_update(\n &self,\n payment_data: &D,\n ) -> common_enums::enums::IntentStatus;\n\n /// Get the intent error response status based on parameters like captured amount and amount capturable\n fn get_intent_error_response_status_for_db_update(\n &self,\n payment_data: &D,\n error: ErrorResponse,\n ) -> common_enums::enums::IntentStatus;\n\n /// Get the attempt status based on parameters like captured amount and amount capturable\n fn get_attempt_status_for_db_update(\n &self,\n payment_data: &D,\n ) -> common_enums::enums::AttemptStatus;\n}\n\n#[cfg(feature = \"v2\")]\nimpl\n TrackerPostUpdateObjects<\n router_flow_types::Authorize,\n router_request_types::PaymentsAuthorizeData,\n payments::PaymentConfirmData,\n >\n for RouterData<\n router_flow_types::Authorize,\n router_request_types::PaymentsAuthorizeData,\n router_response_types::PaymentsResponseData,\n >\n{\n fn get_payment_intent_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentIntentUpdate {\n let amount_captured = self.get_captured_amount(payment_data);\n let intent_amount_captured = payment_data\n .payment_intent\n .amount_captured\n .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))\n .or(amount_captured);\n let updated_feature_metadata =\n payment_data\n .payment_intent\n .feature_metadata\n .clone()\n .map(|mut feature_metadata| {\n if let Some(ref mut payment_revenue_recovery_metadata) =\n feature_metadata.payment_revenue_recovery_metadata\n {\n payment_revenue_recovery_metadata.payment_connector_transmission = match &self.response {\n Ok(_) => common_enums::enums::PaymentConnectorTransmission::ConnectorCallSucceeded,\n Err(error_response) => match &error_response.status_code {\n 500..=511 => common_enums::enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,\n _ => common_enums::enums::PaymentConnectorTransmission::ConnectorCallSucceeded,\n }\n }\n }\n Box::new(feature_metadata)\n });\n\n match self.response {\n Ok(ref _response) => {\n let status = self.get_intent_status_for_db_update(payment_data);\n\n PaymentIntentUpdate::ConfirmIntentPostUpdate {\n status,\n amount_captured: intent_amount_captured,\n updated_by: storage_scheme.to_string(),\n feature_metadata: updated_feature_metadata,\n }\n }\n Err(ref error) => {\n let status = self\n .get_intent_error_response_status_for_db_update(payment_data, error.clone());\n PaymentIntentUpdate::ConfirmIntentPostUpdate {\n status,\n amount_captured: intent_amount_captured,\n updated_by: storage_scheme.to_string(),\n feature_metadata: updated_feature_metadata,\n }\n }\n }\n }\n\n fn get_payment_attempt_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentAttemptUpdate {\n let amount_capturable = self.get_amount_capturable(payment_data);\n let amount_captured = self.get_captured_amount(payment_data);\n\n match self.response {\n Ok(ref response_router_data) => match response_router_data {\n router_response_types::PaymentsResponseData::TransactionResponse {\n resource_id,\n redirection_data,\n connector_metadata,\n connector_response_reference_id,\n ..\n } => {\n let attempt_status = self.get_attempt_status_for_db_update(payment_data);\n\n let connector_payment_id = match resource_id {\n router_request_types::ResponseId::NoResponseId => None,\n router_request_types::ResponseId::ConnectorTransactionId(id)\n | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),\n };\n\n PaymentAttemptUpdate::ConfirmIntentResponse(Box::new(\n payments::payment_attempt::ConfirmIntentResponseUpdate {\n status: attempt_status,\n connector_payment_id,\n updated_by: storage_scheme.to_string(),\n redirection_data: *redirection_data.clone(),\n amount_capturable,\n connector_metadata: connector_metadata.clone().map(Secret::new),\n connector_token_details: response_router_data\n .get_updated_connector_token_details(\n payment_data\n .payment_attempt\n .connector_token_details\n .as_ref()\n .and_then(|token_details| {\n token_details.get_connector_token_request_reference_id()\n }),\n ),\n connector_response_reference_id: connector_response_reference_id\n .clone(),\n amount_captured,\n payment_method_data: payment_data\n .payment_attempt\n .payment_method_data\n .clone(),\n },\n ))\n }\n router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::ConnectorCustomerResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {\n ..\n } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {\n ..\n } => todo!(),\n },\n Err(ref error_response) => {\n let ErrorResponse {\n code,\n message,\n reason,\n status_code: _,\n attempt_status: _,\n connector_transaction_id,\n connector_response_reference_id,\n network_decline_code,\n network_advice_code,\n network_error_message,\n connector_metadata,\n } = error_response.clone();\n\n let attempt_status = match error_response.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None => match error_response.status_code {\n 500..=511 => common_enums::enums::AttemptStatus::Pending,\n _ => common_enums::enums::AttemptStatus::Failure,\n },\n };\n let error_details = ErrorDetails {\n code,\n message,\n reason,\n unified_code: None,\n unified_message: None,\n network_advice_code,\n network_decline_code,\n network_error_message,\n };\n\n PaymentAttemptUpdate::ErrorUpdate {\n status: attempt_status,\n error: Box::new(error_details),\n amount_capturable,\n connector_payment_id: connector_transaction_id,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n payment_method_data: payment_data.payment_attempt.payment_method_data.clone(),\n }\n }\n }\n }\n\n fn get_attempt_status_for_db_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> common_enums::AttemptStatus {\n match self.status {\n common_enums::AttemptStatus::Charged => {\n let amount_captured = self\n .get_captured_amount(payment_data)\n .unwrap_or(MinorUnit::zero());\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n\n if amount_captured == total_amount {\n common_enums::AttemptStatus::Charged\n } else {\n common_enums::AttemptStatus::PartialCharged\n }\n }\n _ => self.status,\n }\n }\n\n fn get_intent_status_for_db_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> common_enums::IntentStatus {\n let base_status =\n common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data));\n\n let amount_captured = self.get_captured_amount(payment_data);\n let intent_amount_captured = payment_data\n .payment_intent\n .amount_captured\n .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))\n .or(amount_captured);\n\n let has_captured_amount = intent_amount_captured\n .map(|amt| amt > MinorUnit::zero())\n .unwrap_or(false);\n\n // If it's a partial authorization flow, we need to adjust the intent status accordingly\n if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {\n match self.status {\n common_enums::enums::AttemptStatus::Pending => {\n common_enums::IntentStatus::PartiallyCapturedAndProcessing\n }\n status if status.is_payment_terminal_failure() => {\n common_enums::IntentStatus::PartiallyCaptured\n }\n _ => base_status,\n }\n } else {\n base_status\n }\n }\n\n fn get_intent_error_response_status_for_db_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n error: ErrorResponse,\n ) -> common_enums::enums::IntentStatus {\n // Step 1: Determine attempt_status using existing logic\n let attempt_status = match error.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None => match error.status_code {\n 500..=511 => common_enums::enums::AttemptStatus::Pending,\n _ => common_enums::enums::AttemptStatus::Failure,\n },\n };\n // Step 2: Check if amount was captured\n let amount_captured = self.get_captured_amount(payment_data);\n let intent_amount_captured = payment_data\n .payment_intent\n .amount_captured\n .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))\n .or(amount_captured);\n\n let has_captured_amount = intent_amount_captured\n .map(|amt| amt > MinorUnit::zero())\n .unwrap_or(false);\n\n // Step 3: Map to intent status based on both attempt_status and amount_captured\n\n if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {\n match self.status {\n common_enums::enums::AttemptStatus::Pending => {\n common_enums::IntentStatus::PartiallyCapturedAndProcessing\n }\n status if status.is_payment_terminal_failure() => {\n common_enums::IntentStatus::PartiallyCaptured\n }\n _ => common_enums::IntentStatus::from(attempt_status),\n }\n } else {\n common_enums::IntentStatus::from(attempt_status)\n }\n }\n\n fn get_amount_capturable(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount capturable\n let intent_status = common_enums::IntentStatus::from(self.status);\n let amount_capturable_from_intent_status = match intent_status {\n // If the status is already succeeded / failed we cannot capture any more amount\n // So set the amount capturable to zero\n common_enums::IntentStatus::Succeeded\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Conflicted\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n // For these statuses, update the capturable amount when it reaches terminal / capturable state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None,\n // If status is requires capture, get the total amount that can be captured\n // This is in cases where the capture method will be `manual` or `manual_multiple`\n // We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow\n common_enums::IntentStatus::RequiresCapture => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n // Invalid statues for this flow, after doing authorization this state is invalid\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n };\n self.minor_amount_capturable\n .or(amount_capturable_from_intent_status)\n .or(Some(payment_data.payment_attempt.get_total_amount()))\n }\n\n fn get_captured_amount(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount that was captured\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n // If the status is succeeded then we have captured the whole amount\n // we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported\n common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n // No amount is captured\n common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n // For these statuses, update the amount captured when it reaches terminal state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => Some(MinorUnit::zero()),\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n // No amount has been captured yet\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {\n Some(MinorUnit::zero())\n }\n // Invalid statues for this flow\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable => {\n self.minor_amount_captured\n }\n }\n }\n}\n#[cfg(feature = \"v2\")]\nimpl\n TrackerPostUpdateObjects<\n router_flow_types::Capture,\n router_request_types::PaymentsCaptureData,\n payments::PaymentCaptureData,\n >\n for RouterData<\n router_flow_types::Capture,\n router_request_types::PaymentsCaptureData,\n router_response_types::PaymentsResponseData,\n >\n{\n fn get_payment_intent_update(\n &self,\n payment_data: &payments::PaymentCaptureData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentIntentUpdate {\n let amount_captured = self.get_captured_amount(payment_data);\n match self.response {\n Ok(ref _response) => PaymentIntentUpdate::CaptureUpdate {\n status: self.get_intent_status_for_db_update(payment_data),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n },\n Err(ref error) => PaymentIntentUpdate::CaptureUpdate {\n status: self\n .get_intent_error_response_status_for_db_update(payment_data, error.clone()),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n },\n }\n }\n\n fn get_intent_status_for_db_update(\n &self,\n payment_data: &payments::PaymentCaptureData,\n ) -> common_enums::enums::IntentStatus {\n common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))\n }\n\n fn get_intent_error_response_status_for_db_update(\n &self,\n payment_data: &payments::PaymentCaptureData,\n error: ErrorResponse,\n ) -> common_enums::enums::IntentStatus {\n error\n .attempt_status\n .map(common_enums::IntentStatus::from)\n .unwrap_or(common_enums::IntentStatus::Failed)\n }\n\n fn get_payment_attempt_update(\n &self,\n payment_data: &payments::PaymentCaptureData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentAttemptUpdate {\n let amount_capturable = self.get_amount_capturable(payment_data);\n\n match self.response {\n Ok(ref response_router_data) => match response_router_data {\n router_response_types::PaymentsResponseData::TransactionResponse { .. } => {\n let attempt_status = self.status;\n\n PaymentAttemptUpdate::CaptureUpdate {\n status: attempt_status,\n amount_capturable,\n updated_by: storage_scheme.to_string(),\n }\n }\n router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::ConnectorCustomerResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {\n ..\n } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {\n ..\n } => todo!(),\n },\n Err(ref error_response) => {\n let ErrorResponse {\n code,\n message,\n reason,\n status_code: _,\n attempt_status,\n connector_transaction_id,\n connector_response_reference_id,\n network_advice_code,\n network_decline_code,\n network_error_message,\n connector_metadata: _,\n } = error_response.clone();\n let attempt_status = attempt_status.unwrap_or(self.status);\n\n let error_details = ErrorDetails {\n code,\n message,\n reason,\n unified_code: None,\n unified_message: None,\n network_advice_code,\n network_decline_code,\n network_error_message,\n };\n\n PaymentAttemptUpdate::ErrorUpdate {\n status: attempt_status,\n error: Box::new(error_details),\n amount_capturable,\n connector_payment_id: connector_transaction_id,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n payment_method_data: payment_data.payment_attempt.payment_method_data.clone(),\n }\n }\n }\n }\n\n fn get_attempt_status_for_db_update(\n &self,\n payment_data: &payments::PaymentCaptureData,\n ) -> common_enums::AttemptStatus {\n match self.status {\n common_enums::AttemptStatus::Charged => {\n let amount_captured = self\n .get_captured_amount(payment_data)\n .unwrap_or(MinorUnit::zero());\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n\n if amount_captured == total_amount {\n common_enums::AttemptStatus::Charged\n } else {\n common_enums::AttemptStatus::PartialCharged\n }\n }\n _ => self.status,\n }\n }\n\n fn get_amount_capturable(\n &self,\n payment_data: &payments::PaymentCaptureData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount capturable\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n // If the status is already succeeded / failed we cannot capture any more amount\n common_enums::IntentStatus::Succeeded\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Conflicted\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n // For these statuses, update the capturable amount when it reaches terminal / capturable state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n // Invalid statues for this flow\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n }\n }\n\n fn get_captured_amount(\n &self,\n payment_data: &payments::PaymentCaptureData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount capturable\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n // If the status is succeeded then we have captured the whole amount\n common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {\n let amount_to_capture = payment_data\n .payment_attempt\n .amount_details\n .get_amount_to_capture();\n\n let amount_captured = amount_to_capture\n .unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount());\n\n Some(amount_captured)\n }\n // No amount is captured\n common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n // For these statuses, update the amount captured when it reaches terminal state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n // Invalid statues for this flow\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => {\n todo!()\n }\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl\n TrackerPostUpdateObjects<\n router_flow_types::PSync,\n router_request_types::PaymentsSyncData,\n payments::PaymentStatusData,\n >\n for RouterData<\n router_flow_types::PSync,\n router_request_types::PaymentsSyncData,\n router_response_types::PaymentsResponseData,\n >\n{\n fn get_payment_intent_update(\n &self,\n payment_data: &payments::PaymentStatusData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentIntentUpdate {\n let amount_captured = self.get_captured_amount(payment_data);\n let updated_amount_captured_in_db = payment_data\n .payment_intent\n .amount_captured\n .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))\n .or(amount_captured);\n\n match self.response {\n Ok(ref _response) => {\n let status = self.get_intent_status_for_db_update(payment_data);\n PaymentIntentUpdate::SyncUpdate {\n status,\n amount_captured: updated_amount_captured_in_db,\n updated_by: storage_scheme.to_string(),\n }\n }\n Err(ref error) => {\n let status = self\n .get_intent_error_response_status_for_db_update(payment_data, error.clone());\n PaymentIntentUpdate::SyncUpdate {\n status,\n amount_captured: updated_amount_captured_in_db,\n updated_by: storage_scheme.to_string(),\n }\n }\n }\n }\n fn get_intent_status_for_db_update(\n &self,\n payment_data: &payments::PaymentStatusData,\n ) -> common_enums::IntentStatus {\n // Calculate base status from attempt\n let base_status =\n common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data));\n\n let amount_captured = self.get_captured_amount(payment_data);\n let intent_amount_captured = payment_data\n .payment_intent\n .amount_captured\n .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))\n .or(amount_captured);\n\n let has_captured_amount = intent_amount_captured\n .map(|amt| amt > MinorUnit::zero())\n .unwrap_or(false);\n\n // If it's a partial authorization flow, we need to adjust the intent status accordingly\n if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {\n match self.status {\n common_enums::enums::AttemptStatus::Pending => {\n common_enums::IntentStatus::PartiallyCapturedAndProcessing\n }\n status if status.is_payment_terminal_failure() => {\n common_enums::IntentStatus::PartiallyCaptured\n }\n _ => base_status,\n }\n } else {\n base_status\n }\n }\n\n fn get_intent_error_response_status_for_db_update(\n &self,\n payment_data: &payments::PaymentStatusData,\n error: ErrorResponse,\n ) -> common_enums::enums::IntentStatus {\n // Step 1: Determine attempt_status using existing logic\n let attempt_status = match error.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None => match error.status_code {\n 200..=299 => common_enums::enums::AttemptStatus::Failure,\n _ => self.status,\n },\n };\n\n // Step 2: Check if amount was captured\n let amount_captured = self.get_captured_amount(payment_data);\n let intent_amount_captured = payment_data\n .payment_intent\n .amount_captured\n .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))\n .or(amount_captured);\n let has_captured_amount = intent_amount_captured\n .map(|amt| amt > MinorUnit::zero())\n .unwrap_or(false);\n // Step 3: Map to intent status based on both attempt_status and amount_captured\n if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {\n match self.status {\n common_enums::enums::AttemptStatus::Pending => {\n common_enums::IntentStatus::PartiallyCapturedAndProcessing\n }\n status if status.is_payment_terminal_failure() => {\n common_enums::IntentStatus::PartiallyCaptured\n }\n _ => common_enums::IntentStatus::from(attempt_status),\n }\n } else {\n common_enums::IntentStatus::from(attempt_status)\n }\n }\n\n fn get_payment_attempt_update(\n &self,\n payment_data: &payments::PaymentStatusData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentAttemptUpdate {\n let amount_capturable = self.get_amount_capturable(payment_data);\n let amount_captured = self.get_captured_amount(payment_data);\n\n match self.response {\n Ok(ref response_router_data) => match response_router_data {\n router_response_types::PaymentsResponseData::TransactionResponse { .. } => {\n let attempt_status = self.get_attempt_status_for_db_update(payment_data);\n\n // Extract payment_method_data from payment_attempt (already updated with connector response data in PostUpdateTracker)\n let payment_method_data = payment_data\n .payment_attempt\n .payment_method_data\n .as_ref()\n .map(|data| data.clone().expose());\n\n PaymentAttemptUpdate::SyncUpdate {\n status: attempt_status,\n amount_capturable,\n updated_by: storage_scheme.to_string(),\n amount_captured,\n payment_method_data,\n }\n }\n router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::ConnectorCustomerResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {\n ..\n } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {\n ..\n } => todo!(),\n },\n Err(ref error_response) => {\n let ErrorResponse {\n code,\n message,\n reason,\n status_code: _,\n attempt_status: _,\n connector_transaction_id,\n connector_response_reference_id,\n network_advice_code,\n network_decline_code,\n network_error_message,\n connector_metadata: _,\n } = error_response.clone();\n\n let attempt_status = match error_response.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None => match error_response.status_code {\n 200..=299 => common_enums::enums::AttemptStatus::Failure,\n _ => self.status,\n },\n };\n\n let error_details = ErrorDetails {\n code,\n message,\n reason,\n unified_code: None,\n unified_message: None,\n network_advice_code,\n network_decline_code,\n network_error_message,\n };\n\n PaymentAttemptUpdate::ErrorUpdate {\n status: attempt_status,\n error: Box::new(error_details),\n amount_capturable,\n connector_payment_id: connector_transaction_id,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n payment_method_data: payment_data.payment_attempt.payment_method_data.clone(),\n }\n }\n }\n }\n\n fn get_attempt_status_for_db_update(\n &self,\n payment_data: &payments::PaymentStatusData,\n ) -> common_enums::AttemptStatus {\n match self.status {\n common_enums::AttemptStatus::Charged => {\n let amount_captured = self\n .get_captured_amount(payment_data)\n .unwrap_or(MinorUnit::zero());\n\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n\n if amount_captured == total_amount {\n common_enums::AttemptStatus::Charged\n } else {\n common_enums::AttemptStatus::PartialCharged\n }\n }\n _ => self.status,\n }\n }\n\n fn get_amount_capturable(\n &self,\n payment_data: &payments::PaymentStatusData,\n ) -> Option {\n let payment_attempt = &payment_data.payment_attempt;\n\n // Based on the status of the response, we can determine the amount capturable\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n // If the status is already succeeded / failed we cannot capture any more amount\n common_enums::IntentStatus::Succeeded\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Conflicted\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n // For these statuses, update the capturable amount when it reaches terminal / capturable state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture\n | common_enums::IntentStatus::PartiallyCaptured => self.minor_amount_capturable,\n // Invalid statues for this flow\n common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n }\n }\n\n fn get_captured_amount(\n &self,\n payment_data: &payments::PaymentStatusData,\n ) -> Option {\n let payment_attempt = &payment_data.payment_attempt;\n\n // Based on the status of the response, we can determine the amount capturable\n let intent_status = common_enums::IntentStatus::from(self.status);\n let amount_captured_from_intent_status = match intent_status {\n // If the status is succeeded then we have captured the whole amount or amount_to_capture\n common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {\n let amount_to_capture = payment_attempt.amount_details.get_amount_to_capture();\n\n let amount_captured =\n amount_to_capture.unwrap_or(payment_attempt.amount_details.get_net_amount());\n\n Some(amount_captured)\n }\n // No amount is captured\n common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n // For these statuses, update the amount captured when it reaches terminal state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => Some(MinorUnit::zero()),\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {\n Some(MinorUnit::zero())\n }\n // Invalid statues for this flow\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,\n };\n self.minor_amount_captured\n .or(amount_captured_from_intent_status)\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl\n TrackerPostUpdateObjects<\n router_flow_types::ExternalVaultProxy,\n router_request_types::ExternalVaultProxyPaymentsData,\n payments::PaymentConfirmData,\n >\n for RouterData<\n router_flow_types::ExternalVaultProxy,\n router_request_types::ExternalVaultProxyPaymentsData,\n router_response_types::PaymentsResponseData,\n >\n{\n fn get_payment_intent_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentIntentUpdate {\n let amount_captured = self.get_captured_amount(payment_data);\n match self.response {\n Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {\n status: self.get_intent_status_for_db_update(payment_data),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n feature_metadata: None,\n },\n Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {\n status: self\n .get_intent_error_response_status_for_db_update(payment_data, error.clone()),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n feature_metadata: None,\n },\n }\n }\n fn get_intent_status_for_db_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> common_enums::enums::IntentStatus {\n common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))\n }\n\n fn get_intent_error_response_status_for_db_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n error: ErrorResponse,\n ) -> common_enums::enums::IntentStatus {\n let attempt_status = match error.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None => match error.status_code {\n 500..=511 => common_enums::enums::AttemptStatus::Pending,\n _ => common_enums::enums::AttemptStatus::Failure,\n },\n };\n common_enums::IntentStatus::from(attempt_status)\n }\n\n fn get_payment_attempt_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentAttemptUpdate {\n let amount_capturable = self.get_amount_capturable(payment_data);\n let amount_captured = self.get_captured_amount(payment_data);\n\n match self.response {\n Ok(ref response_router_data) => match response_router_data {\n router_response_types::PaymentsResponseData::TransactionResponse {\n resource_id,\n redirection_data,\n connector_metadata,\n connector_response_reference_id,\n ..\n } => {\n let attempt_status = self.get_attempt_status_for_db_update(payment_data);\n\n let connector_payment_id = match resource_id {\n router_request_types::ResponseId::NoResponseId => None,\n router_request_types::ResponseId::ConnectorTransactionId(id)\n | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),\n };\n\n PaymentAttemptUpdate::ConfirmIntentResponse(Box::new(\n payments::payment_attempt::ConfirmIntentResponseUpdate {\n status: attempt_status,\n connector_payment_id,\n updated_by: storage_scheme.to_string(),\n redirection_data: *redirection_data.clone(),\n amount_capturable,\n connector_metadata: connector_metadata.clone().map(Secret::new),\n connector_token_details: response_router_data\n .get_updated_connector_token_details(\n payment_data\n .payment_attempt\n .connector_token_details\n .as_ref()\n .and_then(|token_details| {\n token_details.get_connector_token_request_reference_id()\n }),\n ),\n connector_response_reference_id: connector_response_reference_id\n .clone(),\n amount_captured,\n payment_method_data: payment_data\n .payment_attempt\n .payment_method_data\n .clone(),\n },\n ))\n }\n router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::ConnectorCustomerResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {\n ..\n } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {\n ..\n } => todo!(),\n },\n Err(ref error_response) => {\n let ErrorResponse {\n code,\n message,\n reason,\n status_code: _,\n attempt_status: _,\n connector_transaction_id,\n connector_response_reference_id,\n network_decline_code,\n network_advice_code,\n network_error_message,\n connector_metadata,\n } = error_response.clone();\n\n let attempt_status = match error_response.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None => match error_response.status_code {\n 500..=511 => common_enums::enums::AttemptStatus::Pending,\n _ => common_enums::enums::AttemptStatus::Failure,\n },\n };\n let error_details = ErrorDetails {\n code,\n message,\n reason,\n unified_code: None,\n unified_message: None,\n network_advice_code,\n network_decline_code,\n network_error_message,\n };\n\n PaymentAttemptUpdate::ErrorUpdate {\n status: attempt_status,\n error: Box::new(error_details),\n amount_capturable,\n connector_payment_id: connector_transaction_id,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n payment_method_data: payment_data.payment_attempt.payment_method_data.clone(),\n }\n }\n }\n }\n\n fn get_attempt_status_for_db_update(\n &self,\n _payment_data: &payments::PaymentConfirmData,\n ) -> common_enums::AttemptStatus {\n // For this step, consider whatever status was given by the connector module\n // We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount\n self.status\n }\n\n fn get_amount_capturable(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount capturable\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n common_enums::IntentStatus::Succeeded\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Conflicted\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n }\n }\n\n fn get_captured_amount(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount that was captured\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::CancelledPostCapture => Some(MinorUnit::zero()),\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl\n TrackerPostUpdateObjects<\n router_flow_types::SetupMandate,\n router_request_types::SetupMandateRequestData,\n payments::PaymentConfirmData,\n >\n for RouterData<\n router_flow_types::SetupMandate,\n router_request_types::SetupMandateRequestData,\n router_response_types::PaymentsResponseData,\n >\n{\n fn get_payment_intent_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentIntentUpdate {\n let amount_captured = self.get_captured_amount(payment_data);\n match self.response {\n Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {\n status: self.get_intent_status_for_db_update(payment_data),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n feature_metadata: None,\n },\n Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {\n status: self\n .get_intent_error_response_status_for_db_update(payment_data, error.clone()),\n amount_captured,\n updated_by: storage_scheme.to_string(),\n feature_metadata: None,\n },\n }\n }\n\n fn get_intent_status_for_db_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> common_enums::enums::IntentStatus {\n common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))\n }\n\n fn get_intent_error_response_status_for_db_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n error: ErrorResponse,\n ) -> common_enums::enums::IntentStatus {\n error\n .attempt_status\n .map(common_enums::IntentStatus::from)\n .unwrap_or(common_enums::IntentStatus::Failed)\n }\n\n fn get_payment_attempt_update(\n &self,\n payment_data: &payments::PaymentConfirmData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentAttemptUpdate {\n let amount_capturable = self.get_amount_capturable(payment_data);\n let amount_captured = self.get_captured_amount(payment_data);\n\n match self.response {\n Ok(ref response_router_data) => match response_router_data {\n router_response_types::PaymentsResponseData::TransactionResponse {\n resource_id,\n redirection_data,\n connector_metadata,\n ..\n } => {\n let attempt_status = self.get_attempt_status_for_db_update(payment_data);\n\n let connector_payment_id = match resource_id {\n router_request_types::ResponseId::NoResponseId => None,\n router_request_types::ResponseId::ConnectorTransactionId(id)\n | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()),\n };\n\n PaymentAttemptUpdate::ConfirmIntentResponse(Box::new(\n payments::payment_attempt::ConfirmIntentResponseUpdate {\n status: attempt_status,\n connector_payment_id,\n updated_by: storage_scheme.to_string(),\n redirection_data: *redirection_data.clone(),\n amount_capturable,\n connector_metadata: connector_metadata.clone().map(Secret::new),\n connector_token_details: response_router_data\n .get_updated_connector_token_details(\n payment_data\n .payment_attempt\n .connector_token_details\n .as_ref()\n .and_then(|token_details| {\n token_details.get_connector_token_request_reference_id()\n }),\n ),\n connector_response_reference_id: None,\n amount_captured,\n payment_method_data: payment_data\n .payment_attempt\n .payment_method_data\n .clone(),\n },\n ))\n }\n router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::TransactionUnresolvedResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(),\n router_response_types::PaymentsResponseData::ConnectorCustomerResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse {\n ..\n } => todo!(),\n router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse {\n ..\n } => {\n todo!()\n }\n router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse {\n ..\n } => todo!(),\n },\n Err(ref error_response) => {\n let ErrorResponse {\n code,\n message,\n reason,\n status_code: _,\n attempt_status,\n connector_transaction_id,\n connector_response_reference_id,\n network_advice_code,\n network_decline_code,\n network_error_message,\n connector_metadata: _,\n } = error_response.clone();\n let attempt_status = attempt_status.unwrap_or(self.status);\n\n let error_details = ErrorDetails {\n code,\n message,\n reason,\n unified_code: None,\n unified_message: None,\n network_advice_code,\n network_decline_code,\n network_error_message,\n };\n\n PaymentAttemptUpdate::ErrorUpdate {\n status: attempt_status,\n error: Box::new(error_details),\n amount_capturable,\n connector_payment_id: connector_transaction_id,\n connector_response_reference_id,\n updated_by: storage_scheme.to_string(),\n payment_method_data: payment_data.payment_attempt.payment_method_data.clone(),\n }\n }\n }\n }\n\n fn get_attempt_status_for_db_update(\n &self,\n _payment_data: &payments::PaymentConfirmData,\n ) -> common_enums::AttemptStatus {\n // For this step, consider whatever status was given by the connector module\n // We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount\n self.status\n }\n\n fn get_amount_capturable(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount capturable\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n // If the status is already succeeded / failed we cannot capture any more amount\n // So set the amount capturable to zero\n common_enums::IntentStatus::Succeeded\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Conflicted\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n // For these statuses, update the capturable amount when it reaches terminal / capturable state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n // If status is requires capture, get the total amount that can be captured\n // This is in cases where the capture method will be `manual` or `manual_multiple`\n // We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n // Invalid statues for this flow, after doing authorization this state is invalid\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n }\n }\n\n fn get_captured_amount(\n &self,\n payment_data: &payments::PaymentConfirmData,\n ) -> Option {\n // Based on the status of the response, we can determine the amount that was captured\n let intent_status = common_enums::IntentStatus::from(self.status);\n match intent_status {\n // If the status is succeeded then we have captured the whole amount\n // we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported\n common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {\n let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();\n Some(total_amount)\n }\n // No amount is captured\n common_enums::IntentStatus::Cancelled\n | common_enums::IntentStatus::CancelledPostCapture\n | common_enums::IntentStatus::Failed\n | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),\n // For these statuses, update the amount captured when it reaches terminal state\n common_enums::IntentStatus::RequiresCustomerAction\n | common_enums::IntentStatus::RequiresMerchantAction\n | common_enums::IntentStatus::Processing\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n // Invalid states for this flow\n common_enums::IntentStatus::RequiresPaymentMethod\n | common_enums::IntentStatus::RequiresConfirmation => None,\n // No amount has been captured yet\n common_enums::IntentStatus::RequiresCapture\n | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {\n Some(MinorUnit::zero())\n }\n // Invalid statues for this flow\n common_enums::IntentStatus::PartiallyCaptured\n | common_enums::IntentStatus::PartiallyCapturedAndCapturable\n | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,\n }\n }\n}\n\n#[cfg(feature = \"v2\")]\nimpl\n TrackerPostUpdateObjects<\n router_flow_types::Void,\n router_request_types::PaymentsCancelData,\n payments::PaymentCancelData,\n >\n for RouterData<\n router_flow_types::Void,\n router_request_types::PaymentsCancelData,\n router_response_types::PaymentsResponseData,\n >\n{\n fn get_payment_intent_update(\n &self,\n payment_data: &payments::PaymentCancelData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentIntentUpdate {\n let intent_status = self.get_intent_status_for_db_update(payment_data);\n PaymentIntentUpdate::VoidUpdate {\n status: intent_status,\n updated_by: storage_scheme.to_string(),\n }\n }\n fn get_intent_status_for_db_update(\n &self,\n payment_data: &payments::PaymentCancelData,\n ) -> common_enums::enums::IntentStatus {\n common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))\n }\n\n fn get_intent_error_response_status_for_db_update(\n &self,\n payment_data: &payments::PaymentCancelData,\n error: ErrorResponse,\n ) -> common_enums::enums::IntentStatus {\n error\n .attempt_status\n .map(common_enums::IntentStatus::from)\n .unwrap_or(common_enums::IntentStatus::Failed)\n }\n\n fn get_payment_attempt_update(\n &self,\n payment_data: &payments::PaymentCancelData,\n storage_scheme: common_enums::MerchantStorageScheme,\n ) -> PaymentAttemptUpdate {\n match &self.response {\n Err(ref error_response) => {\n let ErrorResponse {\n code,\n message,\n reason,\n status_code: _,\n attempt_status: _,\n connector_transaction_id,\n connector_response_reference_id,\n network_decline_code,\n network_advice_code,\n network_error_message,\n connector_metadata: _,\n } = error_response.clone();\n\n // Handle errors exactly\n let status = match error_response.attempt_status {\n // Use the status sent by connector in error_response if it's present\n Some(status) => status,\n None => match error_response.status_code {\n 500..=511 => common_enums::AttemptStatus::Pending,\n _ => common_enums::AttemptStatus::VoidFailed,\n },\n };\n\n let error_details = ErrorDetails {\n code,\n message,\n reason,\n unified_code: None,\n unified_message: None,\n network_advice_code,\n network_decline_code,\n network_error_message,\n };\n\n PaymentAttemptUpdate::ErrorUpdate {\n status,\n amount_capturable: Some(MinorUnit::zero()),\n error: Box::new(error_details),\n updated_by: storage_scheme.to_string(),\n connector_payment_id: connector_transaction_id,\n connector_response_reference_id,\n payment_method_data: payment_data.payment_attempt.payment_method_data.clone(),\n }\n }\n Ok(ref _response) => PaymentAttemptUpdate::VoidUpdate {\n status: self.status,\n cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(),\n updated_by: storage_scheme.to_string(),\n },\n }\n }\n\n fn get_amount_capturable(\n &self,\n _payment_data: &payments::PaymentCancelData,\n ) -> Option {\n // For void operations, no amount is capturable\n Some(MinorUnit::zero())\n }\n\n fn get_captured_amount(\n &self,\n _payment_data: &payments::PaymentCancelData,\n ) -> Option {\n // For void operations, no amount is captured\n Some(MinorUnit::zero())\n }\n\n fn get_attempt_status_for_db_update(\n &self,\n _payment_data: &payments::PaymentCancelData,\n ) -> common_enums::AttemptStatus {\n // For void operations, determine status based on response\n match &self.response {\n Err(ref error_response) => match error_response.attempt_status {\n Some(status) => status,\n None => match error_response.status_code {\n 500..=511 => common_enums::AttemptStatus::Pending,\n _ => common_enums::AttemptStatus::VoidFailed,\n },\n },\n Ok(ref _response) => self.status,\n }\n }\n}\n"} {"file_name": "crates__router__src__types__domain__user.rs", "text": "use std::{\n collections::HashSet,\n ops::{Deref, Not},\n str::FromStr,\n sync::LazyLock,\n};\n\nuse api_models::{\n admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,\n};\nuse common_enums::EntityType;\nuse common_utils::{\n crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name,\n types::keymanager::Identifier,\n};\nuse diesel_models::{\n enums::{TotpStatus, UserRoleVersion, UserStatus},\n organization::{self as diesel_org, Organization, OrganizationBridge},\n user as storage_user,\n user_role::{UserRole, UserRoleNew},\n};\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::api::ApplicationResponse;\nuse masking::{ExposeInterface, PeekInterface, Secret};\nuse rand::distributions::{Alphanumeric, DistString};\nuse time::PrimitiveDateTime;\nuse unicode_segmentation::UnicodeSegmentation;\n#[cfg(feature = \"keymanager_create\")]\nuse {base64::Engine, common_utils::types::keymanager::EncryptionTransferRequest};\n\nuse crate::{\n consts,\n core::{\n admin,\n errors::{UserErrors, UserResult},\n },\n db::GlobalStorageInterface,\n routes::SessionState,\n services::{\n self,\n authentication::{AuthenticationDataWithOrg, UserFromToken},\n },\n types::{domain, transformers::ForeignFrom},\n utils::{self, user::password},\n};\n\npub mod dashboard_metadata;\npub mod decision_manager;\npub use decision_manager::*;\npub mod oidc;\npub mod user_authentication_method;\n\nuse super::{types as domain_types, UserKeyStore};\n\n#[derive(Clone)]\npub struct UserName(Secret);\n\nimpl UserName {\n pub fn new(name: Secret) -> UserResult {\n let name = name.expose();\n let is_empty_or_whitespace = name.trim().is_empty();\n let is_too_long = name.graphemes(true).count() > consts::user::MAX_NAME_LENGTH;\n\n let forbidden_characters = ['/', '(', ')', '\"', '<', '>', '\\\\', '{', '}'];\n let contains_forbidden_characters = name.chars().any(|g| forbidden_characters.contains(&g));\n\n if is_empty_or_whitespace || is_too_long || contains_forbidden_characters {\n Err(UserErrors::NameParsingError.into())\n } else {\n Ok(Self(name.into()))\n }\n }\n\n pub fn get_secret(self) -> Secret {\n self.0\n }\n}\n\nimpl TryFrom for UserName {\n type Error = error_stack::Report;\n\n fn try_from(value: pii::Email) -> UserResult {\n Self::new(Secret::new(\n value\n .peek()\n .split_once('@')\n .ok_or(UserErrors::InvalidEmailError)?\n .0\n .to_string(),\n ))\n }\n}\n\n#[derive(Clone, Debug)]\npub struct UserEmail(pii::Email);\n\nstatic BLOCKED_EMAIL: LazyLock> = LazyLock::new(|| {\n let blocked_emails_content = include_str!(\"../../utils/user/blocker_emails.txt\");\n let blocked_emails: HashSet = blocked_emails_content\n .lines()\n .map(|s| s.trim().to_owned())\n .collect();\n blocked_emails\n});\n\nimpl UserEmail {\n pub fn new(email: Secret) -> UserResult {\n use validator::ValidateEmail;\n\n let email_string = email.expose().to_lowercase();\n let email =\n pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?;\n\n if email_string.validate_email() {\n let (_username, domain) = match email_string.as_str().split_once('@') {\n Some((u, d)) => (u, d),\n None => return Err(UserErrors::EmailParsingError.into()),\n };\n\n if BLOCKED_EMAIL.contains(domain) {\n return Err(UserErrors::InvalidEmailError.into());\n }\n Ok(Self(email))\n } else {\n Err(UserErrors::EmailParsingError.into())\n }\n }\n\n pub fn from_pii_email(email: pii::Email) -> UserResult {\n let email_string = email.expose().map(|inner| inner.to_lowercase());\n Self::new(email_string)\n }\n\n pub fn into_inner(self) -> pii::Email {\n self.0\n }\n\n pub fn get_inner(&self) -> &pii::Email {\n &self.0\n }\n\n pub fn get_secret(self) -> Secret {\n (*self.0).clone()\n }\n\n pub fn extract_domain(&self) -> UserResult<&str> {\n let (_username, domain) = self\n .peek()\n .split_once('@')\n .ok_or(UserErrors::InternalServerError)?;\n\n Ok(domain)\n }\n}\n\nimpl TryFrom for UserEmail {\n type Error = error_stack::Report;\n\n fn try_from(value: pii::Email) -> Result {\n Self::from_pii_email(value)\n }\n}\n\nimpl Deref for UserEmail {\n type Target = Secret;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\n#[derive(Clone)]\npub struct UserPassword(Secret);\n\nimpl UserPassword {\n pub fn new(password: Secret) -> UserResult {\n let password = password.expose();\n\n let mut has_upper_case = false;\n let mut has_lower_case = false;\n let mut has_numeric_value = false;\n let mut has_special_character = false;\n let mut has_whitespace = false;\n\n for c in password.chars() {\n has_upper_case = has_upper_case || c.is_uppercase();\n has_lower_case = has_lower_case || c.is_lowercase();\n has_numeric_value = has_numeric_value || c.is_numeric();\n has_special_character = has_special_character || !c.is_alphanumeric();\n has_whitespace = has_whitespace || c.is_whitespace();\n }\n\n let is_password_format_valid = has_upper_case\n && has_lower_case\n && has_numeric_value\n && has_special_character\n && !has_whitespace;\n\n let is_too_long = password.graphemes(true).count() > consts::user::MAX_PASSWORD_LENGTH;\n let is_too_short = password.graphemes(true).count() < consts::user::MIN_PASSWORD_LENGTH;\n\n if is_too_short || is_too_long || !is_password_format_valid {\n return Err(UserErrors::PasswordParsingError.into());\n }\n Ok(Self(password.into()))\n }\n\n pub fn new_password_without_validation(password: Secret) -> UserResult {\n let password = password.expose();\n if password.is_empty() {\n return Err(UserErrors::PasswordParsingError.into());\n }\n Ok(Self(password.into()))\n }\n\n pub fn get_secret(&self) -> Secret {\n self.0.clone()\n }\n}\n\n#[derive(Clone)]\npub struct UserCompanyName(String);\n\nimpl UserCompanyName {\n pub fn new(company_name: String) -> UserResult {\n let company_name = company_name.trim();\n let is_empty_or_whitespace = company_name.is_empty();\n let is_too_long =\n company_name.graphemes(true).count() > consts::user::MAX_COMPANY_NAME_LENGTH;\n\n let is_all_valid_characters = company_name\n .chars()\n .all(|x| x.is_alphanumeric() || x.is_ascii_whitespace() || x == '_');\n if is_empty_or_whitespace || is_too_long || !is_all_valid_characters {\n Err(UserErrors::CompanyNameParsingError.into())\n } else {\n Ok(Self(company_name.to_string()))\n }\n }\n\n pub fn get_secret(self) -> String {\n self.0\n }\n}\n\n#[derive(Clone)]\npub struct NewUserOrganization(diesel_org::OrganizationNew);\n\nimpl NewUserOrganization {\n pub async fn insert_org_in_db(self, state: SessionState) -> UserResult {\n state\n .accounts_store\n .insert_organization(self.0)\n .await\n .map_err(|e| {\n if e.current_context().is_db_unique_violation() {\n e.change_context(UserErrors::DuplicateOrganizationId)\n } else {\n e.change_context(UserErrors::InternalServerError)\n }\n })\n .attach_printable(\"Error while inserting organization\")\n }\n\n pub fn get_organization_id(&self) -> id_type::OrganizationId {\n self.0.get_organization_id()\n }\n}\n\nimpl TryFrom for NewUserOrganization {\n type Error = error_stack::Report;\n fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult {\n let org_type = value.organization_type.unwrap_or_default();\n let new_organization = api_org::OrganizationNew::new(\n org_type,\n Some(UserCompanyName::new(value.company_name)?.get_secret()),\n );\n let db_organization = ForeignFrom::foreign_from(new_organization);\n Ok(Self(db_organization))\n }\n}\n\nimpl From for NewUserOrganization {\n fn from(_value: user_api::SignUpRequest) -> Self {\n let new_organization =\n api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);\n let db_organization = ForeignFrom::foreign_from(new_organization);\n Self(db_organization)\n }\n}\n\nimpl From for NewUserOrganization {\n fn from(_value: user_api::ConnectAccountRequest) -> Self {\n let new_organization =\n api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);\n let db_organization = ForeignFrom::foreign_from(new_organization);\n Self(db_organization)\n }\n}\n\nimpl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserOrganization {\n fn from(\n (_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId),\n ) -> Self {\n let new_organization = api_org::OrganizationNew {\n org_id,\n org_type: common_enums::OrganizationType::Standard,\n org_name: None,\n };\n let db_organization = ForeignFrom::foreign_from(new_organization);\n Self(db_organization)\n }\n}\n\nimpl From for NewUserOrganization {\n fn from(value: UserMerchantCreateRequestWithToken) -> Self {\n Self(diesel_org::OrganizationNew::new(\n value.2.org_id,\n common_enums::OrganizationType::Standard,\n Some(value.1.company_name),\n ))\n }\n}\n\nimpl From for NewUserOrganization {\n fn from(value: user_api::PlatformAccountCreateRequest) -> Self {\n let new_organization = api_org::OrganizationNew::new(\n common_enums::OrganizationType::Platform,\n Some(value.organization_name.expose()),\n );\n let db_organization = ForeignFrom::foreign_from(new_organization);\n Self(db_organization)\n }\n}\n\ntype InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken);\nimpl From for NewUserOrganization {\n fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self {\n let new_organization =\n api_org::OrganizationNew::new(common_enums::OrganizationType::Standard, None);\n let db_organization = ForeignFrom::foreign_from(new_organization);\n Self(db_organization)\n }\n}\n\nimpl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserOrganization {\n fn from(\n (_value, merchant_account_identifier): (\n user_api::CreateTenantUserRequest,\n MerchantAccountIdentifier,\n ),\n ) -> Self {\n let new_organization = api_org::OrganizationNew {\n org_id: merchant_account_identifier.org_id,\n org_type: common_enums::OrganizationType::Standard,\n org_name: None,\n };\n let db_organization = ForeignFrom::foreign_from(new_organization);\n Self(db_organization)\n }\n}\n\nimpl ForeignFrom\n for diesel_models::organization::OrganizationNew\n{\n fn foreign_from(item: api_models::user::UserOrgMerchantCreateRequest) -> Self {\n let org_id = id_type::OrganizationId::default();\n let api_models::user::UserOrgMerchantCreateRequest {\n organization_name,\n organization_details,\n metadata,\n ..\n } = item;\n let mut org_new_db = Self::new(\n org_id,\n common_enums::OrganizationType::Standard,\n Some(organization_name.expose()),\n );\n org_new_db.organization_details = organization_details;\n org_new_db.metadata = metadata;\n org_new_db\n }\n}\n\n#[derive(Clone)]\npub struct MerchantId(String);\n\nimpl MerchantId {\n pub fn new(merchant_id: String) -> UserResult {\n let merchant_id = merchant_id.trim().to_lowercase().replace(' ', \"_\");\n let is_empty_or_whitespace = merchant_id.is_empty();\n\n let is_all_valid_characters = merchant_id.chars().all(|x| x.is_alphanumeric() || x == '_');\n if is_empty_or_whitespace || !is_all_valid_characters {\n Err(UserErrors::MerchantIdParsingError.into())\n } else {\n Ok(Self(merchant_id.to_string()))\n }\n }\n\n pub fn get_secret(&self) -> String {\n self.0.clone()\n }\n}\n\nimpl TryFrom for id_type::MerchantId {\n type Error = error_stack::Report;\n fn try_from(value: MerchantId) -> Result {\n Self::try_from(std::borrow::Cow::from(value.0))\n .change_context(UserErrors::MerchantIdParsingError)\n .attach_printable(\"Could not convert user merchant_id to merchant_id type\")\n }\n}\n\n#[derive(Clone)]\npub struct NewUserMerchant {\n merchant_id: id_type::MerchantId,\n company_name: Option,\n new_organization: NewUserOrganization,\n product_type: Option,\n merchant_account_type: Option,\n}\n\nimpl TryFrom for MerchantName {\n // We should ideally not get this error because all the validations are done for company name\n type Error = error_stack::Report;\n\n fn try_from(company_name: UserCompanyName) -> Result {\n Self::try_new(company_name.get_secret()).change_context(UserErrors::CompanyNameParsingError)\n }\n}\n\nimpl NewUserMerchant {\n pub fn get_company_name(&self) -> Option {\n self.company_name.clone().map(UserCompanyName::get_secret)\n }\n\n pub fn get_merchant_id(&self) -> id_type::MerchantId {\n self.merchant_id.clone()\n }\n\n pub fn get_new_organization(&self) -> NewUserOrganization {\n self.new_organization.clone()\n }\n\n pub fn get_product_type(&self) -> Option {\n self.product_type\n }\n\n pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> {\n if state\n .store\n .get_merchant_key_store_by_merchant_id(\n &self.get_merchant_id(),\n &state.store.get_master_key().to_vec().into(),\n )\n .await\n .is_ok()\n {\n return Err(UserErrors::MerchantAccountCreationError(format!(\n \"Merchant with {:?} already exists\",\n self.get_merchant_id()\n ))\n .into());\n }\n Ok(())\n }\n\n #[cfg(feature = \"v2\")]\n fn create_merchant_account_request(&self) -> UserResult {\n let merchant_name = if let Some(company_name) = self.company_name.clone() {\n MerchantName::try_from(company_name)\n } else {\n MerchantName::try_new(\"merchant\".to_string())\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"merchant name validation failed\")\n }\n .map(Secret::new)?;\n\n Ok(admin_api::MerchantAccountCreate {\n merchant_name,\n organization_id: self.new_organization.get_organization_id(),\n metadata: None,\n merchant_details: None,\n product_type: self.get_product_type(),\n })\n }\n\n #[cfg(feature = \"v1\")]\n fn create_merchant_account_request(&self) -> UserResult {\n Ok(admin_api::MerchantAccountCreate {\n merchant_id: self.get_merchant_id(),\n metadata: None,\n locker_id: None,\n return_url: None,\n merchant_name: self.get_company_name().map(Secret::new),\n webhook_details: None,\n publishable_key: None,\n organization_id: Some(self.new_organization.get_organization_id()),\n merchant_details: None,\n routing_algorithm: None,\n parent_merchant_id: None,\n sub_merchants_enabled: None,\n frm_routing_algorithm: None,\n #[cfg(feature = \"payouts\")]\n payout_routing_algorithm: None,\n primary_business_details: None,\n payment_response_hash_key: None,\n enable_payment_response_hash: None,\n redirect_to_merchant_with_http_post: None,\n pm_collect_link_config: None,\n product_type: self.get_product_type(),\n merchant_account_type: self.merchant_account_type,\n })\n }\n\n #[cfg(feature = \"v1\")]\n pub async fn create_new_merchant_and_insert_in_db(\n &self,\n state: SessionState,\n ) -> UserResult {\n self.check_if_already_exists_in_db(state.clone()).await?;\n\n let merchant_account_create_request = self\n .create_merchant_account_request()\n .attach_printable(\"Unable to construct merchant account create request\")?;\n let org_id = merchant_account_create_request\n .clone()\n .organization_id\n .ok_or(UserErrors::InternalServerError)?;\n let ApplicationResponse::Json(merchant_account_response) =\n Box::pin(admin::create_merchant_account(\n state.clone(),\n merchant_account_create_request,\n Some(AuthenticationDataWithOrg {\n organization_id: org_id,\n }),\n ))\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Error while creating merchant\")?\n else {\n return Err(UserErrors::InternalServerError.into());\n };\n\n let merchant_key_store = state\n .store\n .get_merchant_key_store_by_merchant_id(\n &merchant_account_response.merchant_id,\n &state.store.get_master_key().to_vec().into(),\n )\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Failed to retrieve merchant key store by merchant_id\")?;\n\n let merchant_account = state\n .store\n .find_merchant_account_by_merchant_id(\n &merchant_account_response.merchant_id,\n &merchant_key_store,\n )\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Failed to retrieve merchant account by merchant_id\")?;\n Ok(merchant_account)\n }\n\n #[cfg(feature = \"v2\")]\n pub async fn create_new_merchant_and_insert_in_db(\n &self,\n state: SessionState,\n ) -> UserResult {\n self.check_if_already_exists_in_db(state.clone()).await?;\n\n let merchant_account_create_request = self\n .create_merchant_account_request()\n .attach_printable(\"unable to construct merchant account create request\")?;\n\n let ApplicationResponse::Json(merchant_account_response) = Box::pin(\n admin::create_merchant_account(state.clone(), merchant_account_create_request, None),\n )\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Error while creating a merchant\")?\n else {\n return Err(UserErrors::InternalServerError.into());\n };\n\n let profile_create_request = admin_api::ProfileCreate {\n profile_name: consts::user::DEFAULT_PROFILE_NAME.to_string(),\n ..Default::default()\n };\n\n let merchant_key_store = state\n .store\n .get_merchant_key_store_by_merchant_id(\n &merchant_account_response.id,\n &state.store.get_master_key().to_vec().into(),\n )\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Failed to retrieve merchant key store by merchant_id\")?;\n\n let merchant_account = state\n .store\n .find_merchant_account_by_merchant_id(\n &merchant_account_response.id,\n &merchant_key_store,\n )\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Failed to retrieve merchant account by merchant_id\")?;\n\n let platform = domain::Platform::new(\n merchant_account.clone(),\n merchant_key_store.clone(),\n merchant_account.clone(),\n merchant_key_store.clone(),\n None,\n );\n\n Box::pin(admin::create_profile(\n state,\n profile_create_request,\n platform.get_processor().clone(),\n ))\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Error while creating a profile\")?;\n Ok(merchant_account)\n }\n}\n\nimpl TryFrom for NewUserMerchant {\n type Error = error_stack::Report;\n\n fn try_from(value: user_api::SignUpRequest) -> UserResult {\n let merchant_id = id_type::MerchantId::new_from_unix_timestamp();\n let new_organization = NewUserOrganization::from(value);\n let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);\n Ok(Self {\n company_name: None,\n merchant_id,\n new_organization,\n product_type,\n merchant_account_type: None,\n })\n }\n}\n\nimpl TryFrom for NewUserMerchant {\n type Error = error_stack::Report;\n\n fn try_from(value: user_api::ConnectAccountRequest) -> UserResult {\n let merchant_id = id_type::MerchantId::new_from_unix_timestamp();\n let new_organization = NewUserOrganization::from(value);\n let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);\n Ok(Self {\n company_name: None,\n merchant_id,\n new_organization,\n product_type,\n merchant_account_type: None,\n })\n }\n}\n\nimpl TryFrom for NewUserMerchant {\n type Error = error_stack::Report;\n fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult {\n let company_name = Some(UserCompanyName::new(value.company_name.clone())?);\n let merchant_id = MerchantId::new(value.company_name.clone())?;\n let new_organization = NewUserOrganization::try_from(value)?;\n let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE);\n let merchant_account_type = match new_organization.0.organization_type {\n common_enums::OrganizationType::Platform => {\n Some(common_enums::MerchantAccountType::Platform)\n }\n common_enums::OrganizationType::Standard => {\n Some(common_enums::MerchantAccountType::Standard)\n }\n };\n Ok(Self {\n company_name,\n merchant_id: id_type::MerchantId::try_from(merchant_id)?,\n new_organization,\n product_type,\n merchant_account_type,\n })\n }\n}\n\nimpl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserMerchant {\n type Error = error_stack::Report;\n\n fn try_from(\n value: (user_api::CreateInternalUserRequest, id_type::OrganizationId),\n ) -> UserResult {\n let merchant_id = id_type::MerchantId::get_internal_user_merchant_id(\n consts::user_role::INTERNAL_USER_MERCHANT_ID,\n );\n let new_organization = NewUserOrganization::from(value);\n\n Ok(Self {\n company_name: None,\n merchant_id,\n new_organization,\n product_type: None,\n merchant_account_type: None,\n })\n }\n}\n\nimpl TryFrom for NewUserMerchant {\n type Error = error_stack::Report;\n fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult {\n let merchant_id = value.clone().1.merchant_id;\n let new_organization = NewUserOrganization::from(value);\n Ok(Self {\n company_name: None,\n merchant_id,\n new_organization,\n product_type: None,\n merchant_account_type: None,\n })\n }\n}\n\nimpl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserMerchant {\n fn from(value: (user_api::CreateTenantUserRequest, MerchantAccountIdentifier)) -> Self {\n let merchant_id = value.1.merchant_id.clone();\n let new_organization = NewUserOrganization::from(value);\n Self {\n company_name: None,\n merchant_id,\n new_organization,\n product_type: None,\n merchant_account_type: None,\n }\n }\n}\n\ntype UserMerchantCreateRequestWithToken =\n (UserFromStorage, user_api::UserMerchantCreate, UserFromToken);\n\nimpl TryFrom for NewUserMerchant {\n type Error = error_stack::Report;\n\n fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult {\n let merchant_id =\n utils::user::generate_env_specific_merchant_id(value.1.company_name.clone())?;\n let (user_from_storage, user_merchant_create, user_from_token) = value;\n Ok(Self {\n merchant_id,\n company_name: Some(UserCompanyName::new(\n user_merchant_create.company_name.clone(),\n )?),\n product_type: user_merchant_create.product_type,\n merchant_account_type: user_merchant_create.merchant_account_type.map(Into::into),\n new_organization: NewUserOrganization::from((\n user_from_storage,\n user_merchant_create,\n user_from_token,\n )),\n })\n }\n}\n\nimpl TryFrom for NewUserMerchant {\n type Error = error_stack::Report;\n\n fn try_from(value: user_api::PlatformAccountCreateRequest) -> UserResult {\n let merchant_id = utils::user::generate_env_specific_merchant_id(\n value.organization_name.clone().expose(),\n )?;\n\n let new_organization = NewUserOrganization::from(value);\n Ok(Self {\n company_name: None,\n merchant_id,\n new_organization,\n product_type: Some(consts::user::DEFAULT_PRODUCT_TYPE),\n merchant_account_type: None,\n })\n }\n}\n\n#[derive(Debug, Clone)]\npub struct MerchantAccountIdentifier {\n pub merchant_id: id_type::MerchantId,\n pub org_id: id_type::OrganizationId,\n}\n\n#[derive(Clone)]\npub struct NewUser {\n user_id: String,\n name: UserName,\n email: UserEmail,\n password: Option,\n new_merchant: NewUserMerchant,\n}\n\n#[derive(Clone)]\npub struct NewUserPassword {\n password: UserPassword,\n is_temporary: bool,\n}\n\nimpl Deref for NewUserPassword {\n type Target = UserPassword;\n\n fn deref(&self) -> &Self::Target {\n &self.password\n }\n}\n\nimpl NewUser {\n pub fn get_user_id(&self) -> String {\n self.user_id.clone()\n }\n\n pub fn get_email(&self) -> UserEmail {\n self.email.clone()\n }\n\n pub fn get_name(&self) -> Secret {\n self.name.clone().get_secret()\n }\n\n pub fn get_new_merchant(&self) -> NewUserMerchant {\n self.new_merchant.clone()\n }\n\n pub fn get_password(&self) -> Option {\n self.password\n .as_ref()\n .map(|password| password.deref().clone())\n }\n\n pub async fn insert_user_in_db(\n &self,\n db: &dyn GlobalStorageInterface,\n ) -> UserResult {\n match db.insert_user(self.clone().try_into()?).await {\n Ok(user) => Ok(user.into()),\n Err(e) => {\n if e.current_context().is_db_unique_violation() {\n Err(e.change_context(UserErrors::UserExists))\n } else {\n Err(e.change_context(UserErrors::InternalServerError))\n }\n }\n }\n .attach_printable(\"Error while inserting user\")\n }\n\n pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> {\n if state\n .global_store\n .find_user_by_email(&self.get_email())\n .await\n .is_ok()\n {\n return Err(report!(UserErrors::UserExists));\n }\n Ok(())\n }\n\n pub async fn insert_user_and_merchant_in_db(\n &self,\n state: SessionState,\n ) -> UserResult {\n self.check_if_already_exists_in_db(state.clone()).await?;\n let db = state.global_store.as_ref();\n let merchant_id = self.get_new_merchant().get_merchant_id();\n self.new_merchant\n .create_new_merchant_and_insert_in_db(state.clone())\n .await?;\n\n // If Platform org, update organization with platform_merchant_id\n match self.new_merchant.new_organization.0.organization_type {\n common_enums::OrganizationType::Platform => {\n common_utils::fp_utils::when(\n !matches!(\n self.new_merchant.merchant_account_type,\n Some(common_enums::MerchantAccountType::Platform)\n ),\n || {\n Err(\n report!(UserErrors::InvalidPlatformOperation).attach_printable(\n \"Merchant account type must be Platform for Platform organization\",\n ),\n )\n },\n )?;\n\n let org_update =\n diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {\n platform_merchant_id: merchant_id.clone(),\n };\n\n state\n .accounts_store\n .update_organization_by_org_id(\n &self.new_merchant.new_organization.get_organization_id(),\n org_update,\n )\n .await\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Failed to update organization with platform_merchant_id\")?;\n }\n common_enums::OrganizationType::Standard => {}\n }\n\n let created_user = self.insert_user_in_db(db).await;\n if created_user.is_err() {\n let _ = admin::merchant_account_delete(state, merchant_id).await;\n };\n created_user\n }\n\n pub fn get_no_level_user_role(\n self,\n role_id: String,\n user_status: UserStatus,\n ) -> NewUserRole {\n let now = common_utils::date_time::now();\n let user_id = self.get_user_id();\n\n NewUserRole {\n status: user_status,\n created_by: user_id.clone(),\n last_modified_by: user_id.clone(),\n user_id,\n role_id,\n created_at: now,\n last_modified: now,\n entity: NoLevel,\n }\n }\n\n pub async fn insert_org_level_user_role_in_db(\n self,\n state: SessionState,\n role_id: String,\n user_status: UserStatus,\n ) -> UserResult {\n let org_id = self\n .get_new_merchant()\n .get_new_organization()\n .get_organization_id();\n\n let org_user_role = self\n .get_no_level_user_role(role_id, user_status)\n .add_entity(OrganizationLevel {\n tenant_id: state.tenant.tenant_id.clone(),\n org_id,\n });\n\n org_user_role.insert_in_v2(&state).await\n }\n}\n\nimpl TryFrom for storage_user::UserNew {\n type Error = error_stack::Report;\n\n fn try_from(value: NewUser) -> UserResult {\n let hashed_password = value\n .password\n .as_ref()\n .map(|password| password::generate_password_hash(password.get_secret()))\n .transpose()?;\n\n let now = common_utils::date_time::now();\n Ok(Self {\n user_id: value.get_user_id(),\n name: value.get_name(),\n email: value.get_email().into_inner(),\n password: hashed_password,\n is_verified: false,\n created_at: Some(now),\n last_modified_at: Some(now),\n totp_status: TotpStatus::NotSet,\n totp_secret: None,\n totp_recovery_codes: None,\n last_password_modified_at: value\n .password\n .and_then(|password_inner| password_inner.is_temporary.not().then_some(now)),\n lineage_context: None,\n })\n }\n}\n\nimpl TryFrom for NewUser {\n type Error = error_stack::Report;\n\n fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult {\n let email = value.email.clone().try_into()?;\n let name = UserName::new(value.name.clone())?;\n let password = NewUserPassword {\n password: UserPassword::new(value.password.clone())?,\n is_temporary: false,\n };\n let user_id = uuid::Uuid::new_v4().to_string();\n let new_merchant = NewUserMerchant::try_from(value)?;\n\n Ok(Self {\n name,\n email,\n password: Some(password),\n user_id,\n new_merchant,\n })\n }\n}\n\nimpl TryFrom for NewUser {\n type Error = error_stack::Report;\n\n fn try_from(value: user_api::SignUpRequest) -> UserResult {\n let user_id = uuid::Uuid::new_v4().to_string();\n let email = value.email.clone().try_into()?;\n let name = UserName::try_from(value.email.clone())?;\n let password = NewUserPassword {\n password: UserPassword::new(value.password.clone())?,\n is_temporary: false,\n };\n let new_merchant = NewUserMerchant::try_from(value)?;\n\n Ok(Self {\n user_id,\n name,\n email,\n password: Some(password),\n new_merchant,\n })\n }\n}\n\nimpl TryFrom for NewUser {\n type Error = error_stack::Report;\n\n fn try_from(value: user_api::ConnectAccountRequest) -> UserResult {\n let user_id = uuid::Uuid::new_v4().to_string();\n let email = value.email.clone().try_into()?;\n let name = UserName::try_from(value.email.clone())?;\n let new_merchant = NewUserMerchant::try_from(value)?;\n\n Ok(Self {\n user_id,\n name,\n email,\n password: None,\n new_merchant,\n })\n }\n}\n\nimpl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUser {\n type Error = error_stack::Report;\n\n fn try_from(\n (value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId),\n ) -> UserResult {\n let user_id = uuid::Uuid::new_v4().to_string();\n let email = value.email.clone().try_into()?;\n let name = UserName::new(value.name.clone())?;\n let password = NewUserPassword {\n password: UserPassword::new(value.password.clone())?,\n is_temporary: false,\n };\n let new_merchant = NewUserMerchant::try_from((value, org_id))?;\n\n Ok(Self {\n user_id,\n name,\n email,\n password: Some(password),\n new_merchant,\n })\n }\n}\n\nimpl TryFrom for NewUser {\n type Error = error_stack::Report;\n\n fn try_from(value: UserMerchantCreateRequestWithToken) -> Result {\n let user = value.0.clone();\n let new_merchant = NewUserMerchant::try_from(value)?;\n let password = user\n .0\n .password\n .map(UserPassword::new_password_without_validation)\n .transpose()?\n .map(|password| NewUserPassword {\n password,\n is_temporary: false,\n });\n\n Ok(Self {\n user_id: user.0.user_id,\n name: UserName::new(user.0.name)?,\n email: user.0.email.clone().try_into()?,\n password,\n new_merchant,\n })\n }\n}\n\nimpl TryFrom for NewUser {\n type Error = error_stack::Report;\n fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult {\n let user_id = uuid::Uuid::new_v4().to_string();\n let email = value.0.email.clone().try_into()?;\n let name = UserName::new(value.0.name.clone())?;\n let password = cfg!(not(feature = \"email\")).then_some(NewUserPassword {\n password: UserPassword::new(password::get_temp_password())?,\n is_temporary: true,\n });\n let new_merchant = NewUserMerchant::try_from(value)?;\n\n Ok(Self {\n user_id,\n name,\n email,\n password,\n new_merchant,\n })\n }\n}\n\nimpl TryFrom<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUser {\n type Error = error_stack::Report;\n\n fn try_from(\n (value, merchant_account_identifier): (\n user_api::CreateTenantUserRequest,\n MerchantAccountIdentifier,\n ),\n ) -> UserResult {\n let user_id = uuid::Uuid::new_v4().to_string();\n let email = value.email.clone().try_into()?;\n let name = UserName::new(value.name.clone())?;\n let password = NewUserPassword {\n password: UserPassword::new(value.password.clone())?,\n is_temporary: false,\n };\n let new_merchant = NewUserMerchant::from((value, merchant_account_identifier));\n\n Ok(Self {\n user_id,\n name,\n email,\n password: Some(password),\n new_merchant,\n })\n }\n}\n\n#[derive(Clone)]\npub struct UserFromStorage(pub storage_user::User);\n\nimpl From for UserFromStorage {\n fn from(value: storage_user::User) -> Self {\n Self(value)\n }\n}\n\nimpl UserFromStorage {\n pub fn get_user_id(&self) -> &str {\n self.0.user_id.as_str()\n }\n\n pub fn compare_password(&self, candidate: &Secret) -> UserResult<()> {\n if let Some(password) = self.0.password.as_ref() {\n match password::is_correct_password(candidate, password) {\n Ok(true) => Ok(()),\n Ok(false) => Err(UserErrors::InvalidCredentials.into()),\n Err(e) => Err(e),\n }\n } else {\n Err(UserErrors::InvalidCredentials.into())\n }\n }\n\n pub fn get_name(&self) -> Secret {\n self.0.name.clone()\n }\n\n pub fn get_email(&self) -> pii::Email {\n self.0.email.clone()\n }\n\n #[cfg(feature = \"email\")]\n pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult> {\n if self.0.is_verified {\n return Ok(None);\n }\n\n let allowed_unverified_duration =\n time::Duration::days(state.conf.email.allowed_unverified_days);\n\n let user_created = self.0.created_at.date();\n let last_date_for_verification = user_created\n .checked_add(allowed_unverified_duration)\n .ok_or(UserErrors::InternalServerError)?;\n\n let today = common_utils::date_time::now().date();\n if today >= last_date_for_verification {\n return Err(UserErrors::UnverifiedUser.into());\n }\n\n let days_left_for_verification = last_date_for_verification - today;\n Ok(Some(days_left_for_verification.whole_days()))\n }\n\n pub fn is_verified(&self) -> bool {\n self.0.is_verified\n }\n\n pub fn is_password_rotate_required(&self, state: &SessionState) -> UserResult {\n let last_password_modified_at =\n if let Some(last_password_modified_at) = self.0.last_password_modified_at {\n last_password_modified_at.date()\n } else {\n return Ok(true);\n };\n\n let password_change_duration =\n time::Duration::days(state.conf.user.password_validity_in_days.into());\n let last_date_for_password_rotate = last_password_modified_at\n .checked_add(password_change_duration)\n .ok_or(UserErrors::InternalServerError)?;\n\n let today = common_utils::date_time::now().date();\n let days_left_for_password_rotate = last_date_for_password_rotate - today;\n\n Ok(days_left_for_password_rotate.whole_days() < 0)\n }\n\n pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult {\n let master_key = state.store.get_master_key();\n let key_manager_state = &state.into();\n let key_store_result = state\n .global_store\n .get_user_key_store_by_user_id(self.get_user_id(), &master_key.to_vec().into())\n .await;\n\n if let Ok(key_store) = key_store_result {\n Ok(key_store)\n } else if key_store_result\n .as_ref()\n .map_err(|e| e.current_context().is_db_not_found())\n .err()\n .unwrap_or(false)\n {\n let key = services::generate_aes256_key()\n .change_context(UserErrors::InternalServerError)\n .attach_printable(\"Unable to generate aes 256 key\")?;\n\n #[cfg(feature = \"keymanager_create\")]\n {\n common_utils::keymanager::transfer_key_to_key_manager(\n key_manager_state,\n EncryptionTransferRequest {\n identifier: Identifier::User(self.get_user_id().to_string()),\n key: masking::StrongSecret::new(consts::BASE64_ENGINE.encode(key)),\n },\n )\n .await\n .change_context(UserErrors::InternalServerError)?;\n }\n\n let key_store = UserKeyStore {\n user_id: self.get_user_id().to_string(),\n key: domain_types::crypto_operation(\n key_manager_state,\n type_name!(UserKeyStore),\n domain_types::CryptoOperation::EncryptLocally(key.to_vec().into()),\n Identifier::User(self.get_user_id().to_string()),\n master_key,\n )\n .await\n .and_then(|val| val.try_into_operation())\n .change_context(UserErrors::InternalServerError)?,\n created_at: common_utils::date_time::now(),\n };\n\n state\n .global_store\n .insert_user_key_store(key_store, &master_key.to_vec().into())\n .await\n .change_context(UserErrors::InternalServerError)\n } else {\n Err(key_store_result\n .err()\n .map(|e| e.change_context(UserErrors::InternalServerError))\n .unwrap_or(UserErrors::InternalServerError.into()))\n }\n }\n\n pub fn get_totp_status(&self) -> TotpStatus {\n self.0.totp_status\n }\n\n pub fn get_recovery_codes(&self) -> Option>> {\n self.0.totp_recovery_codes.clone()\n }\n\n pub async fn decrypt_and_get_totp_secret(\n &self,\n state: &SessionState,\n ) -> UserResult>> {\n if self.0.totp_secret.is_none() {\n return Ok(None);\n }\n let key_manager_state = &state.into();\n let user_key_store = state\n .global_store\n .get_user_key_store_by_user_id(\n self.get_user_id(),\n &state.store.get_master_key().to_vec().into(),\n )\n .await\n .change_context(UserErrors::InternalServerError)?;\n\n Ok(domain_types::crypto_operation::(\n key_manager_state,\n type_name!(storage_user::User),\n domain_types::CryptoOperation::DecryptOptional(self.0.totp_secret.clone()),\n Identifier::User(user_key_store.user_id.clone()),\n user_key_store.key.peek(),\n )\n .await\n .and_then(|val| val.try_into_optionaloperation())\n .change_context(UserErrors::InternalServerError)?\n .map(Encryptable::into_inner))\n }\n}\n\nimpl ForeignFrom for user_role_api::UserStatus {\n fn foreign_from(value: UserStatus) -> Self {\n match value {\n UserStatus::Active => Self::Active,\n UserStatus::InvitationSent => Self::InvitationSent,\n }\n }\n}\n\n#[derive(Clone)]\npub struct RoleName(String);\n\nimpl RoleName {\n pub fn new(name: String) -> UserResult {\n let is_empty_or_whitespace = name.trim().is_empty();\n let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH;\n\n if is_empty_or_whitespace || is_too_long || name.contains(' ') {\n Err(UserErrors::RoleNameParsingError.into())\n } else {\n Ok(Self(name.to_lowercase()))\n }\n }\n\n pub fn get_role_name(self) -> String {\n self.0\n }\n}\n\n#[derive(serde::Serialize, serde::Deserialize, Debug)]\npub struct RecoveryCodes(pub Vec>);\n\nimpl RecoveryCodes {\n pub fn generate_new() -> Self {\n let mut rand = rand::thread_rng();\n let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT)\n .map(|_| {\n let code_part_1 =\n Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);\n let code_part_2 =\n Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);\n\n Secret::new(format!(\"{code_part_1}-{code_part_2}\"))\n })\n .collect::>();\n\n Self(recovery_codes)\n }\n\n pub fn get_hashed(&self) -> UserResult>> {\n self.0\n .iter()\n .cloned()\n .map(password::generate_password_hash)\n .collect::, _>>()\n }\n\n pub fn into_inner(self) -> Vec> {\n self.0\n }\n}\n\n// This is for easier construction\n#[derive(Clone)]\npub struct NoLevel;\n\n#[derive(Clone)]\npub struct TenantLevel {\n pub tenant_id: id_type::TenantId,\n}\n\n#[derive(Clone)]\npub struct OrganizationLevel {\n pub tenant_id: id_type::TenantId,\n pub org_id: id_type::OrganizationId,\n}\n\n#[derive(Clone)]\npub struct MerchantLevel {\n pub tenant_id: id_type::TenantId,\n pub org_id: id_type::OrganizationId,\n pub merchant_id: id_type::MerchantId,\n}\n\n#[derive(Clone)]\npub struct ProfileLevel {\n pub tenant_id: id_type::TenantId,\n pub org_id: id_type::OrganizationId,\n pub merchant_id: id_type::MerchantId,\n pub profile_id: id_type::ProfileId,\n}\n\n#[derive(Clone)]\npub struct NewUserRole {\n pub user_id: String,\n pub role_id: String,\n pub status: UserStatus,\n pub created_by: String,\n pub last_modified_by: String,\n pub created_at: PrimitiveDateTime,\n pub last_modified: PrimitiveDateTime,\n pub entity: E,\n}\n\nimpl NewUserRole {\n pub fn add_entity(self, entity: T) -> NewUserRole\n where\n T: Clone,\n {\n NewUserRole {\n entity,\n user_id: self.user_id,\n role_id: self.role_id,\n status: self.status,\n created_by: self.created_by,\n last_modified_by: self.last_modified_by,\n created_at: self.created_at,\n last_modified: self.last_modified,\n }\n }\n}\n\npub struct EntityInfo {\n tenant_id: id_type::TenantId,\n org_id: Option,\n merchant_id: Option,\n profile_id: Option,\n entity_id: String,\n entity_type: EntityType,\n}\n\nimpl From for EntityInfo {\n fn from(value: TenantLevel) -> Self {\n Self {\n entity_id: value.tenant_id.get_string_repr().to_owned(),\n entity_type: EntityType::Tenant,\n tenant_id: value.tenant_id,\n org_id: None,\n merchant_id: None,\n profile_id: None,\n }\n }\n}\n\nimpl From for EntityInfo {\n fn from(value: OrganizationLevel) -> Self {\n Self {\n entity_id: value.org_id.get_string_repr().to_owned(),\n entity_type: EntityType::Organization,\n tenant_id: value.tenant_id,\n org_id: Some(value.org_id),\n merchant_id: None,\n profile_id: None,\n }\n }\n}\n\nimpl From for EntityInfo {\n fn from(value: MerchantLevel) -> Self {\n Self {\n entity_id: value.merchant_id.get_string_repr().to_owned(),\n entity_type: EntityType::Merchant,\n tenant_id: value.tenant_id,\n org_id: Some(value.org_id),\n merchant_id: Some(value.merchant_id),\n profile_id: None,\n }\n }\n}\n\nimpl From for EntityInfo {\n fn from(value: ProfileLevel) -> Self {\n Self {\n entity_id: value.profile_id.get_string_repr().to_owned(),\n entity_type: EntityType::Profile,\n tenant_id: value.tenant_id,\n org_id: Some(value.org_id),\n merchant_id: Some(value.merchant_id),\n profile_id: Some(value.profile_id),\n }\n }\n}\n\nimpl NewUserRole\nwhere\n E: Clone + Into,\n{\n fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew {\n UserRoleNew {\n user_id: self.user_id,\n role_id: self.role_id,\n status: self.status,\n created_by: self.created_by,\n last_modified_by: self.last_modified_by,\n created_at: self.created_at,\n last_modified: self.last_modified,\n org_id: entity.org_id,\n merchant_id: entity.merchant_id,\n profile_id: entity.profile_id,\n entity_id: Some(entity.entity_id),\n entity_type: Some(entity.entity_type),\n version: UserRoleVersion::V2,\n tenant_id: entity.tenant_id,\n }\n }\n\n pub async fn insert_in_v2(self, state: &SessionState) -> UserResult {\n let entity = self.entity.clone();\n\n let new_v2_role = self.convert_to_new_v2_role(entity.into());\n\n state\n .global_store\n .insert_user_role(new_v2_role)\n .await\n .change_context(UserErrors::InternalServerError)\n }\n}\n"} {"file_name": "crates__router__src__utils.rs", "text": "pub mod chat;\n#[cfg(feature = \"olap\")]\npub mod connector_onboarding;\npub mod currency;\npub mod db_utils;\npub mod ext_traits;\n#[cfg(feature = \"olap\")]\npub mod oidc;\n#[cfg(feature = \"kv_store\")]\npub mod storage_partitioning;\n#[cfg(feature = \"olap\")]\npub mod user;\n#[cfg(feature = \"olap\")]\npub mod user_role;\n#[cfg(feature = \"olap\")]\npub mod verify_connector;\nuse std::fmt::Debug;\n\nuse api_models::{\n enums,\n payments::{self},\n subscription as subscription_types, webhooks,\n};\npub use common_utils::{\n crypto::{self, Encryptable},\n ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt},\n fp_utils::when,\n id_type, pii,\n validation::validate_email,\n};\n#[cfg(feature = \"v1\")]\nuse common_utils::{\n type_name,\n types::keymanager::{Identifier, ToEncryptable},\n};\nuse error_stack::ResultExt;\npub use hyperswitch_connectors::utils::QrImage;\nuse hyperswitch_domain_models::payments::PaymentIntent;\n#[cfg(feature = \"v1\")]\nuse hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};\nuse masking::{ExposeInterface, SwitchStrategy};\nuse nanoid::nanoid;\nuse serde::de::DeserializeOwned;\nuse serde_json::Value;\n#[cfg(feature = \"v1\")]\nuse subscriptions::{subscription_handler::SubscriptionHandler, workflows::InvoiceSyncHandler};\nuse tracing_futures::Instrument;\n\npub use self::ext_traits::{OptionExt, ValidateCall};\nuse crate::{\n consts,\n core::{\n authentication::types::ExternalThreeDSConnectorMetadata,\n errors::{self, CustomResult, RouterResult, StorageErrorExt},\n payments as payments_core,\n },\n headers::ACCEPT_LANGUAGE,\n logger,\n routes::{metrics, SessionState},\n services::{self, authentication::get_header_value_by_key},\n types::{self, domain, transformers::ForeignInto},\n};\n#[cfg(feature = \"v1\")]\nuse crate::{core::webhooks as webhooks_core, types::storage};\n\npub mod error_parser {\n use std::fmt::Display;\n\n use actix_web::{\n error::{Error, JsonPayloadError},\n http::StatusCode,\n HttpRequest, ResponseError,\n };\n\n #[derive(Debug)]\n struct CustomJsonError {\n err: JsonPayloadError,\n }\n\n // Display is a requirement defined by the actix crate for implementing ResponseError trait\n impl Display for CustomJsonError {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.write_str(\n serde_json::to_string(&serde_json::json!({\n \"error\": {\n \"error_type\": \"invalid_request\",\n \"message\": self.err.to_string(),\n \"code\": \"IR_06\",\n }\n }))\n .as_deref()\n .unwrap_or(\"Invalid Json Error\"),\n )\n }\n }\n\n impl ResponseError for CustomJsonError {\n fn status_code(&self) -> StatusCode {\n StatusCode::BAD_REQUEST\n }\n\n fn error_response(&self) -> actix_web::HttpResponse {\n use actix_web::http::header;\n\n actix_web::HttpResponseBuilder::new(self.status_code())\n .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON))\n .body(self.to_string())\n }\n }\n\n pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error {\n Error::from(CustomJsonError { err })\n }\n}\n\n#[inline]\npub fn generate_id(length: usize, prefix: &str) -> String {\n format!(\"{}_{}\", prefix, nanoid!(length, &consts::ALPHABETS))\n}\n\npub trait ConnectorResponseExt: Sized {\n fn get_response(self) -> RouterResult;\n fn get_error_response(self) -> RouterResult;\n fn get_response_inner(self, type_name: &'static str) -> RouterResult {\n self.get_response()?\n .response\n .parse_struct(type_name)\n .change_context(errors::ApiErrorResponse::InternalServerError)\n }\n}\n\nimpl ConnectorResponseExt\n for Result, error_stack::Report>\n{\n fn get_error_response(self) -> RouterResult {\n self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError))\n .attach_printable(\"Error while receiving response\")\n .and_then(|inner| match inner {\n Ok(res) => {\n logger::error!(response=?res);\n Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(\n \"Expecting error response, received response: {res:?}\"\n ))\n }\n Err(err_res) => Ok(err_res),\n })\n }\n\n fn get_response(self) -> RouterResult {\n self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError))\n .attach_printable(\"Error while receiving response\")\n .and_then(|inner| match inner {\n Err(err_res) => {\n logger::error!(error_response=?err_res);\n Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(\n \"Expecting response, received error response: {err_res:?}\"\n ))\n }\n Ok(res) => Ok(res),\n })\n }\n}\n\n#[inline]\npub fn get_payout_attempt_id(payout_id: &str, attempt_count: i16) -> String {\n format!(\"{payout_id}_{attempt_count}\")\n}\n\n#[cfg(feature = \"v1\")]\npub async fn find_payment_intent_from_payment_id_type(\n state: &SessionState,\n payment_id_type: payments::PaymentIdType,\n platform: &domain::Platform,\n) -> CustomResult {\n let db = &*state.store;\n match payment_id_type {\n payments::PaymentIdType::PaymentIntentId(payment_id) => db\n .find_payment_intent_by_payment_id_processor_merchant_id(\n &payment_id,\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_key_store(),\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound),\n payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => {\n let attempt = db\n .find_payment_attempt_by_processor_merchant_id_connector_txn_id(\n platform.get_processor().get_account().get_id(),\n &connector_transaction_id,\n platform.get_processor().get_account().storage_scheme,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n db.find_payment_intent_by_payment_id_processor_merchant_id(\n &attempt.payment_id,\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_key_store(),\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)\n }\n payments::PaymentIdType::PaymentAttemptId(attempt_id) => {\n let attempt = db\n .find_payment_attempt_by_attempt_id_processor_merchant_id(\n &attempt_id,\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_account().storage_scheme,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n db.find_payment_intent_by_payment_id_processor_merchant_id(\n &attempt.payment_id,\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_key_store(),\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)\n }\n payments::PaymentIdType::PreprocessingId(_) => {\n Err(errors::ApiErrorResponse::PaymentNotFound)?\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\npub async fn find_payment_intent_from_refund_id_type(\n state: &SessionState,\n refund_id_type: webhooks::RefundIdType,\n platform: &domain::Platform,\n connector_name: &str,\n) -> CustomResult {\n let db = &*state.store;\n let refund = match refund_id_type {\n webhooks::RefundIdType::RefundId(id) => db\n .find_refund_by_merchant_id_refund_id(\n platform.get_processor().get_account().get_id(),\n &id,\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?,\n webhooks::RefundIdType::ConnectorRefundId(id) => db\n .find_refund_by_merchant_id_connector_refund_id_connector(\n platform.get_processor().get_account().get_id(),\n &id,\n connector_name,\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?,\n };\n let attempt = db\n .find_payment_attempt_by_attempt_id_processor_merchant_id(\n &refund.attempt_id,\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_account().storage_scheme,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n db.find_payment_intent_by_payment_id_processor_merchant_id(\n &attempt.payment_id,\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_key_store(),\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)\n}\n\n#[cfg(feature = \"v1\")]\npub async fn find_payment_intent_from_mandate_id_type(\n state: &SessionState,\n mandate_id_type: webhooks::MandateIdType,\n platform: &domain::Platform,\n) -> CustomResult {\n let db = &*state.store;\n let mandate = match mandate_id_type {\n webhooks::MandateIdType::MandateId(mandate_id) => db\n .find_mandate_by_merchant_id_mandate_id(\n platform.get_processor().get_account().get_id(),\n mandate_id.as_str(),\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,\n webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db\n .find_mandate_by_merchant_id_connector_mandate_id(\n platform.get_processor().get_account().get_id(),\n connector_mandate_id.as_str(),\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,\n };\n db.find_payment_intent_by_payment_id_processor_merchant_id(\n &mandate\n .original_payment_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"original_payment_id not present in mandate record\")?,\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_key_store(),\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)\n}\n\n#[cfg(feature = \"v1\")]\npub async fn find_mca_from_authentication_id_type(\n state: &SessionState,\n authentication_id_type: webhooks::AuthenticationIdType,\n platform: &domain::Platform,\n) -> CustomResult {\n let db = &*state.store;\n let authentication = match authentication_id_type {\n webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db\n .find_authentication_by_merchant_id_authentication_id(\n platform.get_processor().get_account().get_id(),\n &authentication_id,\n platform.get_processor().get_key_store(),\n &state.into(),\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?,\n webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => {\n db.find_authentication_by_merchant_id_connector_authentication_id(\n platform.get_processor().get_account().get_id().clone(),\n connector_authentication_id,\n platform.get_processor().get_key_store(),\n &state.into(),\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?\n }\n };\n #[cfg(feature = \"v1\")]\n {\n // raise error if merchant_connector_id is not present since it should we be present in the current flow\n let mca_id = authentication\n .merchant_connector_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"merchant_connector_id not present in authentication record\")?;\n db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n platform.get_processor().get_account().get_id(),\n &mca_id,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(\n errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: mca_id.get_string_repr().to_string(),\n },\n )\n }\n #[cfg(feature = \"v2\")]\n //get mca using id\n {\n let _ = key_store;\n let _ = authentication;\n todo!()\n }\n}\n\n#[cfg(feature = \"v1\")]\npub async fn get_mca_from_payment_intent(\n state: &SessionState,\n platform: &domain::Platform,\n payment_intent: PaymentIntent,\n connector_name: &str,\n) -> CustomResult {\n let db = &*state.store;\n\n #[cfg(feature = \"v1\")]\n let payment_attempt = db\n .find_payment_attempt_by_attempt_id_processor_merchant_id(\n &payment_intent.active_attempt.get_id(),\n platform.get_processor().get_account().get_id(),\n platform.get_processor().get_account().storage_scheme,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n\n #[cfg(feature = \"v2\")]\n let payment_attempt = db\n .find_payment_attempt_by_attempt_id_merchant_id(\n key_manager_state,\n key_store,\n &payment_intent.active_attempt.get_id(),\n merchant_account.get_id(),\n merchant_account.storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;\n\n match payment_attempt.merchant_connector_id {\n Some(merchant_connector_id) => {\n #[cfg(feature = \"v1\")]\n {\n db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n platform.get_processor().get_account().get_id(),\n &merchant_connector_id,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(\n errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: merchant_connector_id.get_string_repr().to_string(),\n },\n )\n }\n #[cfg(feature = \"v2\")]\n {\n //get mca using id\n let _id = merchant_connector_id;\n let _ = key_store;\n let _ = key_manager_state;\n let _ = connector_name;\n todo!()\n }\n }\n None => {\n let profile_id = payment_intent\n .profile_id\n .as_ref()\n .get_required_value(\"profile_id\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"profile_id is not set in payment_intent\")?\n .clone();\n\n #[cfg(feature = \"v1\")]\n {\n db.find_merchant_connector_account_by_profile_id_connector_name(\n &profile_id,\n connector_name,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(\n errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: format!(\n \"profile_id {} and connector_name {connector_name}\",\n profile_id.get_string_repr()\n ),\n },\n )\n }\n #[cfg(feature = \"v2\")]\n {\n //get mca using id\n let _ = profile_id;\n todo!()\n }\n }\n }\n}\n#[cfg(feature = \"payouts\")]\npub async fn get_mca_from_payout_attempt(\n state: &SessionState,\n platform: &domain::Platform,\n payout_id_type: webhooks::PayoutIdType,\n connector_name: &str,\n) -> CustomResult {\n let db = &*state.store;\n let payout = match payout_id_type {\n webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db\n .find_payout_attempt_by_merchant_id_payout_attempt_id(\n platform.get_processor().get_account().get_id(),\n &payout_attempt_id,\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,\n webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db\n .find_payout_attempt_by_merchant_id_connector_payout_id(\n platform.get_processor().get_account().get_id(),\n &connector_payout_id,\n platform.get_processor().get_account().storage_scheme,\n )\n .await\n .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,\n };\n match payout.merchant_connector_id {\n Some(merchant_connector_id) => {\n #[cfg(feature = \"v1\")]\n {\n db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n platform.get_processor().get_account().get_id(),\n &merchant_connector_id,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(\n errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: merchant_connector_id.get_string_repr().to_string(),\n },\n )\n }\n #[cfg(feature = \"v2\")]\n {\n //get mca using id\n let _id = merchant_connector_id;\n let _ = platform.get_processor().get_key_store();\n let _ = connector_name;\n todo!()\n }\n }\n None => {\n #[cfg(feature = \"v1\")]\n {\n db.find_merchant_connector_account_by_profile_id_connector_name(\n &payout.profile_id,\n connector_name,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(\n errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: format!(\n \"profile_id {} and connector_name {}\",\n payout.profile_id.get_string_repr(),\n connector_name\n ),\n },\n )\n }\n #[cfg(feature = \"v2\")]\n {\n todo!()\n }\n }\n }\n}\n\n#[cfg(feature = \"v1\")]\npub async fn get_mca_from_object_reference_id(\n state: &SessionState,\n object_reference_id: webhooks::ObjectReferenceId,\n platform: &domain::Platform,\n connector_name: &str,\n) -> CustomResult {\n let db = &*state.store;\n\n #[cfg(feature = \"v1\")]\n let default_profile_id = platform\n .get_processor()\n .get_account()\n .default_profile\n .as_ref();\n\n #[cfg(feature = \"v2\")]\n let default_profile_id = Option::<&String>::None;\n\n match default_profile_id {\n Some(profile_id) => {\n #[cfg(feature = \"v1\")]\n {\n db.find_merchant_connector_account_by_profile_id_connector_name(\n profile_id,\n connector_name,\n platform.get_processor().get_key_store(),\n )\n .await\n .to_not_found_response(\n errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: format!(\n \"profile_id {} and connector_name {connector_name}\",\n profile_id.get_string_repr()\n ),\n },\n )\n }\n #[cfg(feature = \"v2\")]\n {\n let _db = db;\n let _profile_id = profile_id;\n todo!()\n }\n }\n _ => match object_reference_id {\n webhooks::ObjectReferenceId::PaymentId(payment_id_type) => {\n get_mca_from_payment_intent(\n state,\n platform,\n find_payment_intent_from_payment_id_type(state, payment_id_type, platform)\n .await?,\n connector_name,\n )\n .await\n }\n webhooks::ObjectReferenceId::RefundId(refund_id_type) => {\n get_mca_from_payment_intent(\n state,\n platform,\n find_payment_intent_from_refund_id_type(\n state,\n refund_id_type,\n platform,\n connector_name,\n )\n .await?,\n connector_name,\n )\n .await\n }\n webhooks::ObjectReferenceId::MandateId(mandate_id_type) => {\n get_mca_from_payment_intent(\n state,\n platform,\n find_payment_intent_from_mandate_id_type(state, mandate_id_type, platform)\n .await?,\n connector_name,\n )\n .await\n }\n webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => {\n find_mca_from_authentication_id_type(state, authentication_id_type, platform).await\n }\n webhooks::ObjectReferenceId::SubscriptionId(subscription_id_type) => {\n #[cfg(feature = \"v1\")]\n {\n let subscription_state = state.clone().into();\n let subscription_handler =\n SubscriptionHandler::new(&subscription_state, platform);\n let mut subscription_with_handler = subscription_handler\n .find_subscription(subscription_id_type)\n .await?;\n\n subscription_with_handler.get_mca(connector_name).await\n }\n #[cfg(feature = \"v2\")]\n {\n let _db = db;\n todo!()\n }\n }\n #[cfg(feature = \"payouts\")]\n webhooks::ObjectReferenceId::PayoutId(payout_id_type) => {\n get_mca_from_payout_attempt(state, platform, payout_id_type, connector_name).await\n }\n },\n }\n}\n\n// validate json format for the error\npub fn handle_json_response_deserialization_failure(\n res: types::Response,\n connector: &'static str,\n) -> CustomResult {\n metrics::RESPONSE_DESERIALIZATION_FAILURE\n .add(1, router_env::metric_attributes!((\"connector\", connector)));\n\n let response_data = String::from_utf8(res.response.to_vec())\n .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;\n\n // check for whether the response is in json format\n match serde_json::from_str::(&response_data) {\n // in case of unexpected response but in json format\n Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,\n // in case of unexpected response but in html or string format\n Err(error_msg) => {\n logger::error!(deserialization_error=?error_msg);\n logger::error!(\"UNEXPECTED RESPONSE FROM CONNECTOR: {}\", response_data);\n Ok(types::ErrorResponse {\n status_code: res.status_code,\n code: consts::NO_ERROR_CODE.to_string(),\n message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),\n reason: Some(response_data),\n attempt_status: None,\n connector_transaction_id: None,\n connector_response_reference_id: None,\n network_advice_code: None,\n network_decline_code: None,\n network_error_message: None,\n connector_metadata: None,\n })\n }\n }\n}\n\npub fn get_http_status_code_type(\n status_code: u16,\n) -> CustomResult {\n let status_code_type = match status_code {\n 100..=199 => \"1xx\",\n 200..=299 => \"2xx\",\n 300..=399 => \"3xx\",\n 400..=499 => \"4xx\",\n 500..=599 => \"5xx\",\n _ => Err(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Invalid http status code\")?,\n };\n Ok(status_code_type.to_string())\n}\n\n// Trims whitespace from a Secret string and returns None if empty\npub fn trim_secret_string(secret: masking::Secret) -> Option> {\n let trimmed = secret.expose().trim().to_string();\n (!trimmed.is_empty()).then(|| masking::Secret::new(trimmed))\n}\n\n// Trims whitespace from a regular string and returns None if empty\npub fn trim_string(value: String) -> Option {\n let trimmed = value.trim().to_string();\n (!trimmed.is_empty()).then_some(trimmed)\n}\n\npub fn add_connector_http_status_code_metrics(option_status_code: Option) {\n if let Some(status_code) = option_status_code {\n let status_code_type = get_http_status_code_type(status_code).ok();\n match status_code_type.as_deref() {\n Some(\"1xx\") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]),\n Some(\"2xx\") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]),\n Some(\"3xx\") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]),\n Some(\"4xx\") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]),\n Some(\"5xx\") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]),\n _ => logger::info!(\"Skip metrics as invalid http status code received from connector\"),\n };\n } else {\n logger::info!(\"Skip metrics as no http status code received from connector\")\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[async_trait::async_trait]\npub trait CustomerAddress {\n async fn get_address_update(\n &self,\n state: &SessionState,\n address_details: payments::AddressDetails,\n key: &[u8],\n storage_scheme: storage::enums::MerchantStorageScheme,\n merchant_id: id_type::MerchantId,\n ) -> CustomResult;\n\n async fn get_domain_address(\n &self,\n state: &SessionState,\n address_details: payments::AddressDetails,\n merchant_id: &id_type::MerchantId,\n customer_id: &id_type::CustomerId,\n key: &[u8],\n storage_scheme: storage::enums::MerchantStorageScheme,\n ) -> CustomResult;\n}\n\n#[cfg(feature = \"v1\")]\n#[async_trait::async_trait]\nimpl CustomerAddress for api_models::customers::CustomerRequest {\n async fn get_address_update(\n &self,\n state: &SessionState,\n address_details: payments::AddressDetails,\n key: &[u8],\n storage_scheme: storage::enums::MerchantStorageScheme,\n merchant_id: id_type::MerchantId,\n ) -> CustomResult {\n let encrypted_data = crypto_operation(\n &state.into(),\n type_name!(storage::Address),\n CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(\n domain::FromRequestEncryptableAddress {\n line1: address_details.line1.clone(),\n line2: address_details.line2.clone(),\n line3: address_details.line3.clone(),\n state: address_details.state.clone(),\n first_name: address_details.first_name.clone(),\n last_name: address_details.last_name.clone(),\n zip: address_details.zip.clone(),\n phone_number: self.phone.clone(),\n email: self\n .email\n .as_ref()\n .map(|a| a.clone().expose().switch_strategy()),\n origin_zip: address_details.origin_zip.clone(),\n },\n )),\n Identifier::Merchant(merchant_id.to_owned()),\n key,\n )\n .await\n .and_then(|val| val.try_into_batchoperation())?;\n\n let encryptable_address =\n domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)\n .change_context(common_utils::errors::CryptoError::EncodingFailed)?;\n\n Ok(storage::AddressUpdate::Update {\n city: address_details.city,\n country: address_details.country,\n line1: encryptable_address.line1,\n line2: encryptable_address.line2,\n line3: encryptable_address.line3,\n zip: encryptable_address.zip,\n state: encryptable_address.state,\n first_name: encryptable_address.first_name,\n last_name: encryptable_address.last_name,\n phone_number: encryptable_address.phone_number,\n country_code: self.phone_country_code.clone(),\n updated_by: storage_scheme.to_string(),\n email: encryptable_address.email.map(|email| {\n let encryptable: Encryptable> =\n Encryptable::new(\n email.clone().into_inner().switch_strategy(),\n email.into_encrypted(),\n );\n encryptable\n }),\n origin_zip: encryptable_address.origin_zip,\n })\n }\n\n async fn get_domain_address(\n &self,\n state: &SessionState,\n address_details: payments::AddressDetails,\n merchant_id: &id_type::MerchantId,\n customer_id: &id_type::CustomerId,\n key: &[u8],\n storage_scheme: storage::enums::MerchantStorageScheme,\n ) -> CustomResult {\n let encrypted_data = crypto_operation(\n &state.into(),\n type_name!(storage::Address),\n CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(\n domain::FromRequestEncryptableAddress {\n line1: address_details.line1.clone(),\n line2: address_details.line2.clone(),\n line3: address_details.line3.clone(),\n state: address_details.state.clone(),\n first_name: address_details.first_name.clone(),\n last_name: address_details.last_name.clone(),\n zip: address_details.zip.clone(),\n phone_number: self.phone.clone(),\n email: self\n .email\n .as_ref()\n .map(|a| a.clone().expose().switch_strategy()),\n origin_zip: address_details.origin_zip.clone(),\n },\n )),\n Identifier::Merchant(merchant_id.to_owned()),\n key,\n )\n .await\n .and_then(|val| val.try_into_batchoperation())?;\n\n let encryptable_address =\n domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)\n .change_context(common_utils::errors::CryptoError::EncodingFailed)?;\n\n let address = domain::Address {\n city: address_details.city,\n country: address_details.country,\n line1: encryptable_address.line1,\n line2: encryptable_address.line2,\n line3: encryptable_address.line3,\n zip: encryptable_address.zip,\n state: encryptable_address.state,\n first_name: encryptable_address.first_name,\n last_name: encryptable_address.last_name,\n phone_number: encryptable_address.phone_number,\n country_code: self.phone_country_code.clone(),\n merchant_id: merchant_id.to_owned(),\n address_id: generate_id(consts::ID_LENGTH, \"add\"),\n created_at: common_utils::date_time::now(),\n modified_at: common_utils::date_time::now(),\n updated_by: storage_scheme.to_string(),\n email: encryptable_address.email.map(|email| {\n let encryptable: Encryptable> =\n Encryptable::new(\n email.clone().into_inner().switch_strategy(),\n email.into_encrypted(),\n );\n encryptable\n }),\n origin_zip: encryptable_address.origin_zip,\n };\n\n Ok(domain::CustomerAddress {\n address,\n customer_id: customer_id.to_owned(),\n })\n }\n}\n\n#[cfg(feature = \"v1\")]\n#[async_trait::async_trait]\nimpl CustomerAddress for api_models::customers::CustomerUpdateRequest {\n async fn get_address_update(\n &self,\n state: &SessionState,\n address_details: payments::AddressDetails,\n key: &[u8],\n storage_scheme: storage::enums::MerchantStorageScheme,\n merchant_id: id_type::MerchantId,\n ) -> CustomResult {\n let encrypted_data = crypto_operation(\n &state.into(),\n type_name!(storage::Address),\n CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(\n domain::FromRequestEncryptableAddress {\n line1: address_details.line1.clone(),\n line2: address_details.line2.clone(),\n line3: address_details.line3.clone(),\n state: address_details.state.clone(),\n first_name: address_details.first_name.clone(),\n last_name: address_details.last_name.clone(),\n zip: address_details.zip.clone(),\n phone_number: self.phone.clone(),\n email: self\n .email\n .as_ref()\n .map(|a| a.clone().expose().switch_strategy()),\n origin_zip: address_details.origin_zip.clone(),\n },\n )),\n Identifier::Merchant(merchant_id.to_owned()),\n key,\n )\n .await\n .and_then(|val| val.try_into_batchoperation())?;\n\n let encryptable_address =\n domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)\n .change_context(common_utils::errors::CryptoError::EncodingFailed)?;\n Ok(storage::AddressUpdate::Update {\n city: address_details.city,\n country: address_details.country,\n line1: encryptable_address.line1,\n line2: encryptable_address.line2,\n line3: encryptable_address.line3,\n zip: encryptable_address.zip,\n state: encryptable_address.state,\n first_name: encryptable_address.first_name,\n last_name: encryptable_address.last_name,\n phone_number: encryptable_address.phone_number,\n country_code: self.phone_country_code.clone(),\n updated_by: storage_scheme.to_string(),\n email: encryptable_address.email.map(|email| {\n let encryptable: Encryptable> =\n Encryptable::new(\n email.clone().into_inner().switch_strategy(),\n email.into_encrypted(),\n );\n encryptable\n }),\n origin_zip: encryptable_address.origin_zip,\n })\n }\n\n async fn get_domain_address(\n &self,\n state: &SessionState,\n address_details: payments::AddressDetails,\n merchant_id: &id_type::MerchantId,\n customer_id: &id_type::CustomerId,\n key: &[u8],\n storage_scheme: storage::enums::MerchantStorageScheme,\n ) -> CustomResult {\n let encrypted_data = crypto_operation(\n &state.into(),\n type_name!(storage::Address),\n CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(\n domain::FromRequestEncryptableAddress {\n line1: address_details.line1.clone(),\n line2: address_details.line2.clone(),\n line3: address_details.line3.clone(),\n state: address_details.state.clone(),\n first_name: address_details.first_name.clone(),\n last_name: address_details.last_name.clone(),\n zip: address_details.zip.clone(),\n phone_number: self.phone.clone(),\n email: self\n .email\n .as_ref()\n .map(|a| a.clone().expose().switch_strategy()),\n origin_zip: address_details.origin_zip.clone(),\n },\n )),\n Identifier::Merchant(merchant_id.to_owned()),\n key,\n )\n .await\n .and_then(|val| val.try_into_batchoperation())?;\n\n let encryptable_address =\n domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)\n .change_context(common_utils::errors::CryptoError::EncodingFailed)?;\n let address = domain::Address {\n city: address_details.city,\n country: address_details.country,\n line1: encryptable_address.line1,\n line2: encryptable_address.line2,\n line3: encryptable_address.line3,\n zip: encryptable_address.zip,\n state: encryptable_address.state,\n first_name: encryptable_address.first_name,\n last_name: encryptable_address.last_name,\n phone_number: encryptable_address.phone_number,\n country_code: self.phone_country_code.clone(),\n merchant_id: merchant_id.to_owned(),\n address_id: generate_id(consts::ID_LENGTH, \"add\"),\n created_at: common_utils::date_time::now(),\n modified_at: common_utils::date_time::now(),\n updated_by: storage_scheme.to_string(),\n email: encryptable_address.email.map(|email| {\n let encryptable: Encryptable> =\n Encryptable::new(\n email.clone().into_inner().switch_strategy(),\n email.into_encrypted(),\n );\n encryptable\n }),\n origin_zip: encryptable_address.origin_zip,\n };\n\n Ok(domain::CustomerAddress {\n address,\n customer_id: customer_id.to_owned(),\n })\n }\n}\n\npub fn add_apple_pay_flow_metrics(\n apple_pay_flow: &Option,\n connector: Option,\n merchant_id: id_type::MerchantId,\n) {\n if let Some(flow) = apple_pay_flow {\n match flow {\n domain::ApplePayFlow::DecryptAtApplication(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW\n .add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n connector.to_owned().unwrap_or(\"null\".to_string()),\n ),\n (\"merchant_id\", merchant_id.clone()),\n ),\n ),\n domain::ApplePayFlow::SkipDecryption => metrics::APPLE_PAY_MANUAL_FLOW.add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n connector.to_owned().unwrap_or(\"null\".to_string()),\n ),\n (\"merchant_id\", merchant_id.clone()),\n ),\n ),\n }\n }\n}\n\npub fn add_apple_pay_payment_status_metrics(\n payment_attempt_status: enums::AttemptStatus,\n apple_pay_flow: Option,\n connector: Option,\n merchant_id: id_type::MerchantId,\n) {\n if payment_attempt_status == enums::AttemptStatus::Charged {\n if let Some(flow) = apple_pay_flow {\n match flow {\n domain::ApplePayFlow::DecryptAtApplication(_) => {\n metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n connector.to_owned().unwrap_or(\"null\".to_string()),\n ),\n (\"merchant_id\", merchant_id.clone()),\n ),\n )\n }\n domain::ApplePayFlow::SkipDecryption => {\n metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT.add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n connector.to_owned().unwrap_or(\"null\".to_string()),\n ),\n (\"merchant_id\", merchant_id.clone()),\n ),\n )\n }\n }\n }\n } else if payment_attempt_status == enums::AttemptStatus::Failure {\n if let Some(flow) = apple_pay_flow {\n match flow {\n domain::ApplePayFlow::DecryptAtApplication(_) => {\n metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n connector.to_owned().unwrap_or(\"null\".to_string()),\n ),\n (\"merchant_id\", merchant_id.clone()),\n ),\n )\n }\n domain::ApplePayFlow::SkipDecryption => {\n metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add(\n 1,\n router_env::metric_attributes!(\n (\n \"connector\",\n connector.to_owned().unwrap_or(\"null\".to_string()),\n ),\n (\"merchant_id\", merchant_id.clone()),\n ),\n )\n }\n }\n }\n }\n}\n\npub fn check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(\n metadata: Option,\n) -> bool {\n let external_three_ds_connector_metadata: Option = metadata\n .parse_value(\"ExternalThreeDSConnectorMetadata\")\n .map_err(|err| logger::warn!(parsing_error=?err,\"Error while parsing ExternalThreeDSConnectorMetadata\"))\n .ok();\n external_three_ds_connector_metadata\n .and_then(|metadata| metadata.pull_mechanism_for_external_3ds_enabled)\n .unwrap_or(true)\n}\n\n#[cfg(feature = \"v2\")]\n#[allow(clippy::too_many_arguments)]\npub async fn trigger_payments_webhook(\n processor: &domain::Processor,\n initiator: Option<&domain::Initiator>,\n business_profile: domain::Profile,\n payment_data: D,\n customer: Option,\n state: &SessionState,\n operation: Op,\n) -> RouterResult<()>\nwhere\n F: Send + Clone + Sync,\n Op: Debug,\n D: payments_core::OperationSessionGetters,\n{\n todo!()\n}\n\n#[cfg(feature = \"v1\")]\n#[allow(clippy::too_many_arguments)]\npub async fn trigger_payments_webhook(\n processor: &domain::Processor,\n initiator: Option<&domain::Initiator>,\n business_profile: domain::Profile,\n payment_data: D,\n state: &SessionState,\n operation: Op,\n) -> RouterResult<()>\nwhere\n F: Send + Clone + Sync,\n Op: Debug,\n D: payments_core::OperationSessionGetters,\n{\n let status = payment_data.get_payment_intent().status;\n\n // Trigger an outgoing webhook regardless of the current payment intent status if nothing is configured in the profile.\n let should_trigger_webhook = business_profile\n .get_configured_payment_webhook_statuses()\n .map(|statuses| statuses.contains(&status))\n .unwrap_or(true);\n\n if should_trigger_webhook {\n let captures = payment_data\n .get_multiple_capture_data()\n .map(|multiple_capture_data| {\n multiple_capture_data\n .get_all_captures()\n .into_iter()\n .cloned()\n .collect()\n });\n let payment_id = payment_data.get_payment_intent().get_id().to_owned();\n let payments_response = crate::core::payments::transformers::payments_to_payments_response(\n payment_data,\n captures,\n services::AuthFlow::Merchant,\n &state.base_url,\n &operation,\n &state.conf.connector_request_reference_id_config,\n None,\n None,\n None,\n processor,\n initiator,\n )?;\n\n let event_type = status.into();\n\n if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) =\n payments_response\n {\n let cloned_state = state.clone();\n // This spawns this futures in a background thread, the exception inside this future won't affect\n // the current thread and the lifecycle of spawn thread is not handled by runtime.\n // So when server shutdown won't wait for this thread's completion.\n\n if let Some(event_type) = event_type {\n let cloned_processor = processor.clone();\n tokio::spawn(\n async move {\n let primary_object_created_at = payments_response_json.created;\n Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(\n cloned_state,\n cloned_processor,\n business_profile,\n event_type,\n diesel_models::enums::EventClass::Payments,\n payment_id.get_string_repr().to_owned(),\n common_enums::EventObjectType::PaymentDetails,\n webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(\n payments_response_json,\n )),\n primary_object_created_at,\n ))\n .await\n }\n .in_current_span(),\n );\n } else {\n logger::warn!(\n \"Outgoing webhook not sent because of missing event type status mapping\"\n );\n }\n }\n }\n\n Ok(())\n}\n\ntype Handle = tokio::task::JoinHandle>;\n\npub async fn flatten_join_error(handle: Handle) -> RouterResult {\n match handle.await {\n Ok(Ok(t)) => Ok(t),\n Ok(Err(err)) => Err(err),\n Err(err) => Err(err)\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Join Error\"),\n }\n}\n\n#[cfg(feature = \"v1\")]\npub async fn trigger_refund_outgoing_webhook(\n state: &SessionState,\n platform: &domain::Platform,\n refund: &diesel_models::Refund,\n profile_id: id_type::ProfileId,\n) -> RouterResult<()> {\n let refund_status = refund.refund_status;\n\n let business_profile = state\n .store\n .find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n // Trigger an outgoing webhook regardless of the current refund status if nothing is configured in the profile.\n let should_trigger_webhook = business_profile\n .get_configured_refund_webhook_statuses()\n .map(|statuses| statuses.contains(&refund_status))\n .unwrap_or(true);\n\n if should_trigger_webhook {\n let event_type = refund_status.into();\n let refund_response: api_models::refunds::RefundResponse = refund.clone().foreign_into();\n let refund_id = refund_response.refund_id.clone();\n let cloned_state = state.clone();\n let primary_object_created_at = refund_response.created_at;\n if let Some(outgoing_event_type) = event_type {\n let processor = platform.get_processor().clone();\n tokio::spawn(\n async move {\n Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(\n cloned_state,\n processor,\n business_profile,\n outgoing_event_type,\n diesel_models::enums::EventClass::Refunds,\n refund_id.to_string(),\n common_enums::EventObjectType::RefundDetails,\n webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),\n primary_object_created_at,\n ))\n .await\n }\n .in_current_span(),\n );\n } else {\n logger::warn!(\"Outgoing webhook not sent because of missing event type status mapping\");\n };\n }\n Ok(())\n}\n\n#[cfg(feature = \"v2\")]\npub async fn trigger_refund_outgoing_webhook(\n state: &SessionState,\n merchant_account: &domain::MerchantAccount,\n refund: &diesel_models::Refund,\n profile_id: id_type::ProfileId,\n key_store: &domain::MerchantKeyStore,\n) -> RouterResult<()> {\n todo!()\n}\n\npub fn get_locale_from_header(headers: &actix_web::http::header::HeaderMap) -> String {\n get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)\n .ok()\n .flatten()\n .map(|val| val.to_string())\n .unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string())\n}\n\n#[cfg(all(feature = \"payouts\", feature = \"v1\"))]\npub async fn trigger_payouts_webhook(\n state: &SessionState,\n platform: &domain::Platform,\n payout_response: &api_models::payouts::PayoutCreateResponse,\n) -> RouterResult<()> {\n let profile_id = &payout_response.profile_id;\n let business_profile = state\n .store\n .find_business_profile_by_profile_id(platform.get_processor().get_key_store(), profile_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n let status = &payout_response.status;\n\n // Trigger an outgoing webhook regardless of the current payout status if nothing is configured in the profile.\n let should_trigger_webhook = business_profile\n .get_configured_payout_webhook_statuses()\n .map(|statuses| statuses.contains(status))\n .unwrap_or(true);\n\n if should_trigger_webhook {\n let event_type = (*status).into();\n if let Some(event_type) = event_type {\n let cloned_state = state.clone();\n let cloned_response = payout_response.clone();\n let processor = platform.get_processor().clone();\n\n // This spawns this futures in a background thread, the exception inside this future won't affect\n // the current thread and the lifecycle of spawn thread is not handled by runtime.\n // So when server shutdown won't wait for this thread's completion.\n tokio::spawn(\n async move {\n let primary_object_created_at = cloned_response.created;\n Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(\n cloned_state,\n processor,\n business_profile,\n event_type,\n diesel_models::enums::EventClass::Payouts,\n cloned_response.payout_id.get_string_repr().to_owned(),\n common_enums::EventObjectType::PayoutDetails,\n webhooks::OutgoingWebhookContent::PayoutDetails(Box::new(cloned_response)),\n primary_object_created_at,\n ))\n .await\n }\n .in_current_span(),\n );\n } else {\n logger::warn!(\"Outgoing webhook not sent because of missing event type status mapping\");\n }\n }\n Ok(())\n}\n\n#[cfg(all(feature = \"payouts\", feature = \"v2\"))]\npub async fn trigger_payouts_webhook(\n state: &SessionState,\n platform: &domain::Platform,\n payout_response: &api_models::payouts::PayoutCreateResponse,\n) -> RouterResult<()> {\n todo!()\n}\n\n#[cfg(feature = \"v1\")]\npub async fn trigger_subscriptions_outgoing_webhook(\n state: &SessionState,\n payment_response: subscription_types::PaymentResponseData,\n invoice: &hyperswitch_domain_models::invoice::Invoice,\n subscription: &hyperswitch_domain_models::subscription::Subscription,\n merchant_account: &domain::MerchantAccount,\n key_store: &domain::MerchantKeyStore,\n profile: &domain::Profile,\n) -> RouterResult<()> {\n if invoice.status != common_enums::enums::InvoiceStatus::InvoicePaid {\n logger::info!(\"Invoice not paid, skipping outgoing webhook trigger\");\n return Ok(());\n }\n let response = InvoiceSyncHandler::generate_response(subscription, invoice, &payment_response)\n .attach_printable(\"Subscriptions: Failed to generate response for outgoing webhook\")?;\n\n let platform = domain::Platform::new(\n merchant_account.clone(),\n key_store.clone(),\n merchant_account.clone(),\n key_store.clone(),\n None,\n );\n\n let cloned_state = state.clone();\n let cloned_profile = profile.clone();\n let invoice_id = invoice.id.get_string_repr().to_owned();\n let created_at = subscription.created_at;\n let processor = platform.get_processor().clone();\n\n tokio::spawn(async move {\n Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(\n cloned_state,\n processor,\n cloned_profile,\n common_enums::enums::EventType::InvoicePaid,\n common_enums::enums::EventClass::Subscriptions,\n invoice_id,\n common_enums::EventObjectType::SubscriptionDetails,\n webhooks::OutgoingWebhookContent::SubscriptionDetails(Box::new(response)),\n Some(created_at),\n ))\n .await\n });\n\n Ok(())\n}\n"} {"file_name": "crates__storage_impl__src__merchant_connector_account.rs", "text": "use async_bb8_diesel::AsyncConnection;\nuse common_utils::{encryption::Encryption, ext_traits::AsyncExt};\nuse diesel_models::merchant_connector_account as storage;\nuse error_stack::{report, ResultExt};\nuse hyperswitch_domain_models::{\n behaviour::{Conversion, ReverseConversion},\n merchant_connector_account::{self as domain, MerchantConnectorAccountInterface},\n merchant_key_store::MerchantKeyStore,\n};\nuse router_env::{instrument, tracing};\n\n#[cfg(feature = \"accounts_cache\")]\nuse crate::redis::cache;\nuse crate::{\n kv_router_store,\n utils::{pg_accounts_connection_read, pg_accounts_connection_write},\n CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,\n};\n\n#[async_trait::async_trait]\nimpl MerchantConnectorAccountInterface for kv_router_store::KVRouterStore {\n type Error = StorageError;\n #[cfg(feature = \"v1\")]\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_merchant_id_connector_label(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_label: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .find_merchant_connector_account_by_merchant_id_connector_label(\n merchant_id,\n connector_label,\n key_store,\n )\n .await\n }\n\n #[cfg(feature = \"v1\")]\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_profile_id_connector_name(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .find_merchant_connector_account_by_profile_id_connector_name(\n profile_id,\n connector_name,\n key_store,\n )\n .await\n }\n\n #[cfg(feature = \"v1\")]\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_merchant_id_connector_name(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, Self::Error> {\n self.router_store\n .find_merchant_connector_account_by_merchant_id_connector_name(\n merchant_id,\n connector_name,\n key_store,\n )\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v1\")]\n async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n merchant_id,\n merchant_connector_id,\n key_store,\n )\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v2\")]\n async fn find_merchant_connector_account_by_id(\n &self,\n id: &common_utils::id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .find_merchant_connector_account_by_id(id, key_store)\n .await\n }\n\n #[instrument(skip_all)]\n async fn insert_merchant_connector_account(\n &self,\n t: domain::MerchantConnectorAccount,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .insert_merchant_connector_account(t, key_store)\n .await\n }\n\n async fn list_enabled_connector_accounts_by_profile_id(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n key_store: &MerchantKeyStore,\n connector_type: common_enums::ConnectorType,\n ) -> CustomResult, Self::Error> {\n self.router_store\n .list_enabled_connector_accounts_by_profile_id(profile_id, key_store, connector_type)\n .await\n }\n\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n get_disabled: bool,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .find_merchant_connector_account_by_merchant_id_and_disabled_list(\n merchant_id,\n get_disabled,\n key_store,\n )\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(all(feature = \"olap\", feature = \"v2\"))]\n async fn list_connector_account_by_profile_id(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, Self::Error> {\n self.router_store\n .list_connector_account_by_profile_id(profile_id, key_store)\n .await\n }\n\n #[instrument(skip_all)]\n async fn update_multiple_merchant_connector_accounts(\n &self,\n merchant_connector_accounts: Vec<(\n domain::MerchantConnectorAccount,\n storage::MerchantConnectorAccountUpdateInternal,\n )>,\n ) -> CustomResult<(), Self::Error> {\n self.router_store\n .update_multiple_merchant_connector_accounts(merchant_connector_accounts)\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v1\")]\n async fn update_merchant_connector_account(\n &self,\n this: domain::MerchantConnectorAccount,\n merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .update_merchant_connector_account(this, merchant_connector_account, key_store)\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v2\")]\n async fn update_merchant_connector_account(\n &self,\n this: domain::MerchantConnectorAccount,\n merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n self.router_store\n .update_merchant_connector_account(this, merchant_connector_account, key_store)\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v1\")]\n async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,\n ) -> CustomResult {\n self.router_store\n .delete_merchant_connector_account_by_merchant_id_merchant_connector_id(\n merchant_id,\n merchant_connector_id,\n )\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v2\")]\n async fn delete_merchant_connector_account_by_id(\n &self,\n id: &common_utils::id_type::MerchantConnectorAccountId,\n ) -> CustomResult {\n self.router_store\n .delete_merchant_connector_account_by_id(id)\n .await\n }\n}\n\n#[async_trait::async_trait]\nimpl MerchantConnectorAccountInterface for RouterStore {\n type Error = StorageError;\n #[cfg(feature = \"v1\")]\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_merchant_id_connector_label(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_label: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let find_call = || async {\n let conn = pg_accounts_connection_read(self).await?;\n storage::MerchantConnectorAccount::find_by_merchant_id_connector(\n &conn,\n merchant_id,\n connector_label,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n };\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n find_call()\n .await?\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DeserializationFailed)\n }\n\n #[cfg(feature = \"accounts_cache\")]\n {\n cache::get_or_populate_in_memory(\n self,\n &format!(\"{}_{}\", merchant_id.get_string_repr(), connector_label),\n find_call,\n &cache::ACCOUNTS_CACHE,\n )\n .await\n .async_and_then(|item| async {\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n })\n .await\n }\n }\n\n #[cfg(feature = \"v1\")]\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_profile_id_connector_name(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let find_call = || async {\n let conn = pg_accounts_connection_read(self).await?;\n storage::MerchantConnectorAccount::find_by_profile_id_connector_name(\n &conn,\n profile_id,\n connector_name,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n };\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n find_call()\n .await?\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DeserializationFailed)\n }\n\n #[cfg(feature = \"accounts_cache\")]\n {\n cache::get_or_populate_in_memory(\n self,\n &format!(\"{}_{}\", profile_id.get_string_repr(), connector_name),\n find_call,\n &cache::ACCOUNTS_CACHE,\n )\n .await\n .async_and_then(|item| async {\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n })\n .await\n }\n }\n\n #[cfg(feature = \"v1\")]\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_merchant_id_connector_name(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, Self::Error> {\n let conn = pg_accounts_connection_read(self).await?;\n storage::MerchantConnectorAccount::find_by_merchant_id_connector_name(\n &conn,\n merchant_id,\n connector_name,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n .async_and_then(|items| async {\n let mut output = Vec::with_capacity(items.len());\n for item in items.into_iter() {\n output.push(\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)?,\n )\n }\n Ok(output)\n })\n .await\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v1\")]\n async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let find_call = || async {\n let conn = pg_accounts_connection_read(self).await?;\n storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(\n &conn,\n merchant_id,\n merchant_connector_id,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n };\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n find_call()\n .await?\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n }\n\n #[cfg(feature = \"accounts_cache\")]\n {\n cache::get_or_populate_in_memory(\n self,\n &format!(\n \"{}_{}\",\n merchant_id.get_string_repr(),\n merchant_connector_id.get_string_repr()\n ),\n find_call,\n &cache::ACCOUNTS_CACHE,\n )\n .await?\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n }\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v2\")]\n async fn find_merchant_connector_account_by_id(\n &self,\n id: &common_utils::id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let find_call = || async {\n let conn = pg_accounts_connection_read(self).await?;\n storage::MerchantConnectorAccount::find_by_id(&conn, id)\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n };\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n find_call()\n .await?\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone(),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n }\n\n #[cfg(feature = \"accounts_cache\")]\n {\n cache::get_or_populate_in_memory(\n self,\n id.get_string_repr(),\n find_call,\n &cache::ACCOUNTS_CACHE,\n )\n .await?\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n common_utils::types::keymanager::Identifier::Merchant(\n key_store.merchant_id.clone(),\n ),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n }\n }\n\n #[instrument(skip_all)]\n async fn insert_merchant_connector_account(\n &self,\n t: domain::MerchantConnectorAccount,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let conn = pg_accounts_connection_write(self).await?;\n t.construct_new()\n .await\n .change_context(Self::Error::EncryptionError)?\n .insert(&conn)\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n .async_and_then(|item| async {\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n })\n .await\n }\n\n async fn list_enabled_connector_accounts_by_profile_id(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n key_store: &MerchantKeyStore,\n connector_type: common_enums::ConnectorType,\n ) -> CustomResult, Self::Error> {\n let conn = pg_accounts_connection_read(self).await?;\n\n storage::MerchantConnectorAccount::list_enabled_by_profile_id(\n &conn,\n profile_id,\n connector_type,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n .async_and_then(|items| async {\n let mut output = Vec::with_capacity(items.len());\n for item in items.into_iter() {\n output.push(\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)?,\n )\n }\n Ok(output)\n })\n .await\n }\n\n #[instrument(skip_all)]\n async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n get_disabled: bool,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let conn = pg_accounts_connection_read(self).await?;\n let merchant_connector_account_vec =\n storage::MerchantConnectorAccount::find_by_merchant_id(\n &conn,\n merchant_id,\n get_disabled,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n .async_and_then(|items| async {\n let mut output = Vec::with_capacity(items.len());\n for item in items.into_iter() {\n output.push(\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)?,\n )\n }\n Ok(output)\n })\n .await?;\n Ok(domain::MerchantConnectorAccounts::new(\n merchant_connector_account_vec,\n ))\n }\n\n #[instrument(skip_all)]\n #[cfg(all(feature = \"olap\", feature = \"v2\"))]\n async fn list_connector_account_by_profile_id(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, Self::Error> {\n let conn = pg_accounts_connection_read(self).await?;\n storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id)\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n .async_and_then(|items| async {\n let mut output = Vec::with_capacity(items.len());\n for item in items.into_iter() {\n output.push(\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)?,\n )\n }\n Ok(output)\n })\n .await\n }\n\n #[instrument(skip_all)]\n async fn update_multiple_merchant_connector_accounts(\n &self,\n merchant_connector_accounts: Vec<(\n domain::MerchantConnectorAccount,\n storage::MerchantConnectorAccountUpdateInternal,\n )>,\n ) -> CustomResult<(), Self::Error> {\n let conn = pg_accounts_connection_write(self).await?;\n\n async fn update_call(\n connection: &diesel_models::PgPooledConn,\n (merchant_connector_account, mca_update): (\n domain::MerchantConnectorAccount,\n storage::MerchantConnectorAccountUpdateInternal,\n ),\n ) -> Result<(), error_stack::Report> {\n Conversion::convert(merchant_connector_account)\n .await\n .change_context(StorageError::EncryptionError)?\n .update(connection, mca_update)\n .await\n .map_err(|error| report!(StorageError::from(error)))?;\n Ok(())\n }\n\n conn.transaction_async(|connection_pool| async move {\n for (merchant_connector_account, update_merchant_connector_account) in\n merchant_connector_accounts\n {\n #[cfg(feature = \"v1\")]\n let _connector_name = merchant_connector_account.connector_name.clone();\n\n #[cfg(feature = \"v2\")]\n let _connector_name = merchant_connector_account.connector_name.to_string();\n\n let _profile_id = merchant_connector_account.profile_id.clone();\n\n let _merchant_id = merchant_connector_account.merchant_id.clone();\n let _merchant_connector_id = merchant_connector_account.get_id().clone();\n\n let update = update_call(\n &connection_pool,\n (\n merchant_connector_account,\n update_merchant_connector_account,\n ),\n );\n\n #[cfg(feature = \"accounts_cache\")]\n // Redact all caches as any of might be used because of backwards compatibility\n Box::pin(cache::publish_and_redact_multiple(\n self,\n [\n cache::CacheKind::Accounts(\n format!(\"{}_{}\", _profile_id.get_string_repr(), _connector_name).into(),\n ),\n cache::CacheKind::Accounts(\n format!(\n \"{}_{}\",\n _merchant_id.get_string_repr(),\n _merchant_connector_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::CGraph(\n format!(\n \"cgraph_{}_{}\",\n _merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n ],\n || update,\n ))\n .await\n .map_err(|error| {\n // Returning `DatabaseConnectionError` after logging the actual error because\n // -> it is not possible to get the underlying from `error_stack::Report`\n // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report`\n // because of Rust's orphan rules\n router_env::logger::error!(\n ?error,\n \"DB transaction for updating multiple merchant connector account failed\"\n );\n Self::Error::DatabaseConnectionError\n })?;\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n update.await.map_err(|error| {\n // Returning `DatabaseConnectionError` after logging the actual error because\n // -> it is not possible to get the underlying from `error_stack::Report`\n // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report`\n // because of Rust's orphan rules\n router_env::logger::error!(\n ?error,\n \"DB transaction for updating multiple merchant connector account failed\"\n );\n Self::Error::DatabaseConnectionError\n })?;\n }\n }\n Ok::<_, Self::Error>(())\n })\n .await?;\n Ok(())\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v1\")]\n async fn update_merchant_connector_account(\n &self,\n this: domain::MerchantConnectorAccount,\n merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let _connector_name = this.connector_name.clone();\n let _profile_id = this.profile_id.clone();\n\n let _merchant_id = this.merchant_id.clone();\n let _merchant_connector_id = this.merchant_connector_id.clone();\n\n let update_call = || async {\n let conn = pg_accounts_connection_write(self).await?;\n Conversion::convert(this)\n .await\n .change_context(Self::Error::EncryptionError)?\n .update(&conn, merchant_connector_account)\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n .async_and_then(|item| async {\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n })\n .await\n };\n\n #[cfg(feature = \"accounts_cache\")]\n {\n // Redact all caches as any of might be used because of backwards compatibility\n cache::publish_and_redact_multiple(\n self,\n [\n cache::CacheKind::Accounts(\n format!(\"{}_{}\", _profile_id.get_string_repr(), _connector_name).into(),\n ),\n cache::CacheKind::Accounts(\n format!(\n \"{}_{}\",\n _merchant_id.get_string_repr(),\n _merchant_connector_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::CGraph(\n format!(\n \"cgraph_{}_{}\",\n _merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::PmFiltersCGraph(\n format!(\n \"pm_filters_cgraph_{}_{}\",\n _merchant_id.get_string_repr(),\n _profile_id.get_string_repr(),\n )\n .into(),\n ),\n ],\n update_call,\n )\n .await\n }\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n update_call().await\n }\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v2\")]\n async fn update_merchant_connector_account(\n &self,\n this: domain::MerchantConnectorAccount,\n merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let _connector_name = this.connector_name;\n let _profile_id = this.profile_id.clone();\n\n let _merchant_id = this.merchant_id.clone();\n let _merchant_connector_id = this.get_id().clone();\n\n let update_call = || async {\n let conn = pg_accounts_connection_write(self).await?;\n Conversion::convert(this)\n .await\n .change_context(Self::Error::EncryptionError)?\n .update(&conn, merchant_connector_account)\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n .async_and_then(|item| async {\n item.convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n common_utils::types::keymanager::Identifier::Merchant(\n key_store.merchant_id.clone(),\n ),\n )\n .await\n .change_context(Self::Error::DecryptionError)\n })\n .await\n };\n\n #[cfg(feature = \"accounts_cache\")]\n {\n // Redact all caches as any of might be used because of backwards compatibility\n cache::publish_and_redact_multiple(\n self,\n [\n cache::CacheKind::Accounts(\n format!(\"{}_{}\", _profile_id.get_string_repr(), _connector_name).into(),\n ),\n cache::CacheKind::Accounts(\n _merchant_connector_id.get_string_repr().to_string().into(),\n ),\n cache::CacheKind::CGraph(\n format!(\n \"cgraph_{}_{}\",\n _merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::PmFiltersCGraph(\n format!(\n \"pm_filters_cgraph_{}_{}\",\n _merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n ],\n update_call,\n )\n .await\n }\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n update_call().await\n }\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v1\")]\n async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,\n ) -> CustomResult {\n let conn = pg_accounts_connection_write(self).await?;\n let delete_call = || async {\n storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id(\n &conn,\n merchant_id,\n merchant_connector_id,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n };\n\n #[cfg(feature = \"accounts_cache\")]\n {\n // We need to fetch mca here because the key that's saved in cache in\n // {merchant_id}_{connector_label}.\n // Used function from storage model to reuse the connection that made here instead of\n // creating new.\n\n let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(\n &conn,\n merchant_id,\n merchant_connector_id,\n )\n .await\n .map_err(|error| report!(Self::Error::from(error)))?;\n\n let _profile_id = mca\n .profile_id\n .ok_or(Self::Error::ValueNotFound(\"profile_id\".to_string()))?;\n\n cache::publish_and_redact_multiple(\n self,\n [\n cache::CacheKind::Accounts(\n format!(\n \"{}_{}\",\n mca.merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::CGraph(\n format!(\n \"cgraph_{}_{}\",\n mca.merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::PmFiltersCGraph(\n format!(\n \"pm_filters_cgraph_{}_{}\",\n mca.merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n ],\n delete_call,\n )\n .await\n }\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n delete_call().await\n }\n }\n\n #[instrument(skip_all)]\n #[cfg(feature = \"v2\")]\n async fn delete_merchant_connector_account_by_id(\n &self,\n id: &common_utils::id_type::MerchantConnectorAccountId,\n ) -> CustomResult {\n let conn = pg_accounts_connection_write(self).await?;\n let delete_call = || async {\n storage::MerchantConnectorAccount::delete_by_id(&conn, id)\n .await\n .map_err(|error| report!(Self::Error::from(error)))\n };\n\n #[cfg(feature = \"accounts_cache\")]\n {\n // We need to fetch mca here because the key that's saved in cache in\n // {merchant_id}_{connector_label}.\n // Used function from storage model to reuse the connection that made here instead of\n // creating new.\n\n let mca = storage::MerchantConnectorAccount::find_by_id(&conn, id)\n .await\n .map_err(|error| report!(Self::Error::from(error)))?;\n\n let _profile_id = mca.profile_id;\n\n cache::publish_and_redact_multiple(\n self,\n [\n cache::CacheKind::Accounts(\n format!(\n \"{}_{}\",\n mca.merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::CGraph(\n format!(\n \"cgraph_{}_{}\",\n mca.merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n cache::CacheKind::PmFiltersCGraph(\n format!(\n \"pm_filters_cgraph_{}_{}\",\n mca.merchant_id.get_string_repr(),\n _profile_id.get_string_repr()\n )\n .into(),\n ),\n ],\n delete_call,\n )\n .await\n }\n\n #[cfg(not(feature = \"accounts_cache\"))]\n {\n delete_call().await\n }\n }\n}\n\n#[async_trait::async_trait]\nimpl MerchantConnectorAccountInterface for MockDb {\n type Error = StorageError;\n async fn update_multiple_merchant_connector_accounts(\n &self,\n _merchant_connector_accounts: Vec<(\n domain::MerchantConnectorAccount,\n storage::MerchantConnectorAccountUpdateInternal,\n )>,\n ) -> CustomResult<(), StorageError> {\n // No need to implement this function for `MockDb` as this function will be removed after the\n // apple pay certificate migration\n Err(StorageError::MockDbError)?\n }\n #[cfg(feature = \"v1\")]\n async fn find_merchant_connector_account_by_merchant_id_connector_label(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n match self\n .merchant_connector_accounts\n .lock()\n .await\n .iter()\n .find(|account| {\n account.merchant_id == *merchant_id\n && account.connector_label == Some(connector.to_string())\n })\n .cloned()\n .async_map(|account| async {\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError)\n })\n .await\n {\n Some(result) => result,\n None => {\n return Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account\".to_string(),\n )\n .into())\n }\n }\n }\n\n async fn list_enabled_connector_accounts_by_profile_id(\n &self,\n _profile_id: &common_utils::id_type::ProfileId,\n _key_store: &MerchantKeyStore,\n _connector_type: common_enums::ConnectorType,\n ) -> CustomResult, StorageError> {\n Err(StorageError::MockDbError)?\n }\n\n #[cfg(feature = \"v1\")]\n async fn find_merchant_connector_account_by_merchant_id_connector_name(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, StorageError> {\n let accounts = self\n .merchant_connector_accounts\n .lock()\n .await\n .iter()\n .filter(|account| {\n account.merchant_id == *merchant_id && account.connector_name == connector_name\n })\n .cloned()\n .collect::>();\n let mut output = Vec::with_capacity(accounts.len());\n for account in accounts.into_iter() {\n output.push(\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError)?,\n )\n }\n Ok(output)\n }\n\n #[cfg(feature = \"v1\")]\n async fn find_merchant_connector_account_by_profile_id_connector_name(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n connector_name: &str,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let maybe_mca = self\n .merchant_connector_accounts\n .lock()\n .await\n .iter()\n .find(|account| {\n account.profile_id.eq(&Some(profile_id.to_owned()))\n && account.connector_name == connector_name\n })\n .cloned();\n\n match maybe_mca {\n Some(mca) => mca\n .to_owned()\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError),\n None => Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account\".to_string(),\n )\n .into()),\n }\n }\n\n #[cfg(feature = \"v1\")]\n async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n match self\n .merchant_connector_accounts\n .lock()\n .await\n .iter()\n .find(|account| {\n account.merchant_id == *merchant_id\n && account.merchant_connector_id == *merchant_connector_id\n })\n .cloned()\n .async_map(|account| async {\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError)\n })\n .await\n {\n Some(result) => result,\n None => {\n return Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account\".to_string(),\n )\n .into())\n }\n }\n }\n\n #[cfg(feature = \"v2\")]\n async fn find_merchant_connector_account_by_id(\n &self,\n id: &common_utils::id_type::MerchantConnectorAccountId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n match self\n .merchant_connector_accounts\n .lock()\n .await\n .iter()\n .find(|account| account.get_id() == *id)\n .cloned()\n .async_map(|account| async {\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n common_utils::types::keymanager::Identifier::Merchant(\n key_store.merchant_id.clone(),\n ),\n )\n .await\n .change_context(StorageError::DecryptionError)\n })\n .await\n {\n Some(result) => result,\n None => {\n return Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account\".to_string(),\n )\n .into())\n }\n }\n }\n\n #[cfg(feature = \"v1\")]\n async fn insert_merchant_connector_account(\n &self,\n t: domain::MerchantConnectorAccount,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let mut accounts = self.merchant_connector_accounts.lock().await;\n let account = storage::MerchantConnectorAccount {\n merchant_id: t.merchant_id,\n connector_name: t.connector_name,\n connector_account_details: t.connector_account_details.into(),\n test_mode: t.test_mode,\n disabled: t.disabled,\n merchant_connector_id: t.merchant_connector_id.clone(),\n id: Some(t.merchant_connector_id),\n payment_methods_enabled: t.payment_methods_enabled,\n metadata: t.metadata,\n frm_configs: None,\n frm_config: t.frm_configs,\n connector_type: t.connector_type,\n connector_label: t.connector_label,\n business_country: t.business_country,\n business_label: t.business_label,\n business_sub_label: t.business_sub_label,\n created_at: common_utils::date_time::now(),\n modified_at: common_utils::date_time::now(),\n connector_webhook_details: t.connector_webhook_details,\n profile_id: Some(t.profile_id),\n applepay_verified_domains: t.applepay_verified_domains,\n pm_auth_config: t.pm_auth_config,\n status: t.status,\n connector_wallets_details: t.connector_wallets_details.map(Encryption::from),\n additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),\n version: t.version,\n connector_webhook_registration_details: t.connector_webhook_registration_details,\n };\n accounts.push(account.clone());\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError)\n }\n\n #[cfg(feature = \"v2\")]\n async fn insert_merchant_connector_account(\n &self,\n t: domain::MerchantConnectorAccount,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let mut accounts = self.merchant_connector_accounts.lock().await;\n let account = storage::MerchantConnectorAccount {\n id: t.id,\n merchant_id: t.merchant_id,\n connector_name: t.connector_name,\n connector_account_details: t.connector_account_details.into(),\n disabled: t.disabled,\n payment_methods_enabled: t.payment_methods_enabled,\n metadata: t.metadata,\n frm_config: t.frm_configs,\n connector_type: t.connector_type,\n connector_label: t.connector_label,\n created_at: common_utils::date_time::now(),\n modified_at: common_utils::date_time::now(),\n connector_webhook_details: t.connector_webhook_details,\n profile_id: t.profile_id,\n applepay_verified_domains: t.applepay_verified_domains,\n pm_auth_config: t.pm_auth_config,\n status: t.status,\n connector_wallets_details: t.connector_wallets_details.map(Encryption::from),\n additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),\n version: t.version,\n feature_metadata: t.feature_metadata.map(From::from),\n connector_webhook_registration_details: None,\n };\n accounts.push(account.clone());\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n common_utils::types::keymanager::Identifier::Merchant(\n key_store.merchant_id.clone(),\n ),\n )\n .await\n .change_context(StorageError::DecryptionError)\n }\n\n async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n get_disabled: bool,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let accounts = self\n .merchant_connector_accounts\n .lock()\n .await\n .iter()\n .filter(|account: &&storage::MerchantConnectorAccount| {\n if get_disabled {\n account.merchant_id == *merchant_id\n } else {\n account.merchant_id == *merchant_id && account.disabled == Some(false)\n }\n })\n .cloned()\n .collect::>();\n\n let mut output = Vec::with_capacity(accounts.len());\n for account in accounts.into_iter() {\n output.push(\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError)?,\n )\n }\n Ok(domain::MerchantConnectorAccounts::new(output))\n }\n\n #[cfg(all(feature = \"olap\", feature = \"v2\"))]\n async fn list_connector_account_by_profile_id(\n &self,\n profile_id: &common_utils::id_type::ProfileId,\n key_store: &MerchantKeyStore,\n ) -> CustomResult, StorageError> {\n let accounts = self\n .merchant_connector_accounts\n .lock()\n .await\n .iter()\n .filter(|account: &&storage::MerchantConnectorAccount| {\n account.profile_id == *profile_id\n })\n .cloned()\n .collect::>();\n\n let mut output = Vec::with_capacity(accounts.len());\n for account in accounts.into_iter() {\n output.push(\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError)?,\n )\n }\n Ok(output)\n }\n\n #[cfg(feature = \"v1\")]\n async fn update_merchant_connector_account(\n &self,\n this: domain::MerchantConnectorAccount,\n merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let mca_update_res = self\n .merchant_connector_accounts\n .lock()\n .await\n .iter_mut()\n .find(|account| account.merchant_connector_id == this.merchant_connector_id)\n .map(|a| {\n let updated =\n merchant_connector_account.create_merchant_connector_account(a.clone());\n *a = updated.clone();\n updated\n })\n .async_map(|account| async {\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n key_store.merchant_id.clone().into(),\n )\n .await\n .change_context(StorageError::DecryptionError)\n })\n .await;\n\n match mca_update_res {\n Some(result) => result,\n None => {\n return Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account to update\".to_string(),\n )\n .into())\n }\n }\n }\n\n #[cfg(feature = \"v2\")]\n async fn update_merchant_connector_account(\n &self,\n this: domain::MerchantConnectorAccount,\n merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,\n key_store: &MerchantKeyStore,\n ) -> CustomResult {\n let mca_update_res = self\n .merchant_connector_accounts\n .lock()\n .await\n .iter_mut()\n .find(|account| account.get_id() == this.get_id())\n .map(|a| {\n let updated =\n merchant_connector_account.create_merchant_connector_account(a.clone());\n *a = updated.clone();\n updated\n })\n .async_map(|account| async {\n account\n .convert(\n self.get_keymanager_state()\n .attach_printable(\"Missing KeyManagerState\")?,\n key_store.key.get_inner(),\n common_utils::types::keymanager::Identifier::Merchant(\n key_store.merchant_id.clone(),\n ),\n )\n .await\n .change_context(StorageError::DecryptionError)\n })\n .await;\n\n match mca_update_res {\n Some(result) => result,\n None => {\n return Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account to update\".to_string(),\n )\n .into())\n }\n }\n }\n\n #[cfg(feature = \"v1\")]\n async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(\n &self,\n merchant_id: &common_utils::id_type::MerchantId,\n merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,\n ) -> CustomResult {\n let mut accounts = self.merchant_connector_accounts.lock().await;\n match accounts.iter().position(|account| {\n account.merchant_id == *merchant_id\n && account.merchant_connector_id == *merchant_connector_id\n }) {\n Some(index) => {\n accounts.remove(index);\n return Ok(true);\n }\n None => {\n return Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account to delete\".to_string(),\n )\n .into())\n }\n }\n }\n\n #[cfg(feature = \"v2\")]\n async fn delete_merchant_connector_account_by_id(\n &self,\n id: &common_utils::id_type::MerchantConnectorAccountId,\n ) -> CustomResult {\n let mut accounts = self.merchant_connector_accounts.lock().await;\n match accounts.iter().position(|account| account.get_id() == *id) {\n Some(index) => {\n accounts.remove(index);\n return Ok(true);\n }\n None => {\n return Err(StorageError::ValueNotFound(\n \"cannot find merchant connector account to delete\".to_string(),\n )\n .into())\n }\n }\n }\n}\n"}