hash
stringlengths
40
40
date
stringdate
2022-11-17 13:04:47
2025-03-21 17:04:41
author
stringclasses
141 values
commit_message
stringlengths
22
166
is_merge
bool
1 class
git_diff
stringlengths
238
9.63M
type
stringclasses
17 values
masked_commit_message
stringlengths
6
143
b1a6be5a7ccc3da690d4fd68c009110918eb28e3
2023-02-24 18:15:59
Arjun Karthik
refactor(connector-template): raise errors instead of using `todo!()` (#620)
false
diff --git a/connector-template/mod.rs b/connector-template/mod.rs index 926a4819738..ee78464f025 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -10,7 +10,7 @@ use crate::{ errors::{self, CustomResult}, payments, }, - headers, logger, services::{self, ConnectorIntegration}, + headers, services::{self, ConnectorIntegration}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, @@ -24,6 +24,18 @@ use transformers as {{project-name | downcase}}; #[derive(Debug, Clone)] pub struct {{project-name | downcase | pascal_case}}; +impl api::Payment for {{project-name | downcase | pascal_case}} {} +impl api::PaymentSession for {{project-name | downcase | pascal_case}} {} +impl api::ConnectorAccessToken for {{project-name | downcase | pascal_case}} {} +impl api::PreVerify for {{project-name | downcase | pascal_case}} {} +impl api::PaymentAuthorize for {{project-name | downcase | pascal_case}} {} +impl api::PaymentSync for {{project-name | downcase | pascal_case}} {} +impl api::PaymentCapture for {{project-name | downcase | pascal_case}} {} +impl api::PaymentVoid for {{project-name | downcase | pascal_case}} {} +impl api::Refund for {{project-name | downcase | pascal_case}} {} +impl api::RefundExecute for {{project-name | downcase | pascal_case}} {} +impl api::RefundSync for {{project-name | downcase | pascal_case}} {} + impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for {{project-name | downcase | pascal_case}} where Self: ConnectorIntegration<Flow, Request, Response>,{ @@ -32,7 +44,7 @@ where _req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::NotImplemented("build_headers method".to_string()).into()) } } @@ -42,8 +54,7 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} { } fn common_get_content_type(&self) -> &'static str { - todo!() - // Ex: "application/x-www-form-urlencoded" + mime::APPLICATION_JSON.essence_str() } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { @@ -58,9 +69,21 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} { } } -impl api::Payment for {{project-name | downcase | pascal_case}} {} +impl + ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for {{project-name | downcase | pascal_case}} +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for {{project-name | downcase | pascal_case}} +{ +} -impl api::PreVerify for {{project-name | downcase | pascal_case}} {} impl ConnectorIntegration< api::Verify, @@ -70,24 +93,69 @@ impl { } -impl api::PaymentVoid for {{project-name | downcase | pascal_case}} {} - impl ConnectorIntegration< - api::Void, - types::PaymentsCancelData, + api::Authorize, + types::PaymentsAuthorizeData, types::PaymentsResponseData, - > for {{project-name | downcase | pascal_case}} -{} + > for {{project-name | downcase | pascal_case}} { + fn get_headers(&self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { + self.build_headers(req, connectors) + } -impl api::ConnectorAccessToken for {{project-name | downcase | pascal_case}} {} + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for {{project-name | downcase | pascal_case}} -{ + fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body(&self, req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Option<String>,errors::ConnectorError> { + let {{project-name | downcase}}_req = + utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::convert_and_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some({{project-name | downcase}}_req)) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData,errors::ConnectorError> { + let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsResponse = res.response.parse_struct("{{project-name | downcase | pascal_case}} PaymentsAuthorizeResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> { + self.build_error_response(res) + } } -impl api::PaymentSync for {{project-name | downcase | pascal_case}} {} impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for {{project-name | downcase | pascal_case}} @@ -109,7 +177,7 @@ impl _req: &types::PaymentsSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( @@ -126,22 +194,14 @@ impl )) } - fn get_error_response( - &self, - res: Response, - ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - self.build_error_response(res) - } - fn handle_response( &self, data: &types::PaymentsSyncRouterData, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(payment_sync_response=?res); let response: {{project-name | downcase}}:: {{project-name | downcase | pascal_case}}PaymentsResponse = res .response - .parse_struct("{{project-name | downcase}} PaymentsResponse") + .parse_struct("{{project-name | downcase}} PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::RouterData::try_from(types::ResponseRouterData { response, @@ -150,10 +210,15 @@ impl }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } -} + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} -impl api::PaymentCapture for {{project-name | downcase | pascal_case}} {} impl ConnectorIntegration< api::Capture, @@ -178,14 +243,14 @@ impl _req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( @@ -211,9 +276,8 @@ impl ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: {{project-name | downcase }}::{{project-name | downcase | pascal_case}}PaymentsResponse = res .response - .parse_struct("{{project-name | downcase | pascal_case}} PaymentsResponse") + .parse_struct("{{project-name | downcase | pascal_case}} PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!({{project-name | downcase}}payments_create_response=?response); types::ResponseRouterData { response, data: data.clone(), @@ -231,87 +295,13 @@ impl } } -impl api::PaymentSession for {{project-name | downcase | pascal_case}} {} - impl ConnectorIntegration< - api::Session, - types::PaymentsSessionData, + api::Void, + types::PaymentsCancelData, types::PaymentsResponseData, > for {{project-name | downcase | pascal_case}} -{ - //TODO: implement sessions flow -} - -impl api::PaymentAuthorize for {{project-name | downcase | pascal_case}} {} - -impl - ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for {{project-name | downcase | pascal_case}} { - fn get_headers(&self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors,) -> CustomResult<Vec<(String, String)>,errors::ConnectorError> { - self.build_headers(req, connectors) - } - - fn get_content_type(&self) -> &'static str { - self.common_get_content_type() - } - - fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { - todo!() - } - - fn get_request_body(&self, req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Option<String>,errors::ConnectorError> { - let {{project-name | downcase}}_req = - utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::convert_and_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some({{project-name | downcase}}_req)) - } - - fn build_request( - &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) - .build(), - )) - } - - fn handle_response( - &self, - data: &types::PaymentsAuthorizeRouterData, - res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData,errors::ConnectorError> { - let response: {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsResponse = res.response.parse_struct("PaymentIntentResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - logger::debug!({{project-name | downcase}}payments_create_response=?response); - types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - } - .try_into() - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - fn get_error_response(&self, res: Response) -> CustomResult<ErrorResponse,errors::ConnectorError> { - self.build_error_response(res) - } -} - -impl api::Refund for {{project-name | downcase | pascal_case}} {} -impl api::RefundExecute for {{project-name | downcase | pascal_case}} {} -impl api::RefundSync for {{project-name | downcase | pascal_case}} {} +{} impl ConnectorIntegration< @@ -328,7 +318,7 @@ impl } fn get_url(&self, _req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body(&self, req: &types::RefundsRouterData<api::Execute>) -> CustomResult<Option<String>,errors::ConnectorError> { @@ -351,7 +341,6 @@ impl data: &types::RefundsRouterData<api::Execute>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>,errors::ConnectorError> { - logger::debug!(target: "router::connector::{{project-name | downcase}}", response=?res); let response: {{project-name| downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::RequestEncodingFailed)?; types::ResponseRouterData { response, @@ -378,7 +367,7 @@ impl } fn get_url(&self, _req: &types::RefundSyncRouterData,_connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> { - todo!() + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( @@ -401,8 +390,7 @@ impl data: &types::RefundSyncRouterData, res: Response, ) -> CustomResult<types::RefundSyncRouterData,errors::ConnectorError,> { - logger::debug!(target: "router::connector::{{project-name | downcase}}", response=?res); - let response: {{project-name | downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response: {{project-name | downcase}}::RefundResponse = res.response.parse_struct("{{project-name | downcase}} RefundSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::ResponseRouterData { response, data: data.clone(), diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index ab51bbff3cd..81ea5459f37 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -8,7 +8,7 @@ pub struct {{project-name | downcase | pascal_case}}PaymentsRequest {} impl TryFrom<&types::PaymentsAuthorizeRouterData> for {{project-name | downcase | pascal_case}}PaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: &types::PaymentsAuthorizeRouterData) -> Result<Self,Self::Error> { - todo!() + Err(errors::ConnectorError::NotImplemented("try_from PaymentsAuthorizeRouterData".to_string()).into()) } } @@ -21,7 +21,7 @@ pub struct {{project-name | downcase | pascal_case}}AuthType { impl TryFrom<&types::ConnectorAuthType> for {{project-name | downcase | pascal_case}}AuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - todo!() + Err(errors::ConnectorError::NotImplemented("try_from ConnectorAuthType".to_string()).into()) } } // PaymentsResponse @@ -53,14 +53,13 @@ pub struct {{project-name | downcase | pascal_case}}PaymentsResponse { } impl<F,T> TryFrom<types::ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { - type Error = error_stack::Report<errors::ParsingError>; + type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: types::ResponseRouterData<F, {{project-name | downcase | pascal_case}}PaymentsResponse, T, types::PaymentsResponseData>) -> Result<Self,Self::Error> { Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), @@ -76,9 +75,9 @@ impl<F,T> TryFrom<types::ResponseRouterData<F, {{project-name | downcase | pasca pub struct {{project-name | downcase | pascal_case}}RefundRequest {} impl<F> TryFrom<&types::RefundsRouterData<F>> for {{project-name | downcase | pascal_case}}RefundRequest { - type Error = error_stack::Report<errors::ParsingError>; + type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: &types::RefundsRouterData<F>) -> Result<Self,Self::Error> { - todo!() + Err(errors::ConnectorError::NotImplemented("try_from RefundsRouterData".to_string()).into()) } } @@ -112,19 +111,19 @@ pub struct RefundResponse { impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> for types::RefundsRouterData<api::Execute> { - type Error = error_stack::Report<errors::ParsingError>; + type Error = error_stack::Report<errors::ConnectorError>; fn try_from( _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { - todo!() + Err(errors::ConnectorError::NotImplemented("try_from RefundsResponseRouterData".to_string()).into()) } } impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> for types::RefundsRouterData<api::RSync> { - type Error = error_stack::Report<errors::ParsingError>; + type Error = error_stack::Report<errors::ConnectorError>; fn try_from(_item: types::RefundsResponseRouterData<api::RSync, RefundResponse>) -> Result<Self,Self::Error> { - todo!() + Err(errors::ConnectorError::NotImplemented("try_from RefundsResponseRouterData".to_string()).into()) } } diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index b4c4a82230c..e387e192c54 100644 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -26,6 +26,7 @@ sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/config.exam sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" loadtest/config/Development.toml sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" loadtest/config/Development.toml sed -i'' -e "s/Dummy,/Dummy,\n\t${pgc},/" crates/api_models/src/enums.rs +sed -i'' -e "s/pub enum RoutableConnectors {/pub enum RoutableConnectors {\n\t${pgc},/" crates/api_models/src/enums.rs # remove temporary files created in above step rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/Development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/Development.toml-e crates/api_models/src/enums.rs-e cd $conn/
refactor
raise errors instead of using `todo!()` (#620)
8b50997e56307507be101c562aa70d0a9b429137
2023-10-09 18:40:58
Kartikeya Hegde
feat(kv): add kv wrapper for executing kv tasks (#2384)
false
diff --git a/Cargo.lock b/Cargo.lock index 9e026101d1a..83dd8c4f1f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4792,6 +4792,7 @@ dependencies = [ "once_cell", "redis_interface", "ring", + "router_derive", "router_env", "serde", "serde_json", diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 939586116fc..c44b14fee21 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -232,6 +232,7 @@ impl super::RedisConnectionPool { &self, key: &str, values: V, + ttl: Option<u32>, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisMap> + Debug + Send + Sync, @@ -246,7 +247,9 @@ impl super::RedisConnectionPool { // setting expiry for the key output - .async_and_then(|_| self.set_expiry(key, self.config.default_hash_ttl.into())) + .async_and_then(|_| { + self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into()) + }) .await } @@ -256,6 +259,7 @@ impl super::RedisConnectionPool { key: &str, field: &str, value: V, + ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, @@ -270,7 +274,7 @@ impl super::RedisConnectionPool { output .async_and_then(|inner| async { - self.set_expiry(key, self.config.default_hash_ttl.into()) + self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into()) .await?; Ok(inner) }) @@ -283,6 +287,7 @@ impl super::RedisConnectionPool { key: &str, field: &str, value: V, + ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: serde::Serialize + Debug, @@ -290,7 +295,7 @@ impl super::RedisConnectionPool { let serialized = Encode::<V>::encode_to_vec(&value) .change_context(errors::RedisError::JsonSerializationFailed)?; - self.set_hash_field_if_not_exist(key, field, serialized.as_slice()) + self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl) .await } @@ -339,6 +344,7 @@ impl super::RedisConnectionPool { &self, kv: &[(&str, V)], field: &str, + ttl: Option<u32>, ) -> CustomResult<Vec<HsetnxReply>, errors::RedisError> where V: serde::Serialize + Debug, @@ -346,7 +352,7 @@ impl super::RedisConnectionPool { let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len()); for (key, val) in kv { hsetnx.push( - self.serialize_and_set_hash_field_if_not_exist(key, field, val) + self.serialize_and_set_hash_field_if_not_exist(key, field, val, ttl) .await?, ); } diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs index 4ea88638ac7..213fb799892 100644 --- a/crates/redis_interface/src/errors.rs +++ b/crates/redis_interface/src/errors.rs @@ -62,4 +62,6 @@ pub enum RedisError { PublishError, #[error("Failed while receiving message from publisher")] OnMessageError, + #[error("Got an unknown result from redis")] + UnknownResult, } diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 02db8b1754e..89e4e864d18 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -46,3 +46,6 @@ pub(crate) const QR_IMAGE_DATA_SOURCE_STRING: &str = "data:image/png;base64"; pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32"; pub(crate) const METRICS_HOST_TAG_NAME: &str = "host"; + +// TTL for KV setup +pub(crate) const KV_TTL: u32 = 300; diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 389229742f3..9356444c4e8 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -23,13 +23,17 @@ pub mod payouts; pub mod refund; pub mod reverse_lookup; +use std::fmt::Debug; + use data_models::payments::{ payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface, }; use masking::PeekInterface; +use redis_interface::errors::RedisError; +use serde::de; use storage_impl::{redis::kv_store::RedisConnInterface, MockDb}; -use crate::services::Store; +use crate::{consts, errors::CustomResult, services::Store}; #[derive(PartialEq, Eq)] pub enum StorageImpl { @@ -115,7 +119,7 @@ pub async fn get_and_deserialize_key<T>( db: &dyn StorageInterface, key: &str, type_name: &'static str, -) -> common_utils::errors::CustomResult<T, redis_interface::errors::RedisError> +) -> CustomResult<T, RedisError> where T: serde::de::DeserializeOwned, { @@ -128,4 +132,60 @@ where .change_context(redis_interface::errors::RedisError::JsonDeserializationFailed) } +pub enum KvOperation<'a, S: serde::Serialize + Debug> { + Set((&'a str, String)), + SetNx(&'a str, S), + Get(&'a str), + Scan(&'a str), +} + +#[derive(router_derive::TryGetEnumVariant)] +#[error(RedisError(UnknownResult))] +pub enum KvResult<T: de::DeserializeOwned> { + Get(T), + Set(()), + SetNx(redis_interface::HsetnxReply), + Scan(Vec<T>), +} + +pub async fn kv_wrapper<'a, T, S>( + store: &Store, + op: KvOperation<'a, S>, + key: impl AsRef<str>, +) -> CustomResult<KvResult<T>, RedisError> +where + T: de::DeserializeOwned, + S: serde::Serialize + Debug, +{ + let redis_conn = store.get_redis_conn()?; + + let key = key.as_ref(); + let type_name = std::any::type_name::<T>(); + + match op { + KvOperation::Set(value) => { + redis_conn + .set_hash_fields(key, value, Some(consts::KV_TTL)) + .await?; + Ok(KvResult::Set(())) + } + KvOperation::Get(field) => { + let result = redis_conn + .get_hash_field_and_deserialize(key, field, type_name) + .await?; + Ok(KvResult::Get(result)) + } + KvOperation::Scan(pattern) => { + let result: Vec<T> = redis_conn.hscan_and_deserialize(key, pattern, None).await?; + Ok(KvResult::Scan(result)) + } + KvOperation::SetNx(field, value) => { + let result = redis_conn + .serialize_and_set_hash_field_if_not_exist(key, field, value, Some(consts::KV_TTL)) + .await?; + Ok(KvResult::SetNx(result)) + } + } +} + dyn_clone::clone_trait_object!(StorageInterface); diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 904f9161335..781df79713f 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -244,7 +244,7 @@ mod storage { use error_stack::{IntoReport, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; - use storage_impl::redis::kv_store::{PartitionKey, RedisConnInterface}; + use storage_impl::redis::kv_store::{kv_wrapper, KvOperation, PartitionKey}; use super::AddressInterface; use crate::{ @@ -307,9 +307,15 @@ mod storage { let key = format!("{}_{}", merchant_id, payment_id); let field = format!("add_{}", address_id); db_utils::try_redis_get_else_try_database_get( - self.get_redis_conn() - .change_context(errors::StorageError::DatabaseConnectionError)? - .get_hash_field_and_deserialize(&key, &field, "Address"), + async { + kv_wrapper( + self, + KvOperation::<diesel_models::Address>::Get(&field), + key, + ) + .await? + .try_into_get() + }, database_call, ) .await @@ -394,11 +400,15 @@ mod storage { merchant_id: address_new.merchant_id.clone(), payment_id: address_new.payment_id.clone(), }; - match self - .get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_address) - .await + + match kv_wrapper::<diesel_models::Address, _, _>( + self, + KvOperation::SetNx(&field, &created_address), + &key, + ) + .await + .change_context(errors::StorageError::KVError)? + .try_into_setnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "address", diff --git a/crates/router/src/db/connector_response.rs b/crates/router/src/db/connector_response.rs index 331aea03d46..dd08f123c4d 100644 --- a/crates/router/src/db/connector_response.rs +++ b/crates/router/src/db/connector_response.rs @@ -100,7 +100,7 @@ mod storage { use error_stack::{IntoReport, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; - use storage_impl::redis::kv_store::{PartitionKey, RedisConnInterface}; + use storage_impl::redis::kv_store::{kv_wrapper, KvOperation, PartitionKey}; use super::Store; use crate::{ @@ -148,15 +148,15 @@ mod storage { authentication_data: connector_response.authentication_data.clone(), encoded_data: connector_response.encoded_data.clone(), }; - match self - .get_redis_conn() - .map_err(|er| error_stack::report!(errors::StorageError::RedisError(er)))? - .serialize_and_set_hash_field_if_not_exist( - &key, - &field, - &created_connector_resp, - ) - .await + + match kv_wrapper::<storage_type::ConnectorResponse, _, _>( + self, + KvOperation::SetNx(&field, &created_connector_resp), + &key, + ) + .await + .change_context(errors::StorageError::KVError)? + .try_into_setnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "address", @@ -213,17 +213,20 @@ mod storage { data_models::MerchantStorageScheme::RedisKv => { let key = format!("{merchant_id}_{payment_id}"); let field = format!("connector_resp_{merchant_id}_{payment_id}_{attempt_id}"); - let redis_conn = self - .get_redis_conn() - .map_err(|er| error_stack::report!(errors::StorageError::RedisError(er)))?; - let redis_fut = redis_conn.get_hash_field_and_deserialize( - &key, - &field, - "ConnectorResponse", - ); - - db_utils::try_redis_get_else_try_database_get(redis_fut, database_call).await + db_utils::try_redis_get_else_try_database_get( + async { + kv_wrapper( + self, + KvOperation::<diesel_models::Address>::Get(&field), + key, + ) + .await? + .try_into_get() + }, + database_call, + ) + .await } } } @@ -255,13 +258,16 @@ mod storage { &updated_connector_response.payment_id, &updated_connector_response.attempt_id ); - let updated_connector_response = self - .get_redis_conn() - .map_err(|er| error_stack::report!(errors::StorageError::RedisError(er)))? - .set_hash_fields(&key, (&field, &redis_value)) - .await - .map(|_| updated_connector_response) - .change_context(errors::StorageError::KVError)?; + + kv_wrapper::<(), _, _>( + self, + KvOperation::Set::<storage_type::ConnectorResponse>((&field, redis_value)), + &key, + ) + .await + .change_context(errors::StorageError::KVError)? + .try_into_set() + .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index 9fc3bc26fc1..9b7936ef2af 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -64,6 +64,7 @@ mod storage { .serialize_and_set_multiple_hash_field_if_not_exist( &[(&secret_key, &created_ek), (&id_key, &created_ek)], "ephkey", + None, ) .await { diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 35322805f33..ddc3bcf4165 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -270,7 +270,7 @@ mod storage { use common_utils::date_time; use error_stack::{IntoReport, ResultExt}; use redis_interface::HsetnxReply; - use storage_impl::redis::kv_store::RedisConnInterface; + use storage_impl::redis::kv_store::{kv_wrapper, KvOperation}; use super::RefundInterface; use crate::{ @@ -309,9 +309,15 @@ mod storage { let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .get_hash_field_and_deserialize(key, &lookup.sk_id, "Refund"), + async { + kv_wrapper( + self, + KvOperation::<storage_types::Refund>::Get(&lookup.sk_id), + key, + ) + .await? + .try_into_get() + }, database_call, ) .await @@ -365,11 +371,14 @@ mod storage { "pa_{}_ref_{}", &created_refund.attempt_id, &created_refund.refund_id ); - match self - .get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_refund) - .await + match kv_wrapper::<storage_types::Refund, _, _>( + self, + KvOperation::SetNx(&field, &created_refund), + &key, + ) + .await + .change_context(errors::StorageError::KVError)? + .try_into_setnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "refund", @@ -449,18 +458,19 @@ mod storage { connector_transaction_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { + let database_call = || async { + let conn = connection::pg_connection_read(self).await?; + storage_types::Refund::find_by_merchant_id_connector_transaction_id( + &conn, + merchant_id, + connector_transaction_id, + ) + .await + .map_err(Into::into) + .into_report() + }; match storage_scheme { - enums::MerchantStorageScheme::PostgresOnly => { - let conn = connection::pg_connection_read(self).await?; - storage_types::Refund::find_by_merchant_id_connector_transaction_id( - &conn, - merchant_id, - connector_transaction_id, - ) - .await - .map_err(Into::into) - .into_report() - } + enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!("{merchant_id}_{connector_transaction_id}"); let lookup = match self.get_lookup_by_lookup_id(&lookup_id).await { @@ -474,11 +484,19 @@ mod storage { let pattern = db_utils::generate_hscan_pattern_for_refund(&lookup.sk_id); - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .hscan_and_deserialize(key, &pattern, None) - .await - .change_context(errors::StorageError::KVError) + db_utils::try_redis_get_else_try_database_get( + async { + kv_wrapper( + self, + KvOperation::<storage_types::Refund>::Scan(&pattern), + key, + ) + .await? + .try_into_scan() + }, + database_call, + ) + .await } } } @@ -508,11 +526,15 @@ mod storage { ) .change_context(errors::StorageError::SerializationFailed)?; - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .set_hash_fields(&key, (field, redis_value)) - .await - .change_context(errors::StorageError::KVError)?; + kv_wrapper::<(), _, _>( + self, + KvOperation::Set::<storage_types::Refund>((&field, redis_value)), + &key, + ) + .await + .change_context(errors::StorageError::KVError)? + .try_into_set() + .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { @@ -557,9 +579,15 @@ mod storage { let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .get_hash_field_and_deserialize(key, &lookup.sk_id, "Refund"), + async { + kv_wrapper( + self, + KvOperation::<storage_types::Refund>::Get(&lookup.sk_id), + key, + ) + .await? + .try_into_get() + }, database_call, ) .await @@ -594,9 +622,15 @@ mod storage { let key = &lookup.pk_id; db_utils::try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .get_hash_field_and_deserialize(key, &lookup.sk_id, "Refund"), + async { + kv_wrapper( + self, + KvOperation::<storage_types::Refund>::Get(&lookup.sk_id), + key, + ) + .await? + .try_into_get() + }, database_call, ) .await @@ -610,25 +644,34 @@ mod storage { merchant_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { + let database_call = || async { + let conn = connection::pg_connection_read(self).await?; + storage_types::Refund::find_by_payment_id_merchant_id( + &conn, + payment_id, + merchant_id, + ) + .await + .map_err(Into::into) + .into_report() + }; match storage_scheme { - enums::MerchantStorageScheme::PostgresOnly => { - let conn = connection::pg_connection_read(self).await?; - storage_types::Refund::find_by_payment_id_merchant_id( - &conn, - payment_id, - merchant_id, - ) - .await - .map_err(Into::into) - .into_report() - } + enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let key = format!("{merchant_id}_{payment_id}"); - self.get_redis_conn() - .map_err(Into::<errors::StorageError>::into)? - .hscan_and_deserialize(&key, "pa_*_ref_*", None) - .await - .change_context(errors::StorageError::KVError) + db_utils::try_redis_get_else_try_database_get( + async { + kv_wrapper( + self, + KvOperation::<storage_types::Refund>::Scan("pa_*_ref_*"), + key, + ) + .await? + .try_into_scan() + }, + database_call, + ) + .await } } } diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 58d623682ac..0a7ec822e93 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -538,3 +538,41 @@ pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStrea .unwrap_or_else(|error| error.into_compile_error()) .into() } + +/// Generates the function to get the value out of enum variant +/// Usage +/// ``` +/// #[derive(TryGetEnumVariant)] +/// #[error(RedisError(UnknownResult))] +/// struct Result { +/// Set(String), +/// Get(i32) +/// } +/// ``` +/// +/// This will generate the function to get `String` and `i32` out of the variants +/// +/// ``` +/// impl Result { +/// fn try_into_get(&self)-> Result<i32, RedisError> { +/// match self { +/// Self::Get(a) => Ok(a), +/// _=>Err(RedisError::UnknownResult) +/// } +/// } +/// +/// fn try_into_set(&self)-> Result<String, RedisError> { +/// match self { +/// Self::Set(a) => Ok(a), +/// _=>Err(RedisError::UnknownResult) +/// } +/// } +/// } +#[proc_macro_derive(TryGetEnumVariant, attributes(error))] +pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as syn::DeriveInput); + + macros::try_get_enum::try_get_enum_variant(input) + .unwrap_or_else(|error| error.into_compile_error()) + .into() +} diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index 6f5de383304..86501f054a5 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -3,6 +3,7 @@ pub(crate) mod diesel; pub(crate) mod generate_schema; pub(crate) mod misc; pub(crate) mod operation; +pub(crate) mod try_get_enum; mod helpers; diff --git a/crates/router_derive/src/macros/try_get_enum.rs b/crates/router_derive/src/macros/try_get_enum.rs new file mode 100644 index 00000000000..3a534b080df --- /dev/null +++ b/crates/router_derive/src/macros/try_get_enum.rs @@ -0,0 +1,122 @@ +use proc_macro2::Span; +use syn::punctuated::Punctuated; + +/// Try and get the variants for an enum +pub fn try_get_enum_variant( + input: syn::DeriveInput, +) -> Result<proc_macro2::TokenStream, syn::Error> { + let name = &input.ident; + + let error_attr = input + .attrs + .iter() + .find(|attr| attr.path.is_ident("error")) + .ok_or(super::helpers::syn_error( + proc_macro2::Span::call_site(), + "Unable to find attribute error. Expected #[error(..)]", + ))?; + let (error_type, error_variant) = get_error_type_and_variant(error_attr)?; + let (impl_generics, generics, where_clause) = input.generics.split_for_impl(); + + let variants = get_enum_variants(&input.data)?; + + let try_into_fns = variants.iter().map(|variant| { + let variant_name = &variant.ident; + let variant_field = get_enum_variant_field(variant)?; + let variant_types = variant_field.iter().map(|f|f.ty.clone()); + + let try_into_fn = syn::Ident::new( + &format!("try_into_{}", variant_name.to_string().to_lowercase()), + proc_macro2::Span::call_site(), + ); + + Ok(quote::quote! { + pub fn #try_into_fn(self)->Result<(#(#variant_types),*),error_stack::Report<#error_type>> { + match self { + Self::#variant_name(inner) => Ok(inner), + _=> Err(error_stack::report!(#error_type::#error_variant)), + } + } + }) + }).collect::<Result<Vec<proc_macro2::TokenStream>,syn::Error>>()?; + + let expanded = quote::quote! { + impl #impl_generics #name #generics #where_clause { + #(#try_into_fns)* + } + }; + + Ok(expanded) +} + +/// Parses the attribute #[error(ErrorType(ErrorVariant))] +fn get_error_type_and_variant(attr: &syn::Attribute) -> syn::Result<(syn::Ident, syn::Path)> { + let meta = attr.parse_meta()?; + let metalist = match meta { + syn::Meta::List(list) => list, + _ => { + return Err(super::helpers::syn_error( + proc_macro2::Span::call_site(), + "Invalid attribute format #[error(ErrorType(ErrorVariant)]", + )) + } + }; + + for meta in metalist.nested.iter() { + if let syn::NestedMeta::Meta(syn::Meta::List(meta)) = meta { + let error_type = meta + .path + .get_ident() + .ok_or(super::helpers::syn_error( + proc_macro2::Span::call_site(), + "Invalid attribute format #[error(ErrorType(ErrorVariant))]", + )) + .cloned()?; + let error_variant = get_error_variant(meta)?; + return Ok((error_type, error_variant)); + }; + } + + Err(super::helpers::syn_error( + proc_macro2::Span::call_site(), + "Invalid attribute format #[error(ErrorType(ErrorVariant))]", + )) +} + +fn get_error_variant(meta: &syn::MetaList) -> syn::Result<syn::Path> { + for meta in meta.nested.iter() { + if let syn::NestedMeta::Meta(syn::Meta::Path(meta)) = meta { + return Ok(meta.clone()); + } + } + Err(super::helpers::syn_error( + proc_macro2::Span::call_site(), + "Invalid attribute format expected #[error(ErrorType(ErrorVariant))]", + )) +} + +/// Get variants from Enum +fn get_enum_variants(data: &syn::Data) -> syn::Result<Punctuated<syn::Variant, syn::token::Comma>> { + if let syn::Data::Enum(syn::DataEnum { variants, .. }) = data { + Ok(variants.clone()) + } else { + Err(super::helpers::non_enum_error()) + } +} + +/// Get Field from an enum variant +fn get_enum_variant_field( + variant: &syn::Variant, +) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> { + let field = match variant.fields.clone() { + syn::Fields::Unnamed(un) => un.unnamed, + syn::Fields::Named(n) => n.named, + syn::Fields::Unit => { + return Err(super::helpers::syn_error( + Span::call_site(), + "The enum is a unit variant it's not supported", + )) + } + }; + Ok(field) +} diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index 2226baa5c3b..e4c41c41b6f 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -24,6 +24,7 @@ masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } router_env = { version = "0.1.0", path = "../router_env" } external_services = { version = "0.1.0", path = "../external_services" } +router_derive = { version = "0.1.0", path = "../router_derive" } # Third party crates actix-web = "4.3.1" diff --git a/crates/storage_impl/src/consts.rs b/crates/storage_impl/src/consts.rs new file mode 100644 index 00000000000..04eab6176f9 --- /dev/null +++ b/crates/storage_impl/src/consts.rs @@ -0,0 +1,2 @@ +// TTL for KV setup +pub(crate) const KV_TTL: u32 = 300; diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 5f355e71348..bcc5c79257f 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -9,6 +9,7 @@ mod address; pub mod config; pub mod connection; mod connector_response; +mod consts; pub mod database; pub mod errors; mod lookup; diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index e4d3973918e..4911fdfdc32 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -28,7 +28,7 @@ use router_env::{instrument, tracing}; use crate::{ diesel_error_to_data_error, lookup::ReverseLookupInterface, - redis::kv_store::{PartitionKey, RedisConnInterface}, + redis::kv_store::{kv_wrapper, KvOperation, PartitionKey}, utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get}, DataModelExt, DatabaseStore, KVRouterStore, RouterStore, }; @@ -362,14 +362,15 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { }; let field = format!("pa_{}", created_attempt.attempt_id); - match self - .get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_attempt) - .await + + match kv_wrapper::<PaymentAttempt, _, _>( + self, + KvOperation::SetNx(&field, &created_attempt), + &key, + ) + .await + .change_context(errors::StorageError::KVError)? + .try_into_setnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "payment attempt", @@ -448,16 +449,16 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { .into_report() .change_context(errors::StorageError::KVError)?; let field = format!("pa_{}", updated_attempt.attempt_id); - let updated_attempt = self - .get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .set_hash_fields(&key, (&field, &redis_value)) - .await - .map(|_| updated_attempt) - .change_context(errors::StorageError::KVError)?; + + kv_wrapper::<(), _, _>( + self, + KvOperation::Set::<PaymentAttempt>((&field, redis_value)), + &key, + ) + .await + .change_context(errors::StorageError::KVError)? + .try_into_set() + .change_context(errors::StorageError::KVError)?; match ( old_connector_transaction_id, @@ -563,12 +564,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let key = &lookup.pk_id; try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"), + async { + kv_wrapper(self, KvOperation::<PaymentAttempt>::Get(&lookup.sk_id), key).await?.try_into_get() + }, || async {self.router_store.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(connector_transaction_id, payment_id, merchant_id, storage_scheme).await}, ) .await @@ -595,24 +593,25 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { MerchantStorageScheme::RedisKv => { let key = format!("{merchant_id}_{payment_id}"); let pattern = "pa_*"; - let redis_conn = self - .get_redis_conn() - .change_context(errors::StorageError::KVError)?; let redis_fut = async { - redis_conn - .hscan_and_deserialize::<PaymentAttempt>(&key, pattern, None) - .await - .and_then(|mut payment_attempts| { - payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at)); - payment_attempts - .iter() - .find(|&pa| pa.status == api_models::enums::AttemptStatus::Charged) - .cloned() - .ok_or(error_stack::report!( - redis_interface::errors::RedisError::NotFound - )) - }) + let kv_result = kv_wrapper::<PaymentAttempt, _, _>( + self, + KvOperation::<PaymentAttempt>::Scan(pattern), + key, + ) + .await? + .try_into_scan(); + kv_result.and_then(|mut payment_attempts| { + payment_attempts.sort_by(|a, b| b.modified_at.cmp(&a.modified_at)); + payment_attempts + .iter() + .find(|&pa| pa.status == api_models::enums::AttemptStatus::Charged) + .cloned() + .ok_or(error_stack::report!( + redis_interface::errors::RedisError::NotFound + )) + }) }; try_redis_get_else_try_database_get(redis_fut, database_call).await } @@ -641,12 +640,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let key = &lookup.pk_id; try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"), + async { + kv_wrapper(self, KvOperation::<PaymentAttempt>::Get(&lookup.sk_id), key) + .await? + .try_into_get() + }, || async { self.router_store .find_payment_attempt_by_merchant_id_connector_txn_id( @@ -685,12 +683,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let key = format!("{merchant_id}_{payment_id}"); let field = format!("pa_{attempt_id}"); try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .get_hash_field_and_deserialize(&key, &field, "PaymentAttempt"), + async { + kv_wrapper(self, KvOperation::<PaymentAttempt>::Get(&field), key) + .await? + .try_into_get() + }, || async { self.router_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( @@ -728,12 +725,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let lookup = self.get_lookup_by_lookup_id(&lookup_id).await?; let key = &lookup.pk_id; try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"), + async { + kv_wrapper(self, KvOperation::<PaymentAttempt>::Get(&lookup.sk_id), key) + .await? + .try_into_get() + }, || async { self.router_store .find_payment_attempt_by_attempt_id_merchant_id( @@ -771,12 +767,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let key = &lookup.pk_id; try_redis_get_else_try_database_get( - self.get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .get_hash_field_and_deserialize(key, &lookup.sk_id, "PaymentAttempt"), + async { + kv_wrapper(self, KvOperation::<PaymentAttempt>::Get(&lookup.sk_id), key) + .await? + .try_into_get() + }, || async { self.router_store .find_payment_attempt_by_preprocessing_id_merchant_id( @@ -811,13 +806,10 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { MerchantStorageScheme::RedisKv => { let key = format!("{merchant_id}_{payment_id}"); - self.get_redis_conn() - .map_err(|er| { - let error = format!("{}", er); - er.change_context(errors::StorageError::RedisError(error)) - })? - .hscan_and_deserialize(&key, "pa_*", None) + kv_wrapper(self, KvOperation::<PaymentAttempt>::Scan("pa_*"), key) .await + .change_context(errors::StorageError::KVError)? + .try_into_get() .change_context(errors::StorageError::KVError) } } diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 3b3359b4be3..beb9a84b306 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -35,7 +35,7 @@ use router_env::logger; use router_env::{instrument, tracing}; use crate::{ - redis::kv_store::{PartitionKey, RedisConnInterface}, + redis::kv_store::{kv_wrapper, KvOperation, PartitionKey}, utils::{pg_connection_read, pg_connection_write}, DataModelExt, DatabaseStore, KVRouterStore, }; @@ -93,11 +93,14 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { payment_confirm_source: new.payment_confirm_source, }; - match self - .get_redis_conn() - .change_context(StorageError::DatabaseConnectionError)? - .serialize_and_set_hash_field_if_not_exist(&key, &field, &created_intent) - .await + match kv_wrapper::<PaymentIntent, _, _>( + self, + KvOperation::SetNx(&field, &created_intent), + &key, + ) + .await + .change_context(StorageError::KVError)? + .try_into_setnx() { Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue { entity: "payment_intent", @@ -151,13 +154,15 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { Encode::<PaymentIntent>::encode_to_string_of_json(&updated_intent) .change_context(StorageError::SerializationFailed)?; - let updated_intent = self - .get_redis_conn() - .change_context(StorageError::DatabaseConnectionError)? - .set_hash_fields(&key, (&field, &redis_value)) - .await - .map(|_| updated_intent) - .change_context(StorageError::KVError)?; + kv_wrapper::<(), _, _>( + self, + KvOperation::<PaymentIntent>::Set((&field, redis_value)), + &key, + ) + .await + .change_context(StorageError::KVError)? + .try_into_set() + .change_context(StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { @@ -207,9 +212,15 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { let key = format!("{merchant_id}_{payment_id}"); let field = format!("pi_{payment_id}"); crate::utils::try_redis_get_else_try_database_get( - self.get_redis_conn() - .change_context(StorageError::DatabaseConnectionError)? - .get_hash_field_and_deserialize(&key, &field, "PaymentIntent"), + async { + kv_wrapper::<PaymentIntent, _, _>( + self, + KvOperation::<PaymentIntent>::Get(&field), + &key, + ) + .await? + .try_into_get() + }, database_call, ) .await diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 407cb838d86..4f909f0b359 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -1,4 +1,11 @@ -use std::sync::Arc; +use std::{fmt::Debug, sync::Arc}; + +use common_utils::errors::CustomResult; +use redis_interface::errors::RedisError; +use router_derive::TryGetEnumVariant; +use serde::de; + +use crate::{consts, KVRouterStore}; pub trait KvStorePartition { fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 { @@ -32,8 +39,62 @@ impl<'a> std::fmt::Display for PartitionKey<'a> { pub trait RedisConnInterface { fn get_redis_conn( &self, - ) -> error_stack::Result< - Arc<redis_interface::RedisConnectionPool>, - redis_interface::errors::RedisError, - >; + ) -> error_stack::Result<Arc<redis_interface::RedisConnectionPool>, RedisError>; +} + +pub enum KvOperation<'a, S: serde::Serialize + Debug> { + Set((&'a str, String)), + SetNx(&'a str, S), + Get(&'a str), + Scan(&'a str), +} + +#[derive(TryGetEnumVariant)] +#[error(RedisError(UnknownResult))] +pub enum KvResult<T: de::DeserializeOwned> { + Get(T), + Set(()), + SetNx(redis_interface::HsetnxReply), + Scan(Vec<T>), +} + +pub async fn kv_wrapper<'a, T, D, S>( + store: &KVRouterStore<D>, + op: KvOperation<'a, S>, + key: impl AsRef<str>, +) -> CustomResult<KvResult<T>, RedisError> +where + T: de::DeserializeOwned, + D: crate::database::store::DatabaseStore, + S: serde::Serialize + Debug, +{ + let redis_conn = store.get_redis_conn()?; + + let key = key.as_ref(); + let type_name = std::any::type_name::<T>(); + + match op { + KvOperation::Set(value) => { + redis_conn + .set_hash_fields(key, value, Some(consts::KV_TTL)) + .await?; + Ok(KvResult::Set(())) + } + KvOperation::Get(field) => { + let result = redis_conn + .get_hash_field_and_deserialize(key, field, type_name) + .await?; + Ok(KvResult::Get(result)) + } + KvOperation::Scan(pattern) => { + let result: Vec<T> = redis_conn.hscan_and_deserialize(key, pattern, None).await?; + Ok(KvResult::Scan(result)) + } + KvOperation::SetNx(field, value) => { + let result = redis_conn + .serialize_and_set_hash_field_if_not_exist(key, field, value, Some(consts::KV_TTL)) + .await?; + Ok(KvResult::SetNx(result)) + } + } }
feat
add kv wrapper for executing kv tasks (#2384)
93e7cd9bf040239fb1d3904854f1ef5250444bd2
2023-09-13 21:59:36
Pa1NarK
ci(postman): Change assertion status from cancelled to succeeded for checkout (#2155)
false
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario10-Multiple Captures/Cancel After Partial Capture/Payments - Cancel/event.test.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario10-Multiple Captures/Cancel After Partial Capture/Payments - Cancel/event.test.js index 2c8e84e3008..edeeb5a7b2b 100644 --- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario10-Multiple Captures/Cancel After Partial Capture/Payments - Cancel/event.test.js +++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario10-Multiple Captures/Cancel After Partial Capture/Payments - Cancel/event.test.js @@ -50,12 +50,19 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "connector error" for "error type" +// Response body should have value "cancellation succeeded" for "payment status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id/cancel - Content check if value for 'jsonData.status' matches 'cancelled'", + "[POST]::/payments/:id/cancel - Content check if value for 'jsonData.status' matches 'succeeded'", function () { - pm.expect(jsonData.status).to.eql("cancelled"); + pm.expect(jsonData.status).to.eql("succeeded"); }, ); } + +// Response body should have value "0" for "amount_capturable" +if (jsonData?.amount){ + pm.test("[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'", function() { + pm.expect(jsonData.amount_capturable).to.eql(0); + } ) +}
ci
Change assertion status from cancelled to succeeded for checkout (#2155)
6aac16e0c997d36e653f91be0f2a6660a3378dd5
2025-02-13 12:32:21
Kashif
fix(connectors): [fiuu] zero amount mandate flow for wallets (#7251)
false
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index ba00162281f..44f84bf475d 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -28,7 +28,7 @@ use strum::Display; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ - self, AddressDetailsData, ApplePay, PaymentsAuthorizeRequestData, + self, AddressData, AddressDetailsData, ApplePay, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, PaymentsCaptureRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RefundsRequestData, RouterData as _, }, @@ -1467,7 +1467,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { enums::AuthenticationType::NoThreeDs => None, }; let test_mode = get_test_mode(item.test_mode); - let req_address = item.get_billing_address()?.to_owned(); + let req_address = item.get_optional_billing(); let billing = NovalnetPaymentsRequestBilling { house_no: item.get_optional_billing_line1(), @@ -1477,10 +1477,12 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { country_code: item.get_optional_billing_country(), }; + let email = item.get_billing_email().or(item.request.get_email())?; + let customer = NovalnetPaymentsRequestCustomer { - first_name: req_address.get_optional_first_name(), - last_name: req_address.get_optional_last_name(), - email: item.request.get_email()?.clone(), + first_name: req_address.and_then(|addr| addr.get_optional_first_name()), + last_name: req_address.and_then(|addr| addr.get_optional_last_name()), + email, mobile: item.get_optional_billing_phone_number(), billing: Some(billing), // no_nc is used to indicate if minimal customer data is passed or not @@ -1504,7 +1506,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { card_expiry_month: req_card.card_exp_month.clone(), card_expiry_year: req_card.card_exp_year.clone(), card_cvc: req_card.card_cvc.clone(), - card_holder: req_address.get_full_name()?.clone(), + card_holder: item.get_billing_address()?.get_full_name()?, }); let transaction = NovalnetPaymentsRequestTransaction { diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index aec4d31072d..af8e89eeced 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1935,6 +1935,8 @@ pub trait AddressData { fn get_optional_full_name(&self) -> Option<Secret<String>>; fn get_email(&self) -> Result<Email, Error>; fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>; + fn get_optional_first_name(&self) -> Option<Secret<String>>; + fn get_optional_last_name(&self) -> Option<Secret<String>>; } impl AddressData for Address { @@ -1955,6 +1957,18 @@ impl AddressData for Address { .transpose()? .ok_or_else(missing_field_err("phone")) } + + fn get_optional_first_name(&self) -> Option<Secret<String>> { + self.address + .as_ref() + .and_then(|billing_address| billing_address.get_optional_first_name()) + } + + fn get_optional_last_name(&self) -> Option<Secret<String>> { + self.address + .as_ref() + .and_then(|billing_address| billing_address.get_optional_last_name()) + } } pub trait PaymentsPreProcessingRequestData { fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fix
[fiuu] zero amount mandate flow for wallets (#7251)
bc5497f03ab7fde585e7c57815f55cf7b4b8d475
2023-05-18 18:24:41
ThisIsMani
fix(router): add dummy connector url to proxy bypass (#1186)
false
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index c2340ab106d..0b25721f5e6 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -303,6 +303,10 @@ pub async fn send_request( ) -> CustomResult<reqwest::Response, errors::ApiClientError> { logger::debug!(method=?request.method, headers=?request.headers, payload=?request.payload, ?request); let url = &request.url; + #[cfg(feature = "dummy_connector")] + let should_bypass_proxy = url.starts_with(&state.conf.connectors.dummyconnector.base_url) + || client::proxy_bypass_urls(&state.conf.locker).contains(url); + #[cfg(not(feature = "dummy_connector"))] let should_bypass_proxy = client::proxy_bypass_urls(&state.conf.locker).contains(url); let client = client::create_client( &state.conf.proxy,
fix
add dummy connector url to proxy bypass (#1186)
3b7f59158d7cbf67a2f3a5c87a0f438bc50e9676
2023-02-07 15:26:28
Kartikeya Hegde
chore: use generic cache functions for config table (#506)
false
diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs index c543695d220..33f4141182f 100644 --- a/crates/router/src/db/cache.rs +++ b/crates/router/src/db/cache.rs @@ -15,10 +15,9 @@ where F: FnOnce() -> Fut + Send, Fut: futures::Future<Output = CustomResult<T, errors::StorageError>> + Send, { + let type_name = std::any::type_name::<T>(); let redis = &store.redis_conn; - let redis_val = redis - .get_and_deserialize_key::<T>(key, std::any::type_name::<T>()) - .await; + let redis_val = redis.get_and_deserialize_key::<T>(key, type_name).await; match redis_val { Err(err) => match err.current_context() { errors::RedisError::NotFound => { @@ -31,7 +30,7 @@ where } _ => Err(err .change_context(errors::StorageError::KVError) - .attach_printable("Error while fetching config")), + .attach_printable(format!("Error while fetching cache for {type_name}"))), }, Ok(val) => Ok(val), } diff --git a/crates/router/src/db/configs.rs b/crates/router/src/db/configs.rs index d4581467939..3a61609136d 100644 --- a/crates/router/src/db/configs.rs +++ b/crates/router/src/db/configs.rs @@ -1,6 +1,6 @@ -use error_stack::{IntoReport, ResultExt}; +use error_stack::IntoReport; -use super::{MockDb, Store}; +use super::{cache, MockDb, Store}; use crate::{ connection::pg_connection, core::errors::{self, CustomResult}, @@ -76,39 +76,18 @@ impl ConfigInterface for Store { key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { - let config = self.update_config_by_key(key, config_update).await?; - self.redis_conn - .delete_key(key) - .await - .change_context(errors::StorageError::KVError) - .attach_printable("Error while deleting the config key")?; - Ok(config) + cache::redact_cache(self, key, || async { + self.update_config_by_key(key, config_update).await + }) + .await } async fn find_config_by_key_cached( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { - let redis = &self.redis_conn; - let redis_val = redis - .get_and_deserialize_key::<storage::Config>(key, "Config") - .await; - Ok(match redis_val { - Err(err) => match err.current_context() { - errors::RedisError::NotFound => { - let config = self.find_config_by_key(key).await?; - redis - .serialize_and_set_key(&config.key, &config) - .await - .change_context(errors::StorageError::KVError)?; - config - } - _ => Err(err - .change_context(errors::StorageError::KVError) - .attach_printable("Error while fetching config"))?, - }, - Ok(val) => val, - }) + cache::get_or_populate_cache(self, key, || async { self.find_config_by_key(key).await }) + .await } async fn delete_config_by_key(&self, key: &str) -> CustomResult<bool, errors::StorageError> {
chore
use generic cache functions for config table (#506)
031c073e793a174155327ab19302f06cf5d3c8cc
2022-12-10 15:05:17
Nishant Joshi
feat(storage): make amount as an enum (#98)
false
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 002f3a256a7..28c9eb98da7 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -136,7 +136,7 @@ pub(crate) struct StripePaymentIntentRequest { impl From<StripePaymentIntentRequest> for PaymentsRequest { fn from(item: StripePaymentIntentRequest) -> Self { PaymentsRequest { - amount: item.amount, + amount: item.amount.map(|amount| amount.into()), currency: item.currency.as_ref().map(|c| c.to_uppercase()), capture_method: item.capture_method, amount_to_capture: item.amount_capturable, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 61896f59f45..34c6e7291e8 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -431,7 +431,7 @@ where pub payment_intent: storage::PaymentIntent, pub payment_attempt: storage::PaymentAttempt, pub connector_response: storage::ConnectorResponse, - pub amount: i32, + pub amount: api::Amount, pub currency: enums::Currency, pub mandate_id: Option<String>, pub setup_mandate: Option<api::MandateData>, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 97d802b2e16..8274d5df995 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -210,27 +210,37 @@ pub fn validate_merchant_id( #[instrument(skip_all)] pub fn validate_request_amount_and_amount_to_capture( - op_amount: Option<i32>, + op_amount: Option<api::Amount>, op_amount_to_capture: Option<i32>, ) -> CustomResult<(), errors::ApiErrorResponse> { - // If both amount and amount to capture is present - // then amount to be capture should be less than or equal to request amount - - let is_capture_amount_valid = op_amount - .and_then(|amount| { - op_amount_to_capture.map(|amount_to_capture| amount_to_capture.le(&amount)) - }) - .unwrap_or(true); - - utils::when( - !is_capture_amount_valid, - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: format!( - "amount_to_capture is greater than amount capture_amount: {:?} request_amount: {:?}", - op_amount_to_capture, op_amount - ) - })), - ) + match (op_amount, op_amount_to_capture) { + (None, _) => Ok(()), + (Some(_amount), None) => Ok(()), + (Some(amount), Some(amount_to_capture)) => { + match amount { + api::Amount::Value(amount_inner) => { + // If both amount and amount to capture is present + // then amount to be capture should be less than or equal to request amount + utils::when( + !amount_to_capture.le(&amount_inner), + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: format!( + "amount_to_capture is greater than amount capture_amount: {:?} request_amount: {:?}", + amount_to_capture, amount + ) + })), + ) + } + api::Amount::Zero => { + // If the amount is Null but still amount_to_capture is passed this is invalid and + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: "amount_to_capture should not exist for when amount = 0" + .to_string() + })) + } + } + } + } } pub fn validate_mandate( diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index c121c2476f1..ee0e000ae69 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -77,7 +77,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) })?; let currency = payment_attempt.currency.get_required_value("currency")?; - let amount = payment_attempt.amount; + let amount = payment_attempt.amount.into(); payment_attempt.cancellation_reason = request.cancellation_reason.clone(); diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index c06784c318b..70408657ec7 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -85,7 +85,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu currency = payment_attempt.currency.get_required_value("currency")?; - amount = payment_attempt.amount; + amount = payment_attempt.amount.into(); let connector_response = db .find_connector_response_by_payment_id_merchant_id_txn_id( diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9e8801cd4f7..1b0439267b9 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -93,7 +93,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_attempt.payment_method = payment_method_type.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info; currency = payment_attempt.currency.get_required_value("currency")?; - amount = payment_attempt.amount; + amount = payment_attempt.amount.into(); connector_response = db .find_connector_response_by_payment_id_merchant_id_txn_id( diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index c7f2e147d29..2046ad32879 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -284,10 +284,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id) .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let amount = request.amount.get_required_value("amount")?; - helpers::validate_request_amount_and_amount_to_capture( - Some(amount), + request.amount, request.amount_to_capture, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { @@ -295,9 +293,10 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate expected_format: "amount_to_capture lesser than amount".to_string(), })?; - let mandate_type = helpers::validate_mandate(request)?; let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?; + let mandate_type = helpers::validate_mandate(request)?; + Ok(( Box::new(self), operations::ValidateResult { @@ -316,7 +315,7 @@ impl PaymentCreate { payment_id: &str, merchant_id: &str, connector: types::Connector, - money: (i32, enums::Currency), + money: (api::Amount, enums::Currency), payment_method: Option<enums::PaymentMethodType>, request: &api::PaymentsRequest, browser_info: Option<serde_json::Value>, @@ -330,7 +329,7 @@ impl PaymentCreate { merchant_id: merchant_id.to_string(), txn_id: Uuid::new_v4().to_string(), status, - amount, + amount: amount.into(), currency, connector: connector.to_string(), payment_method, @@ -351,7 +350,7 @@ impl PaymentCreate { payment_id: &str, merchant_id: &str, connector_id: &str, - money: (i32, enums::Currency), + money: (api::Amount, enums::Currency), request: &api::PaymentsRequest, shipping_address_id: Option<String>, billing_address_id: Option<String>, @@ -366,7 +365,7 @@ impl PaymentCreate { payment_id: payment_id.to_string(), merchant_id: merchant_id.to_string(), status, - amount, + amount: amount.into(), currency, connector_id: Some(connector_id.to_string()), description: request.description.clone(), @@ -406,7 +405,7 @@ impl PaymentCreate { #[instrument(skip_all)] pub fn payments_create_request_validation( req: &api::PaymentsRequest, -) -> RouterResult<(i32, enums::Currency)> { +) -> RouterResult<(api::Amount, enums::Currency)> { let currency: enums::Currency = req .currency .as_ref() diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index b8593c467d9..12e05fc47a1 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -135,7 +135,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym payment_attempt, /// currency and amount are irrelevant in this scenario currency: storage_enums::Currency::default(), - amount: 0, + amount: api::Amount::Zero, mandate_id: None, setup_mandate: request.mandate_data.clone(), token: request.payment_token.clone(), diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index f73412880ca..fa9a0500dff 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -72,7 +72,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> payment_attempt.payment_method = Some(enums::PaymentMethodType::Wallet); - let amount = payment_intent.amount; + let amount = payment_intent.amount.into(); if let Some(ref payment_intent_client_secret) = payment_intent.client_secret { if request.client_secret.ne(payment_intent_client_secret) { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index b44212c949c..599b664d13e 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -68,7 +68,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f })?; currency = payment_attempt.currency.get_required_value("currency")?; - amount = payment_attempt.amount; + amount = payment_attempt.amount.into(); let shipping_address = helpers::get_address_for_payment_request( db, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 84a6189bdaa..66712d64bd8 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -167,7 +167,7 @@ async fn get_tracker_for_sync< connector_response.encoded_data = request.param.clone(); currency = payment_attempt.currency.get_required_value("currency")?; - amount = payment_attempt.amount; + amount = payment_attempt.amount.into(); let shipping_address = helpers::get_address_by_id(db, payment_intent.shipping_address_id.clone()).await?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 6c3b52fd01d..6e600214dd1 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -42,12 +42,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa PaymentData<F>, Option<CustomerDetails>, )> { - let (mut payment_intent, mut payment_attempt, currency, amount): ( - _, - _, - enums::Currency, - _, - ); + let (mut payment_intent, mut payment_attempt, currency): (_, _, enums::Currency); let payment_id = payment_id .get_payment_intent_id() @@ -80,7 +75,9 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_attempt.payment_method = payment_method_type.or(payment_attempt.payment_method); - amount = request.amount.unwrap_or(payment_attempt.amount); + let amount = request + .amount + .unwrap_or_else(|| payment_attempt.amount.into()); payment_intent = db .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme) @@ -202,7 +199,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .update_payment_attempt( payment_data.payment_attempt, storage::PaymentAttemptUpdate::Update { - amount: payment_data.amount, + amount: payment_data.amount.into(), currency: payment_data.currency, status: get_attempt_status(), authentication_type: None, @@ -237,7 +234,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen .update_payment_intent( payment_data.payment_intent.clone(), storage::PaymentIntentUpdate::Update { - amount: payment_data.amount, + amount: payment_data.amount.into(), currency: payment_data.currency, status: get_status(), customer_id, @@ -285,6 +282,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; + helpers::validate_request_amount_and_amount_to_capture( request.amount, request.amount_to_capture, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 509dcca02a4..cbf24ff7581 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -361,7 +361,7 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsAuthorizeData { confirm: payment_data.payment_attempt.confirm, statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix, capture_method: payment_data.payment_attempt.capture_method, - amount: payment_data.amount, + amount: payment_data.amount.into(), currency: payment_data.currency, browser_info, }) diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 54b91c1d880..0eaaaa8e676 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -16,13 +16,13 @@ use crate::{ services::api, types::api::{ - enums as api_enums, + self as api_types, enums as api_enums, payments::{ PaymentIdType, PaymentListConstraints, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsRequest, PaymentsRetrieveRequest, }, Authorize, Capture, PSync, PaymentRetrieveBody, PaymentsResponse, PaymentsStartRequest, - Verify, VerifyResponse, Void, + Verify, Void, }, // FIXME imports }; @@ -38,46 +38,43 @@ pub async fn payments_create( if let Some(api_enums::CaptureMethod::Scheduled) = payload.capture_method { return http_not_implemented(); }; - match payload.amount { - Some(0) | None => { - api::server_wrap( - &state, - &req, - payload.into(), - |state, merchant_account, req| { - payments::payments_core::<Verify, VerifyResponse, _, _, _>( - state, - merchant_account, - payments::PaymentMethodValidate, - req, - api::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - ) - }, - api::MerchantAuthentication::ApiKey, - ) - .await - } - _ => { - api::server_wrap( - &state, - &req, - payload, - |state, merchant_account, req| { - payments::payments_core::<Authorize, PaymentsResponse, _, _, _>( - state, - merchant_account, - payments::PaymentCreate, - req, - api::AuthFlow::Merchant, - payments::CallConnectorAction::Trigger, - ) - }, - api::MerchantAuthentication::ApiKey, - ) - .await - } - } + + api::server_wrap( + &state, + &req, + payload, + |state, merchant_account, req| { + // TODO: Change for making it possible for the flow to be inferred internally or through validation layer + async { + match req.amount.as_ref() { + Some(api_types::Amount::Value(_)) | None => { + payments::payments_core::<Authorize, PaymentsResponse, _, _, _>( + state, + merchant_account, + payments::PaymentCreate, + req, + api::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + ) + .await + } + Some(api_types::Amount::Zero) => { + payments::payments_core::<Verify, PaymentsResponse, _, _, _>( + state, + merchant_account, + payments::PaymentCreate, + req, + api::AuthFlow::Merchant, + payments::CallConnectorAction::Trigger, + ) + .await + } + } + } + }, + api::MerchantAuthentication::ApiKey, + ) + .await } #[instrument(skip(state), fields(flow = ?Flow::PaymentsStart))] diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index cd50fa14eb5..78432daefb2 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -27,7 +27,8 @@ pub struct PaymentsRequest { )] pub payment_id: Option<PaymentIdType>, pub merchant_id: Option<String>, - pub amount: Option<i32>, + #[serde(default, deserialize_with = "custom_serde::amount::deserialize_option")] + pub amount: Option<Amount>, pub currency: Option<String>, pub capture_method: Option<api_enums::CaptureMethod>, pub amount_to_capture: Option<i32>, @@ -68,6 +69,30 @@ impl PaymentsRequest { } } +#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] +pub enum Amount { + Value(i32), + #[default] + Zero, +} + +impl From<Amount> for i32 { + fn from(amount: Amount) -> Self { + match amount { + Amount::Value(v) => v, + Amount::Zero => 0, + } + } +} +impl From<i32> for Amount { + fn from(val: i32) -> Self { + match val { + 0 => Amount::Zero, + amount => Amount::Value(amount), + } + } +} + #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { @@ -788,7 +813,7 @@ mod payments_test { #[allow(dead_code)] fn payments_request() -> PaymentsRequest { PaymentsRequest { - amount: Some(200), + amount: Some(Amount::Value(200)), payment_method_data: Some(PaymentMethod::Card(card())), ..PaymentsRequest::default() } diff --git a/crates/router/src/utils/custom_serde.rs b/crates/router/src/utils/custom_serde.rs index c5e364ac2e0..57bbd3eeb43 100644 --- a/crates/router/src/utils/custom_serde.rs +++ b/crates/router/src/utils/custom_serde.rs @@ -72,3 +72,69 @@ pub(crate) mod payment_id_type { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } + +pub(crate) mod amount { + use serde::de; + + use crate::types::api; + struct AmountVisitor; + struct OptionalAmountVisitor; + + // This is defined to provide guarded deserialization of amount + // which itself handles zero and non-zero values internally + impl<'de> de::Visitor<'de> for AmountVisitor { + type Value = api::Amount; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(formatter, "amount as i32") + } + + fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(match v { + 0 => api::Amount::Zero, + amount => api::Amount::Value(amount), + }) + } + } + + impl<'de> de::Visitor<'de> for OptionalAmountVisitor { + type Value = Option<api::Amount>; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(formatter, "option of amount (as i32)") + } + + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_any(AmountVisitor).map(Some) + } + + fn visit_none<E>(self) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(None) + } + } + + #[allow(dead_code)] + pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<api::Amount, D::Error> + where + D: de::Deserializer<'de>, + { + deserializer.deserialize_any(AmountVisitor) + } + pub(crate) fn deserialize_option<'de, D>( + deserializer: D, + ) -> Result<Option<api::Amount>, D::Error> + where + D: de::Deserializer<'de>, + { + deserializer.deserialize_option(OptionalAmountVisitor) + } +} diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 3b342f33d92..3b13f239f76 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -288,7 +288,7 @@ async fn payments_create_core() { "pay_mbabizu24mvu3mela5njyhpit10".to_string(), )), merchant_id: Some("jarnura".to_string()), - amount: Some(6540), + amount: Some(6540.into()), currency: Some("USD".to_string()), capture_method: Some(api_enums::CaptureMethod::Automatic), amount_to_capture: Some(6540), @@ -444,7 +444,7 @@ async fn payments_create_core_adyen_no_redirect() { let req = api::PaymentsRequest { payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())), merchant_id: Some(merchant_id.clone()), - amount: Some(6540), + amount: Some(6540.into()), currency: Some("USD".to_string()), capture_method: Some(api_enums::CaptureMethod::Automatic), amount_to_capture: Some(6540), diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index e9a70470a71..541193653e3 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -49,7 +49,7 @@ async fn payments_create_core() { "pay_mbabizu24mvu3mela5njyhpit10".to_string(), )), merchant_id: Some("jarnura".to_string()), - amount: Some(6540), + amount: Some(6540.into()), currency: Some("USD".to_string()), capture_method: Some(api_enums::CaptureMethod::Automatic), amount_to_capture: Some(6540), @@ -200,7 +200,7 @@ async fn payments_create_core_adyen_no_redirect() { let req = api::PaymentsRequest { payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())), merchant_id: Some(merchant_id.clone()), - amount: Some(6540), + amount: Some(6540.into()), currency: Some("USD".to_string()), capture_method: Some(api_enums::CaptureMethod::Automatic), amount_to_capture: Some(6540),
feat
make amount as an enum (#98)
043cf8e0c14e1818ec8e931140f1694d10b7b837
2025-01-15 15:26:14
Prasunna Soppa
feat(core): diesel models, domain models and db interface changes for callback_mapper table (#6571)
false
diff --git a/crates/diesel_models/src/callback_mapper.rs b/crates/diesel_models/src/callback_mapper.rs new file mode 100644 index 00000000000..3e031d483ac --- /dev/null +++ b/crates/diesel_models/src/callback_mapper.rs @@ -0,0 +1,14 @@ +use common_utils::pii; +use diesel::{Identifiable, Insertable, Queryable, Selectable}; + +use crate::schema::callback_mapper; + +#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] +#[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))] +pub struct CallbackMapper { + pub id: String, + pub type_: String, + pub data: pii::SecretSerdeValue, + pub created_at: time::PrimitiveDateTime, + pub last_modified_at: time::PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 1369368a809..1908edb8ad2 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -10,6 +10,7 @@ pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; +pub mod callback_mapper; pub mod customers; pub mod dispute; pub mod dynamic_routing_stats; @@ -61,11 +62,11 @@ use diesel_impl::{DieselArray, OptionalDieselArray}; pub type StorageResult<T> = error_stack::Result<T, errors::DatabaseError>; pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>; pub use self::{ - address::*, api_keys::*, cards_info::*, configs::*, customers::*, dispute::*, ephemeral_key::*, - events::*, file::*, generic_link::*, locker_mock_up::*, mandate::*, merchant_account::*, - merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*, - payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*, - user_authentication_method::*, + address::*, api_keys::*, callback_mapper::*, cards_info::*, configs::*, customers::*, + dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*, locker_mock_up::*, + mandate::*, merchant_account::*, merchant_connector_account::*, payment_attempt::*, + payment_intent::*, payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, + refund::*, reverse_lookup::*, user_authentication_method::*, }; /// The types and implementations provided by this module are required for the schema generated by diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 8eb0a44f5dd..468b4441a87 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -10,6 +10,7 @@ pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; +pub mod callback_mapper; pub mod customers; pub mod dashboard_metadata; pub mod dispute; diff --git a/crates/diesel_models/src/query/callback_mapper.rs b/crates/diesel_models/src/query/callback_mapper.rs new file mode 100644 index 00000000000..4210330e072 --- /dev/null +++ b/crates/diesel_models/src/query/callback_mapper.rs @@ -0,0 +1,20 @@ +use diesel::{associations::HasTable, ExpressionMethods}; + +use super::generics; +use crate::{ + callback_mapper::CallbackMapper, schema::callback_mapper::dsl, PgPooledConn, StorageResult, +}; + +impl CallbackMapper { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Self> { + generics::generic_insert(conn, self).await + } + + pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::id.eq(id.to_owned()), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6e8bdb5ec26..dfe3d5acc23 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -219,6 +219,22 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + callback_mapper (id, type_) { + #[max_length = 128] + id -> Varchar, + #[sql_name = "type"] + #[max_length = 64] + type_ -> Varchar, + data -> Jsonb, + created_at -> Timestamp, + last_modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1492,6 +1508,7 @@ diesel::allow_tables_to_appear_in_same_query!( blocklist_fingerprint, blocklist_lookup, business_profile, + callback_mapper, captures, cards_info, configs, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index d38f684a44d..b5361f4c95c 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -227,6 +227,22 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + callback_mapper (id, type_) { + #[max_length = 128] + id -> Varchar, + #[sql_name = "type"] + #[max_length = 64] + type_ -> Varchar, + data -> Jsonb, + created_at -> Timestamp, + last_modified_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1440,6 +1456,7 @@ diesel::allow_tables_to_appear_in_same_query!( blocklist_fingerprint, blocklist_lookup, business_profile, + callback_mapper, captures, cards_info, configs, diff --git a/crates/hyperswitch_domain_models/src/callback_mapper.rs b/crates/hyperswitch_domain_models/src/callback_mapper.rs new file mode 100644 index 00000000000..fffc33e572a --- /dev/null +++ b/crates/hyperswitch_domain_models/src/callback_mapper.rs @@ -0,0 +1,12 @@ +use common_utils::pii; +use serde::{self, Deserialize, Serialize}; + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct CallbackMapper { + pub id: String, + #[serde(rename = "type")] + pub type_: String, + pub data: pii::SecretSerdeValue, + pub created_at: time::PrimitiveDateTime, + pub last_modified_at: time::PrimitiveDateTime, +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 7a170f918ef..bd6dd2e5371 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -2,6 +2,7 @@ pub mod address; pub mod api; pub mod behaviour; pub mod business_profile; +pub mod callback_mapper; pub mod consts; pub mod customer; pub mod disputes; diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index eef84f6ff98..d852319e388 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -6,6 +6,7 @@ pub mod blocklist; pub mod blocklist_fingerprint; pub mod blocklist_lookup; pub mod business_profile; +pub mod callback_mapper; pub mod capture; pub mod cards_info; pub mod configs; diff --git a/crates/router/src/db/callback_mapper.rs b/crates/router/src/db/callback_mapper.rs new file mode 100644 index 00000000000..0697f41bdac --- /dev/null +++ b/crates/router/src/db/callback_mapper.rs @@ -0,0 +1,53 @@ +use error_stack::report; +use hyperswitch_domain_models::callback_mapper as domain; +use router_env::{instrument, tracing}; +use storage_impl::DataModelExt; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + types::storage, +}; + +#[async_trait::async_trait] +pub trait CallbackMapperInterface { + async fn insert_call_back_mapper( + &self, + call_back_mapper: domain::CallbackMapper, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; + + async fn find_call_back_mapper_by_id( + &self, + id: &str, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; +} + +#[async_trait::async_trait] +impl CallbackMapperInterface for Store { + #[instrument(skip_all)] + async fn insert_call_back_mapper( + &self, + call_back_mapper: domain::CallbackMapper, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + call_back_mapper + .to_storage_model() + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + .map(domain::CallbackMapper::from_storage_model) + } + + #[instrument(skip_all)] + async fn find_call_back_mapper_by_id( + &self, + id: &str, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::CallbackMapper::find_by_id(&conn, id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + .map(domain::CallbackMapper::from_storage_model) + } +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index cbced16bdcd..22e2f10c71c 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -28,7 +28,7 @@ use hyperswitch_domain_models::{ use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::Secret; use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId}; -use router_env::logger; +use router_env::{instrument, logger, tracing}; use scheduler::{ db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface}, SchedulerInterface, @@ -55,6 +55,7 @@ use crate::{ authentication::AuthenticationInterface, authorization::AuthorizationInterface, business_profile::ProfileInterface, + callback_mapper::CallbackMapperInterface, capture::CaptureInterface, cards_info::CardsInfoInterface, configs::ConfigInterface, @@ -3889,3 +3890,24 @@ impl ThemeInterface for KafkaStore { .await } } + +#[async_trait::async_trait] +impl CallbackMapperInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_call_back_mapper( + &self, + call_back_mapper: domain::CallbackMapper, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { + self.diesel_store + .insert_call_back_mapper(call_back_mapper) + .await + } + + #[instrument(skip_all)] + async fn find_call_back_mapper_by_id( + &self, + id: &str, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { + self.diesel_store.find_call_back_mapper_by_id(id).await + } +} diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index 070e583caab..9a87b6d28be 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -16,6 +16,10 @@ mod customers { pub use hyperswitch_domain_models::customer::*; } +mod callback_mapper { + pub use hyperswitch_domain_models::callback_mapper::CallbackMapper; +} + pub use customers::*; pub use merchant_account::*; @@ -39,6 +43,7 @@ pub mod user_key_store; pub use address::*; pub use business_profile::*; +pub use callback_mapper::*; pub use consts::*; pub use event::*; pub use merchant_connector_account::*; diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 24573548d79..96a0d580056 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -6,6 +6,7 @@ pub mod blocklist; pub mod blocklist_fingerprint; pub mod blocklist_lookup; pub mod business_profile; +pub mod callback_mapper; pub mod capture; pub mod cards_info; pub mod configs; @@ -63,13 +64,13 @@ pub use scheduler::db::process_tracker; pub use self::{ address::*, api_keys::*, authentication::*, authorization::*, blocklist::*, - blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, capture::*, cards_info::*, - configs::*, customers::*, dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, - ephemeral_key::*, events::*, file::*, fraud_check::*, generic_link::*, gsm::*, - locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, - merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*, - reverse_lookup::*, role::*, routing_algorithm::*, unified_translations::*, user::*, - user_authentication_method::*, user_role::*, + blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*, + capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*, + dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*, + generic_link::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, + merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, + process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*, + unified_translations::*, user::*, user_authentication_method::*, user_role::*, }; use crate::types::api::routing; diff --git a/crates/router/src/types/storage/callback_mapper.rs b/crates/router/src/types/storage/callback_mapper.rs new file mode 100644 index 00000000000..4f66a56c6f3 --- /dev/null +++ b/crates/router/src/types/storage/callback_mapper.rs @@ -0,0 +1 @@ +pub use diesel_models::callback_mapper::CallbackMapper; diff --git a/crates/storage_impl/src/callback_mapper.rs b/crates/storage_impl/src/callback_mapper.rs new file mode 100644 index 00000000000..186f2b7f927 --- /dev/null +++ b/crates/storage_impl/src/callback_mapper.rs @@ -0,0 +1,28 @@ +use diesel_models::callback_mapper::CallbackMapper as DieselCallbackMapper; +use hyperswitch_domain_models::callback_mapper::CallbackMapper; + +use crate::DataModelExt; + +impl DataModelExt for CallbackMapper { + type StorageModel = DieselCallbackMapper; + + fn to_storage_model(self) -> Self::StorageModel { + DieselCallbackMapper { + id: self.id, + type_: self.type_, + data: self.data, + created_at: self.created_at, + last_modified_at: self.last_modified_at, + } + } + + fn from_storage_model(storage_model: Self::StorageModel) -> Self { + Self { + id: storage_model.id, + type_: storage_model.type_, + data: storage_model.data, + created_at: storage_model.created_at, + last_modified_at: storage_model.last_modified_at, + } + } +} diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 09bb42567df..e0722ef52ea 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -6,6 +6,7 @@ use hyperswitch_domain_models::errors::{StorageError, StorageResult}; use masking::StrongSecret; use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore}; mod address; +pub mod callback_mapper; pub mod config; pub mod connection; pub mod customers; diff --git a/migrations/2024-11-13-105952_add_call-back-mapper_table/down.sql b/migrations/2024-11-13-105952_add_call-back-mapper_table/down.sql new file mode 100644 index 00000000000..8c2f4f54a17 --- /dev/null +++ b/migrations/2024-11-13-105952_add_call-back-mapper_table/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +DROP TABLE IF EXISTS callback_mapper; \ No newline at end of file diff --git a/migrations/2024-11-13-105952_add_call-back-mapper_table/up.sql b/migrations/2024-11-13-105952_add_call-back-mapper_table/up.sql new file mode 100644 index 00000000000..604034f4934 --- /dev/null +++ b/migrations/2024-11-13-105952_add_call-back-mapper_table/up.sql @@ -0,0 +1,9 @@ +-- Your SQL goes here +CREATE TABLE IF NOT EXISTS callback_mapper ( + id VARCHAR(128) NOT NULL, + type VARCHAR(64) NOT NULL, + data JSONB NOT NULL, + created_at TIMESTAMP NOT NULL, + last_modified_at TIMESTAMP NOT NULL, + PRIMARY KEY (id, type) +); \ No newline at end of file
feat
diesel models, domain models and db interface changes for callback_mapper table (#6571)
777771048a8144aac9e2f837c85531e139ecc125
2024-01-25 12:37:35
Apoorv Dixit
feat(user): add support to delete user (#3374)
false
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index c8d8fd96a7a..3ec30d6bd97 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -1,8 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ - AcceptInvitationRequest, AuthorizationInfoResponse, GetRoleRequest, ListRolesResponse, - RoleInfoResponse, UpdateUserRoleRequest, + AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest, + ListRolesResponse, RoleInfoResponse, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -11,5 +11,6 @@ common_utils::impl_misc_api_event_type!( GetRoleRequest, AuthorizationInfoResponse, UpdateUserRoleRequest, - AcceptInvitationRequest + AcceptInvitationRequest, + DeleteUserRoleRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index d2548935f62..e8c9b777c7f 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,5 @@ +use common_utils::pii; + use crate::user::DashboardEntryResponse; #[derive(Debug, serde::Serialize)] @@ -101,3 +103,8 @@ pub struct AcceptInvitationRequest { } pub type AcceptInvitationResponse = DashboardEntryResponse; + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct DeleteUserRoleRequest { + pub email: pii::Email, +} diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs index 678bcc2fd1f..b1cb034eb1f 100644 --- a/crates/diesel_models/src/query/dashboard_metadata.rs +++ b/crates/diesel_models/src/query/dashboard_metadata.rs @@ -104,4 +104,18 @@ impl DashboardMetadata { ) .await } + + pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await + } } diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index 6b408038ef5..e67eba64c7c 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -54,9 +54,18 @@ impl UserRole { .await } - pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<bool> { - generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::user_id.eq(user_id)) - .await + pub async fn delete_by_user_id_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await } pub async fn list_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<Vec<Self>> { diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 330e02cd547..f4000755b3e 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -54,6 +54,8 @@ pub enum UserErrors { MerchantIdParsingError, #[error("ChangePasswordError")] ChangePasswordError, + #[error("InvalidDeleteOperation")] + InvalidDeleteOperation, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -157,6 +159,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon "Old and new password cannot be same", None, )), + Self::InvalidDeleteOperation => AER::BadRequest(ApiError::new( + sub_code, + 30, + "Delete Operation Not Supported", + None, + )), } } } diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 245f8d246d2..742c281b89a 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,6 +1,7 @@ use api_models::user_role as user_role_api; use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; use error_stack::ResultExt; +use masking::ExposeInterface; use router_env::logger; use crate::{ @@ -11,6 +12,7 @@ use crate::{ authorization::{info, predefined_permissions}, ApplicationResponse, }, + types::domain, utils, }; @@ -161,3 +163,88 @@ pub async fn accept_invitation( Ok(ApplicationResponse::StatusOk) } + +pub async fn delete_user_role( + state: AppState, + user_from_token: auth::UserFromToken, + request: user_role_api::DeleteUserRoleRequest, +) -> UserResponse<()> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_email( + domain::UserEmail::from_pii_email(request.email)? + .get_secret() + .expose() + .as_str(), + ) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in records") + } else { + e.change_context(UserErrors::InternalServerError) + } + })? + .into(); + + if user_from_db.get_user_id() == user_from_token.user_id { + return Err(UserErrors::InvalidDeleteOperation.into()) + .attach_printable("User deleting himself"); + } + + let user_roles = state + .store + .list_user_roles_by_user_id(user_from_db.get_user_id()) + .await + .change_context(UserErrors::InternalServerError)?; + + match user_roles + .iter() + .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str()) + { + Some(user_role) => { + if !predefined_permissions::is_role_deletable(&user_role.role_id) { + return Err(UserErrors::InvalidRoleId.into()) + .attach_printable("Deletion not allowed for users with specific role id"); + } + } + None => { + return Err(UserErrors::InvalidDeleteOperation.into()) + .attach_printable("User is not associated with the merchant"); + } + }; + + if user_roles.len() > 1 { + state + .store + .delete_user_role_by_user_id_merchant_id( + user_from_db.get_user_id(), + user_from_token.merchant_id.as_str(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user role")?; + + Ok(ApplicationResponse::StatusOk) + } else { + state + .store + .delete_user_by_user_id(user_from_db.get_user_id()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user entry")?; + + state + .store + .delete_user_role_by_user_id_merchant_id( + user_from_db.get_user_id(), + user_from_token.merchant_id.as_str(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user role")?; + + Ok(ApplicationResponse::StatusOk) + } +} diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index ec24b4ed07d..8e2ac0b6ad3 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -36,6 +36,12 @@ pub trait DashboardMetadataInterface { org_id: &str, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] @@ -111,6 +117,21 @@ impl DashboardMetadataInterface for Store { .map_err(Into::into) .into_report() } + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() + } } #[async_trait::async_trait] @@ -246,4 +267,31 @@ impl DashboardMetadataInterface for MockDb { } Ok(query_result) } + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let mut dashboard_metadata = self.dashboard_metadata.lock().await; + + let initial_len = dashboard_metadata.len(); + + dashboard_metadata.retain(|metadata_inner| { + !(metadata_inner + .user_id + .clone() + .map(|user_id_inner| user_id_inner == user_id) + .unwrap_or(false) + && metadata_inner.merchant_id == merchant_id) + }); + + if dashboard_metadata.len() == initial_len { + return Err(errors::StorageError::ValueNotFound(format!( + "No user available for user_id = {user_id} and merchant id = {merchant_id}" + )) + .into()); + } + + Ok(true) + } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8398c153156..e88d59ea9f3 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1955,9 +1955,14 @@ impl UserRoleInterface for KafkaStore { .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) .await } - - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { - self.diesel_store.delete_user_role(user_id).await + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await } async fn list_user_roles_by_user_id( @@ -2017,6 +2022,16 @@ impl DashboardMetadataInterface for KafkaStore { .find_merchant_scoped_dashboard_metadata(merchant_id, org_id, data_keys) .await } + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index d8938f9683d..f02e6d60b3b 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -32,8 +32,11 @@ pub trait UserRoleInterface { merchant_id: &str, update: storage::UserRoleUpdate, ) -> CustomResult<storage::UserRole, errors::StorageError>; - - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError>; + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError>; async fn list_user_roles_by_user_id( &self, @@ -100,12 +103,20 @@ impl UserRoleInterface for Store { .into_report() } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::delete_by_user_id(&conn, user_id.to_owned()) - .await - .map_err(Into::into) - .into_report() + storage::UserRole::delete_by_user_id_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() } async fn list_user_roles_by_user_id( @@ -230,11 +241,17 @@ impl UserRoleInterface for MockDb { ) } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; let user_role_index = user_roles .iter() - .position(|user_role| user_role.user_id == user_id) + .position(|user_role| { + user_role.user_id == user_id && user_role.merchant_id == merchant_id + }) .ok_or(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )))?; @@ -286,8 +303,14 @@ impl UserRoleInterface for super::KafkaStore { ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store.find_user_role_by_user_id(user_id).await } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { - self.diesel_store.delete_user_role(user_id).await + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await } async fn list_user_roles_by_user_id( &self, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d3a43f0f490..71c79295c73 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -974,7 +974,8 @@ impl User { web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) .route(web::post().to(set_dashboard_metadata)), - ); + ) + .service(web::resource("/user/delete").route(web::delete().to(delete_user_role))); #[cfg(feature = "dummy_connector")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1c967222dc7..30348513c2b 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -176,6 +176,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ForgotPassword | Flow::ResetPassword | Flow::InviteUser + | Flow::DeleteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail | Flow::VerifyEmailRequest diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 73b1ef1b01d..f83134e5825 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -115,3 +115,21 @@ pub async fn accept_invitation( )) .await } + +pub async fn delete_user_role( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<user_role_api::DeleteUserRoleRequest>, +) -> HttpResponse { + let flow = Flow::DeleteUser; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload.into_inner(), + user_role_core::delete_user_role, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs index c489f1fc963..6fe0ddcc360 100644 --- a/crates/router/src/services/authorization/predefined_permissions.rs +++ b/crates/router/src/services/authorization/predefined_permissions.rs @@ -9,6 +9,7 @@ pub struct RoleInfo { permissions: Vec<Permission>, name: Option<&'static str>, is_invitable: bool, + is_deletable: bool, } impl RoleInfo { @@ -63,6 +64,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: None, is_invitable: false, + is_deletable: false, }, ); roles.insert( @@ -87,6 +89,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: None, is_invitable: false, + is_deletable: false, }, ); @@ -126,6 +129,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Organization Admin"), is_invitable: false, + is_deletable: false, }, ); @@ -165,6 +169,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Admin"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -189,6 +194,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("View Only"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -214,6 +220,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("IAM"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -239,6 +246,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Developer"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -269,6 +277,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Operator"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -291,6 +300,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Customer Support"), is_invitable: true, + is_deletable: true, }, ); roles @@ -307,3 +317,9 @@ pub fn is_role_invitable(role_id: &str) -> bool { .get(role_id) .map_or(false, |role_info| role_info.is_invitable) } + +pub fn is_role_deletable(role_id: &str) -> bool { + PREDEFINED_PERMISSIONS + .get(role_id) + .map_or(false, |role_info| role_info.is_deletable) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ba323ebc5e3..84f2e3e1267 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -321,6 +321,8 @@ pub enum Flow { ResetPassword, /// Invite users InviteUser, + /// Delete user + DeleteUser, /// Incremental Authorization flow PaymentsIncrementalAuthorization, /// Get action URL for connector onboarding
feat
add support to delete user (#3374)
44e7456a1088f8c413ff3694357822328bbc29bb
2024-04-10 19:50:40
Kartikeya Hegde
chore(deps): update time crate to 0.3.35 (#4338)
false
diff --git a/Cargo.lock b/Cargo.lock index 5aaf6b67235..b4819f9f379 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6992,9 +6992,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.34" +version = "0.3.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" +checksum = "ef89ece63debf11bc32d1ed8d078ac870cbeb44da02afb02a9ff135ae7ca0582" dependencies = [ "deranged", "itoa", @@ -7015,9 +7015,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ "num-conv", "time-core", diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index 2b1cc798a7e..c3e35519dce 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -37,5 +37,5 @@ serde_json = "1.0.115" sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] } strum = { version = "0.26.2", features = ["derive"] } thiserror = "1.0.58" -time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index cdcee9c506e..0bd0b01a278 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -30,7 +30,7 @@ reqwest = { version = "0.11.27", optional = true } serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26", features = ["derive"] } -time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } frunk = "0.4.2" diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml index ab4152893af..ac8a417fb99 100644 --- a/crates/cards/Cargo.toml +++ b/crates/cards/Cargo.toml @@ -14,7 +14,7 @@ error-stack = "0.4.1" luhn = "1.0.1" serde = { version = "1.0.197", features = ["derive"] } thiserror = "1.0.58" -time = "0.3.34" +time = "0.3.35" # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index 285d423958d..6f08649fbda 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -36,7 +36,7 @@ serde_urlencoded = "0.7.1" signal-hook = { version = "0.3.17", optional = true } strum = { version = "0.26.2", features = ["derive"] } thiserror = "1.0.58" -time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"], optional = true } semver = { version = "1.0.22", features = ["serde"] } uuid = { version = "1.8.0", features = ["v7"] } diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs index e4608c4f371..79e0c5b85e7 100644 --- a/crates/common_utils/src/custom_serde.rs +++ b/crates/common_utils/src/custom_serde.rs @@ -265,3 +265,22 @@ pub mod iso8601custom { }) } } + +#[cfg(test)] +mod tests { + use serde::{Deserialize, Serialize}; + use serde_json::json; + + #[test] + fn test_leap_second_parse() { + #[derive(Serialize, Deserialize)] + struct Try { + #[serde(with = "crate::custom_serde::iso8601")] + f: time::PrimitiveDateTime, + } + let leap_second_date_time = json!({"f": "2023-12-31T23:59:60.000Z"}); + let deser = serde_json::from_value::<Try>(leap_second_date_time); + + assert!(deser.is_ok()) + } +} diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index b1a708f7a08..7b8b7bb9490 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -23,15 +23,15 @@ pub mod validation; /// Date-time utilities. pub mod date_time { + #[cfg(feature = "async_ext")] + use std::time::Instant; use std::{marker::PhantomData, num::NonZeroU8}; use masking::{Deserialize, Serialize}; - #[cfg(feature = "async_ext")] - use time::Instant; use time::{ format_description::{ well_known::iso8601::{Config, EncodedConfig, Iso8601, TimePrecision}, - FormatItem, + BorrowedFormatItem, }, OffsetDateTime, PrimitiveDateTime, }; @@ -68,7 +68,7 @@ pub mod date_time { ) -> (T, f64) { let start = Instant::now(); let result = block().await; - (result, start.elapsed().as_seconds_f64() * 1000f64) + (result, start.elapsed().as_secs_f64() * 1000f64) } /// Return the given date and time in UTC with the given format Eg: format: YYYYMMDDHHmmss Eg: 20191105081132 @@ -76,7 +76,7 @@ pub mod date_time { date: PrimitiveDateTime, format: DateFormat, ) -> Result<String, time::error::Format> { - let format = <&[FormatItem<'_>]>::from(format); + let format = <&[BorrowedFormatItem<'_>]>::from(format); date.format(&format) } @@ -90,7 +90,7 @@ pub mod date_time { now().assume_utc().format(&Iso8601::<ISO_CONFIG>) } - impl From<DateFormat> for &[FormatItem<'_>] { + impl From<DateFormat> for &[BorrowedFormatItem<'_>] { fn from(format: DateFormat) -> Self { match format { DateFormat::YYYYMMDDHHmmss => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero][second padding:zero]"), diff --git a/crates/data_models/Cargo.toml b/crates/data_models/Cargo.toml index 6da89dc2325..54130ca002a 100644 --- a/crates/data_models/Cargo.toml +++ b/crates/data_models/Cargo.toml @@ -26,4 +26,4 @@ error-stack = "0.4.1" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" thiserror = "1.0.58" -time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index 85533d0cf33..577233cdf1a 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -21,7 +21,7 @@ serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } thiserror = "1.0.58" -time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } # First party crates common_enums = { version = "0.1.0", path = "../common_enums" } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 1adecf37c67..8915ab573e0 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -87,7 +87,7 @@ sqlx = { version = "0.7.3", features = ["postgres", "runtime-tokio", "runtime-to strum = { version = "0.26", features = ["derive"] } tera = "1.19.1" thiserror = "1.0.58" -time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } unicode-segmentation = "1.11.0" url = { version = "2.5.0", features = ["serde"] } @@ -135,7 +135,7 @@ awc = { version = "3.4.0", features = ["rustls"] } derive_deref = "1.1.1" rand = "0.8.5" serial_test = "3.0.0" -time = { version = "0.3.34", features = ["macros"] } +time = { version = "0.3.35", features = ["macros"] } tokio = "1.37.0" wiremock = "0.6.0" diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml index 72f0f0b39ac..3b95d5f22fd 100644 --- a/crates/router_env/Cargo.toml +++ b/crates/router_env/Cargo.toml @@ -20,7 +20,7 @@ serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" serde_path_to_error = "0.1.16" strum = { version = "0.26.2", features = ["derive"] } -time = { version = "0.3.34", default-features = false, features = ["formatting"] } +time = { version = "0.3.35", default-features = false, features = ["formatting"] } tokio = { version = "1.37.0" } tracing = { version = "0.1.40" } tracing-actix-web = { version = "0.7.10", features = ["opentelemetry_0_19", "uuid_v7"], optional = true } diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index f713b8f2f2b..b98f212d674 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -23,7 +23,7 @@ serde = "1.0.197" serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } thiserror = "1.0.58" -time = { version = "0.3.34", features = ["serde", "serde-well-known", "std"] } +time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } uuid = { version = "1.8.0", features = ["v4"] } diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml index 714e34f0e95..3b0dfe2b91d 100644 --- a/crates/test_utils/Cargo.toml +++ b/crates/test_utils/Cargo.toml @@ -24,7 +24,7 @@ serde_json = "1.0.115" serde_urlencoded = "0.7.1" serial_test = "3.0.0" thirtyfour = "0.31.0" -time = { version = "0.3.34", features = ["macros"] } +time = { version = "0.3.35", features = ["macros"] } tokio = "1.37.0" toml = "0.8.12"
chore
update time crate to 0.3.35 (#4338)
b681f78d964d02f80249751cc6fd12e3c85bc4d7
2023-06-02 13:30:39
Sanchith Hegde
chore: address Rust 1.70 clippy lints (#1334)
false
diff --git a/crates/masking/tests/basic.rs b/crates/masking/tests/basic.rs index bab5c9607b8..7857783f830 100644 --- a/crates/masking/tests/basic.rs +++ b/crates/masking/tests/basic.rs @@ -41,7 +41,7 @@ fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { }; // clone - + #[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal let composite2 = composite.clone(); assert_eq!(composite, composite2); @@ -134,7 +134,7 @@ fn for_string() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { }; // clone - + #[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal let composite2 = composite.clone(); assert_eq!(composite, composite2); diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs index 39a3341098c..7a7aa719f69 100644 --- a/crates/router/src/connector/nexinets.rs +++ b/crates/router/src/connector/nexinets.rs @@ -95,7 +95,7 @@ impl ConnectorCommon for Nexinets { .parse_struct("NexinetsErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let errors = response.errors.clone(); + let errors = response.errors; let mut message = String::new(); let mut static_message = String::new(); for error in errors.iter() {
chore
address Rust 1.70 clippy lints (#1334)
a95fa581797f2db72d1b448b944ce90b304bead8
2023-08-10 08:22:43
github-actions
chore(version): v1.19.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index ba1f204ae78..9cbd09907aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.19.0 (2023-08-10) + +### Features + +- **connector:** [Adyen] implement Japanese convenience stores ([#1819](https://github.com/juspay/hyperswitch/pull/1819)) ([`a6fdf6d`](https://github.com/juspay/hyperswitch/commit/a6fdf6dc34901a9985062fd5532d967910bcf3c0)) +- **docs:** Add multiple examples support and webhook schema ([#1864](https://github.com/juspay/hyperswitch/pull/1864)) ([`f8ef52c`](https://github.com/juspay/hyperswitch/commit/f8ef52c645d353aac438d6af5b00d9097332fdcb)) + +### Bug Fixes + +- **connector:** + - [ACI] Response Handling in case of `ErrorResponse` ([#1870](https://github.com/juspay/hyperswitch/pull/1870)) ([`14f599d`](https://github.com/juspay/hyperswitch/commit/14f599d1be272afcfd16dfac58c47dbbb649423d)) + - [Adyen] Response Handling in case of RefusalResponse ([#1877](https://github.com/juspay/hyperswitch/pull/1877)) ([`c35a571`](https://github.com/juspay/hyperswitch/commit/c35a5719eb08ff76a10d554a0e61d0af81ff26e6)) +- **router:** Handle JSON connector response parse error ([#1892](https://github.com/juspay/hyperswitch/pull/1892)) ([`393c2ab`](https://github.com/juspay/hyperswitch/commit/393c2ab94cf1052f6f8fa0b40c09e36555ffecd7)) + +### Refactors + +- **connector:** Update the `connector_template` ([#1895](https://github.com/juspay/hyperswitch/pull/1895)) ([`5fe96d4`](https://github.com/juspay/hyperswitch/commit/5fe96d4d9683d8eae25f214f3823d3765dce326a)) +- Remove unnecessary debug logs from payment method list api ([#1884](https://github.com/juspay/hyperswitch/pull/1884)) ([`ba82f17`](https://github.com/juspay/hyperswitch/commit/ba82f173dbccfc2312677ec96fdd85813a417dc6)) + +### Documentation + +- Add architecture and monitoring diagram of hyperswitch ([#1825](https://github.com/juspay/hyperswitch/pull/1825)) ([`125ef2b`](https://github.com/juspay/hyperswitch/commit/125ef2b4f82c922209bcfe161ce4790fe2ee3a86)) + +### Miscellaneous Tasks + +- **configs:** Add `payout_connector_list` config to toml ([#1909](https://github.com/juspay/hyperswitch/pull/1909)) ([`c1e5626`](https://github.com/juspay/hyperswitch/commit/c1e56266df6aabd1c498d6a7ebec324b0df23c12)) +- Add connector functionality validation based on connector_type ([#1849](https://github.com/juspay/hyperswitch/pull/1849)) ([`33c6d71`](https://github.com/juspay/hyperswitch/commit/33c6d71a8a71619f811accbc21f3c22c3c279c47)) +- Remove spaces at beginning of commit messages when generating changelogs ([#1906](https://github.com/juspay/hyperswitch/pull/1906)) ([`7d13226`](https://github.com/juspay/hyperswitch/commit/7d13226740dbc4c1b6ec19631bb93ba89281d303)) + +**Full Changelog:** [`v1.18.0...v1.19.0`](https://github.com/juspay/hyperswitch/compare/v1.18.0...v1.19.0) + +- - - + + ## 1.18.0 (2023-08-09) ### Features
chore
v1.19.0
75ce0df41516696b18b39f693c29b8f1f105112b
2022-11-24 13:56:16
Sanchith Hegde
ci(CI-skip-ignored-files): specify OS matrix with single entry (#13)
false
diff --git a/.github/workflows/CI-skip-ignored-files.yml b/.github/workflows/CI-skip-ignored-files.yml index 7edfc90420e..04523b6f35f 100644 --- a/.github/workflows/CI-skip-ignored-files.yml +++ b/.github/workflows/CI-skip-ignored-files.yml @@ -30,7 +30,11 @@ jobs: check-msrv: name: Check compilation on MSRV toolchain - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: + - ubuntu-latest steps: - name: Skip compilation checks shell: bash @@ -47,6 +51,10 @@ jobs: test: name: Run tests on stable toolchain runs-on: ${{ matrix.os }} + strategy: + matrix: + os: + - ubuntu-latest steps: - name: Skip compilation checks shell: bash
ci
specify OS matrix with single entry (#13)
7d8f100037cc78840c499ea426549d0b89262ac1
2023-02-03 15:01:49
Nishant Joshi
feat: add logging functionality in drainer (#495)
false
diff --git a/crates/drainer/src/env.rs b/crates/drainer/src/env.rs new file mode 100644 index 00000000000..a961a2dddd2 --- /dev/null +++ b/crates/drainer/src/env.rs @@ -0,0 +1,27 @@ +#[doc(inline)] +pub use router_env::*; + +pub mod logger { + #[doc(inline)] + pub use router_env::{log, logger::*}; + + /// + /// Setup logging sub-system + /// + /// + pub fn setup( + conf: &config::Log, + ) -> error_stack::Result<TelemetryGuard, router_env::opentelemetry::metrics::MetricsError> { + Ok(router_env::setup( + conf, + "drainer", + vec![ + "drainer", + "common_utils", + "redis_interface", + "router_env", + "storage_models", + ], + )?) + } +} diff --git a/crates/drainer/src/errors.rs b/crates/drainer/src/errors.rs index 50d5876886b..f46620cd33a 100644 --- a/crates/drainer/src/errors.rs +++ b/crates/drainer/src/errors.rs @@ -9,6 +9,8 @@ pub enum DrainerError { RedisError(error_stack::Report<redis::errors::RedisError>), #[error("Application configuration error: {0}")] ConfigurationError(config::ConfigError), + #[error("Metrics initialization error")] + MetricsError, } pub type DrainerResult<T> = error_stack::Result<T, DrainerError>; diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index a0f5afcb323..81aaf159ca0 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -1,14 +1,18 @@ mod connection; +pub mod env; pub mod errors; pub mod services; pub mod settings; mod utils; use std::sync::Arc; +pub use env as logger; +use logger::{instrument, tracing}; use storage_models::kv; use crate::{connection::pg_connection, services::Store}; +#[instrument(skip(store))] pub async fn start_drainer( store: Arc<Store>, number_of_streams: u8, @@ -32,8 +36,8 @@ async fn drainer_handler( let stream_name = utils::get_drainer_stream_name(store.clone(), stream_index); let drainer_result = drainer(store.clone(), max_read_count, stream_name.as_str()).await; - if let Err(_e) = drainer_result { - //TODO: LOG errors + if let Err(error) = drainer_result { + logger::error!(?error) } let flag_stream_name = utils::get_stream_key_flag(store.clone(), stream_index); @@ -122,8 +126,8 @@ mod macro_util { macro_rules! handle_resp { ($result:expr,$op_type:expr, $table:expr) => { match $result { - Ok(aa) => println!("Ok|{}|{}|{:?}|", $op_type, $table, aa), - Err(err) => println!("Err|{}|{}|{:?}|", $op_type, $table, err), + Ok(aa) => logger::info!("Ok|{}|{}|{:?}|", $op_type, $table, aa), + Err(err) => logger::error!("Err|{}|{}|{:?}|", $op_type, $table, err), } }; } diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 1d928d9fc94..6c1ba086743 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -1,4 +1,5 @@ -use drainer::{errors::DrainerResult, services, settings, start_drainer}; +use drainer::{errors, errors::DrainerResult, logger::logger, services, settings, start_drainer}; +use error_stack::ResultExt; #[tokio::main] async fn main() -> DrainerResult<()> { @@ -18,7 +19,12 @@ async fn main() -> DrainerResult<()> { let number_of_streams = store.config.drainer_num_partitions; let max_read_count = conf.drainer.max_read_count; - start_drainer(store, number_of_streams, max_read_count).await?; + let _guard = logger::setup(&conf.log).change_context(errors::DrainerError::MetricsError)?; + logger::info!("Drainer started [{:?}] [{:?}]", conf.drainer, conf.log); + + start_drainer(store.clone(), number_of_streams, max_read_count).await?; + + store.close().await; Ok(()) } diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index dd86010716c..a9cbf12378f 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -31,4 +31,13 @@ impl Store { // Example: {shard_5}_drainer_stream format!("{{{}}}_{}", shard_key, self.config.drainer_stream_name,) } + + #[allow(clippy::expect_used)] + pub async fn close(mut self: Arc<Self>) { + Arc::get_mut(&mut self) + .and_then(|inner| Arc::get_mut(&mut inner.redis_conn)) + .expect("Redis connection pool cannot be closed") + .close_connections() + .await; + } } diff --git a/crates/drainer/src/utils.rs b/crates/drainer/src/utils.rs index 91c15275548..45142c40871 100644 --- a/crates/drainer/src/utils.rs +++ b/crates/drainer/src/utils.rs @@ -5,7 +5,7 @@ use redis_interface as redis; use crate::{ errors::{self, DrainerError}, - services, + logger, services, }; pub type StreamEntries = Vec<(String, HashMap<String, String>)>; @@ -20,7 +20,8 @@ pub async fn is_stream_available(stream_index: u8, store: Arc<services::Store>) .await { Ok(resp) => resp == redis::types::SetnxReply::KeySet, - Err(_e) => { + Err(error) => { + logger::error!(?error); // Add metrics or logs false }
feat
add logging functionality in drainer (#495)
af8778e0091fb4dd92bac55c3972c1ca99303aff
2025-03-03 15:04:51
CHALLA NISHANTH BABU
feat(connector): add template code for stripebilling (#7228)
false
diff --git a/config/config.example.toml b/config/config.example.toml index 1b24292e886..9e54c7e8c88 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -263,6 +263,7 @@ square.base_url = "https://connect.squareupsandbox.com/" square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" +stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" @@ -336,6 +337,7 @@ cards = [ "square", "stax", "stripe", + "stripebilling", "threedsecureio", "thunes", "worldpay", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 0faa8bd81aa..c8eb14c9853 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -109,6 +109,7 @@ square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripe.base_url_file_upload = "https://files.stripe.com/" +stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" thunes.base_url = "https://api.limonetikqualif.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 01e7bdd32bf..90ca4ae143d 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -113,6 +113,7 @@ square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripe.base_url_file_upload = "https://files.stripe.com/" +stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.taxjar.com/v2/" thunes.base_url = "https://api.limonetik.com/" trustpay.base_url = "https://tpgw.trustpay.eu/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index c61c8ae53f9..29e60131149 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -113,6 +113,7 @@ square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripe.base_url_file_upload = "https://files.stripe.com/" +stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" thunes.base_url = "https://api.limonetikqualif.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" diff --git a/config/development.toml b/config/development.toml index b73f267dba9..7619f992aab 100644 --- a/config/development.toml +++ b/config/development.toml @@ -209,6 +209,7 @@ cards = [ "square", "stax", "stripe", + "stripebilling", "taxjar", "threedsecureio", "thunes", @@ -334,6 +335,7 @@ square.base_url = "https://connect.squareupsandbox.com/" square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" +stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index a934bb57957..58cf75fb8d2 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -195,6 +195,7 @@ square.base_url = "https://connect.squareupsandbox.com/" square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" +stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" @@ -290,6 +291,7 @@ cards = [ "square", "stax", "stripe", + "stripebilling", "taxjar", "threedsecureio", "thunes", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index c65cd99d935..cadca5fad02 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -123,6 +123,7 @@ pub enum RoutableConnectors { Square, Stax, Stripe, + //Stripebilling, // Taxjar, Trustpay, // Thunes @@ -263,6 +264,7 @@ pub enum Connector { Square, Stax, Stripe, + // Stripebilling, Taxjar, Threedsecureio, //Thunes, @@ -410,6 +412,7 @@ impl Connector { | Self::Shift4 | Self::Square | Self::Stax + // | Self::Stripebilling | Self::Taxjar // | Self::Thunes | Self::Trustpay @@ -546,6 +549,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Square => Self::Square, RoutableConnectors::Stax => Self::Stax, RoutableConnectors::Stripe => Self::Stripe, + // RoutableConnectors::Stripebilling => Self::Stripebilling, RoutableConnectors::Trustpay => Self::Trustpay, RoutableConnectors::Tsys => Self::Tsys, RoutableConnectors::Volt => Self::Volt, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 97a2bdb77bb..bf815d5c2ca 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -57,6 +57,7 @@ pub mod redsys; pub mod shift4; pub mod square; pub mod stax; +pub mod stripebilling; pub mod taxjar; pub mod thunes; pub mod tsys; @@ -83,8 +84,9 @@ pub use self::{ nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, nuvei::Nuvei, paybox::Paybox, payeezy::Payeezy, paystack::Paystack, payu::Payu, placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, - redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, - tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, volt::Volt, + redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling, + taxjar::Taxjar, thunes::Thunes, tsys::Tsys, + unified_authentication_service::UnifiedAuthenticationService, volt::Volt, wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl, }; diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs new file mode 100644 index 00000000000..e05fb8b8e33 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling.rs @@ -0,0 +1,573 @@ +pub mod transformers; + +use common_utils::{ + errors::CustomResult, + ext_traits::BytesExt, + request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, + }, +}; +use hyperswitch_interfaces::{ + api::{ + self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as stripebilling; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Stripebilling { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Stripebilling { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Stripebilling {} +impl api::PaymentSession for Stripebilling {} +impl api::ConnectorAccessToken for Stripebilling {} +impl api::MandateSetup for Stripebilling {} +impl api::PaymentAuthorize for Stripebilling {} +impl api::PaymentSync for Stripebilling {} +impl api::PaymentCapture for Stripebilling {} +impl api::PaymentVoid for Stripebilling {} +impl api::Refund for Stripebilling {} +impl api::RefundExecute for Stripebilling {} +impl api::RefundSync for Stripebilling {} +impl api::PaymentToken for Stripebilling {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Stripebilling +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Stripebilling +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Stripebilling { + fn id(&self) -> &'static str { + "stripebilling" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Minor + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.stripebilling.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = stripebilling::StripebillingAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.expose().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: stripebilling::StripebillingErrorResponse = res + .response + .parse_struct("StripebillingErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + attempt_status: None, + connector_transaction_id: None, + }) + } +} + +impl ConnectorValidation for Stripebilling { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Stripebilling { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Stripebilling {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Stripebilling +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> + for Stripebilling +{ + fn get_headers( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = stripebilling::StripebillingRouterData::from((amount, req)); + let connector_req = + stripebilling::StripebillingPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: stripebilling::StripebillingPaymentsResponse = res + .response + .parse_struct("Stripebilling PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Stripebilling { + fn get_headers( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + let response: stripebilling::StripebillingPaymentsResponse = res + .response + .parse_struct("stripebilling PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Stripebilling { + fn get_headers( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCaptureRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + let response: stripebilling::StripebillingPaymentsResponse = res + .response + .parse_struct("Stripebilling PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Stripebilling {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Stripebilling { + fn get_headers( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let refund_amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = + stripebilling::StripebillingRouterData::from((refund_amount, req)); + let connector_req = + stripebilling::StripebillingRefundRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let request = RequestBuilder::new() + .method(Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .set_body(types::RefundExecuteType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &RefundsRouterData<Execute>, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + let response: stripebilling::RefundResponse = res + .response + .parse_struct("stripebilling RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Stripebilling { + fn get_headers( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &RefundSyncRouterData, + _connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .set_body(types::RefundSyncType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &RefundSyncRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + let response: stripebilling::RefundResponse = res + .response + .parse_struct("stripebilling RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + RouterData::try_from(ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } +} + +#[async_trait::async_trait] +impl webhooks::IncomingWebhook for Stripebilling { + fn get_webhook_object_reference_id( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_event_type( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } + + fn get_webhook_resource_object( + &self, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { + Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + } +} + +impl ConnectorSpecifications for Stripebilling {} diff --git a/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs new file mode 100644 index 00000000000..dcaa2474639 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/stripebilling/transformers.rs @@ -0,0 +1,232 @@ +use common_enums::enums; +use common_utils::types::StringMinorUnit; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, RefundsRouterData}, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::PaymentsAuthorizeRequestData, +}; + +//TODO: Fill the struct with respective fields +pub struct StripebillingRouterData<T> { + pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for StripebillingRouterData<T> { + fn from((amount, item): (StringMinorUnit, T)) -> Self { + //Todo : use utils to convert the amount to the type of amount that a connector accepts + Self { + amount, + router_data: item, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, PartialEq)] +pub struct StripebillingPaymentsRequest { + amount: StringMinorUnit, + card: StripebillingCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct StripebillingCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&StripebillingRouterData<&PaymentsAuthorizeRouterData>> + for StripebillingPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &StripebillingRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = StripebillingCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct StripebillingAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for StripebillingAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: api_key.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum StripebillingPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<StripebillingPaymentStatus> for common_enums::AttemptStatus { + fn from(item: StripebillingPaymentStatus) -> Self { + match item { + StripebillingPaymentStatus::Succeeded => Self::Charged, + StripebillingPaymentStatus::Failed => Self::Failure, + StripebillingPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct StripebillingPaymentsResponse { + status: StripebillingPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, StripebillingPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, StripebillingPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charges: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct StripebillingRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&StripebillingRouterData<&RefundsRouterData<F>>> for StripebillingRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &StripebillingRouterData<&RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.amount.to_owned(), + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct StripebillingErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 243afaa5f41..86bed027071 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -153,6 +153,7 @@ default_imp_for_authorize_session_token!( connectors::Redsys, connectors::Shift4, connectors::Stax, + connectors::Stripebilling, connectors::Taxjar, connectors::UnifiedAuthenticationService, connectors::Volt, @@ -240,6 +241,7 @@ default_imp_for_calculate_tax!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Thunes, connectors::Tsys, connectors::UnifiedAuthenticationService, @@ -305,6 +307,7 @@ default_imp_for_session_update!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Mifinity, connectors::Mollie, @@ -392,6 +395,7 @@ default_imp_for_post_session_tokens!( connectors::Redsys, connectors::Shift4, connectors::Stax, + connectors::Stripebilling, connectors::Taxjar, connectors::Mifinity, connectors::Mollie, @@ -487,6 +491,7 @@ default_imp_for_complete_authorize!( connectors::Redsys, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -573,6 +578,7 @@ default_imp_for_incremental_authorization!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -658,6 +664,7 @@ default_imp_for_create_customer!( connectors::Redsys, connectors::Shift4, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -737,6 +744,7 @@ default_imp_for_connector_redirect_response!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -816,6 +824,7 @@ default_imp_for_pre_processing_steps!( connectors::Redsys, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -903,6 +912,7 @@ default_imp_for_post_processing_steps!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -991,6 +1001,7 @@ default_imp_for_approve!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1079,6 +1090,7 @@ default_imp_for_reject!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1167,6 +1179,7 @@ default_imp_for_webhook_source_verification!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1256,6 +1269,7 @@ default_imp_for_accept_dispute!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1344,6 +1358,7 @@ default_imp_for_submit_evidence!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1432,6 +1447,7 @@ default_imp_for_defend_dispute!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1529,6 +1545,7 @@ default_imp_for_file_upload!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1608,6 +1625,7 @@ default_imp_for_payouts!( connectors::Shift4, connectors::Square, connectors::Stax, + connectors::Stripebilling, connectors::Taxjar, connectors::Tsys, connectors::UnifiedAuthenticationService, @@ -1696,6 +1714,7 @@ default_imp_for_payouts_create!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1785,6 +1804,7 @@ default_imp_for_payouts_retrieve!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1874,6 +1894,7 @@ default_imp_for_payouts_eligibility!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1962,6 +1983,7 @@ default_imp_for_payouts_fulfill!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2051,6 +2073,7 @@ default_imp_for_payouts_cancel!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2140,6 +2163,7 @@ default_imp_for_payouts_quote!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2229,6 +2253,7 @@ default_imp_for_payouts_recipient!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2318,6 +2343,7 @@ default_imp_for_payouts_recipient_account!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2408,6 +2434,7 @@ default_imp_for_frm_sale!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2498,6 +2525,7 @@ default_imp_for_frm_checkout!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2588,6 +2616,7 @@ default_imp_for_frm_transaction!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2678,6 +2707,7 @@ default_imp_for_frm_fulfillment!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2768,6 +2798,7 @@ default_imp_for_frm_record_return!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2854,6 +2885,7 @@ default_imp_for_revoking_mandates!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2942,6 +2974,7 @@ default_imp_for_uas_pre_authentication!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -3028,6 +3061,7 @@ default_imp_for_uas_post_authentication!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -3114,6 +3148,7 @@ default_imp_for_uas_authentication!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -3201,6 +3236,7 @@ default_imp_for_uas_authentication_confirmation!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 003c3cc46d1..ef339c22a4b 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -263,6 +263,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -352,6 +353,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -436,6 +438,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -525,6 +528,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -613,6 +617,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -702,6 +707,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -801,6 +807,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -892,6 +899,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -983,6 +991,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1074,6 +1083,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1165,6 +1175,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1256,6 +1267,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1347,6 +1359,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1438,6 +1451,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1529,6 +1543,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1618,6 +1633,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1709,6 +1725,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1800,6 +1817,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1891,6 +1909,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1982,6 +2001,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2073,6 +2093,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -2161,6 +2182,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Shift4, connectors::Stax, connectors::Square, + connectors::Stripebilling, connectors::Taxjar, connectors::Thunes, connectors::Tsys, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index 4c4801801f0..5b46184c363 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -88,6 +88,7 @@ pub struct Connectors { pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, + pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index de9d86fdd79..c4720f60ff6 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -44,8 +44,9 @@ pub use hyperswitch_connectors::connectors::{ nuvei::Nuvei, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, paystack, paystack::Paystack, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, redsys, - redsys::Redsys, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar, - taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, unified_authentication_service, + redsys::Redsys, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, + stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, + tsys, tsys::Tsys, unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs index 997a40c9393..d19afa5368e 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -1041,6 +1041,7 @@ default_imp_for_new_connector_integration_payouts!( connector::Square, connector::Stax, connector::Stripe, + connector::Stripebilling, connector::Shift4, connector::Taxjar, connector::Trustpay, @@ -1508,6 +1509,7 @@ default_imp_for_new_connector_integration_frm!( connector::Square, connector::Stax, connector::Stripe, + connector::Stripebilling, connector::Shift4, connector::Taxjar, connector::Trustpay, @@ -1888,6 +1890,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connector::Square, connector::Stax, connector::Stripe, + connector::Stripebilling, connector::Shift4, connector::Taxjar, connector::Trustpay, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index e9e3ea10cd6..af5b5e54cbe 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -467,6 +467,7 @@ default_imp_for_connector_request_id!( connector::Square, connector::Stax, connector::Stripe, + connector::Stripebilling, connector::Taxjar, connector::Threedsecureio, connector::Trustpay, @@ -1427,6 +1428,7 @@ default_imp_for_fraud_check!( connector::Square, connector::Stax, connector::Stripe, + connector::Stripebilling, connector::Taxjar, connector::Threedsecureio, connector::Trustpay, @@ -1965,6 +1967,7 @@ default_imp_for_connector_authentication!( connector::Square, connector::Stax, connector::Stripe, + connector::Stripebilling, connector::Taxjar, connector::Trustpay, connector::Tsys, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index d4b9d1eafce..a32e0457dfa 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -519,6 +519,7 @@ impl ConnectorData { enums::Connector::Stripe => { Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new()))) } + // enums::Connector::Stripebilling => Ok(ConnectorEnum::Old(Box::new(connector::Stripebilling))), enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(connector::Wise::new()))), enums::Connector::Worldline => { Ok(ConnectorEnum::Old(Box::new(&connector::Worldline))) diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 1035aed2f99..0171e6e7c90 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -305,6 +305,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Square => Self::Square, api_enums::Connector::Stax => Self::Stax, api_enums::Connector::Stripe => Self::Stripe, + // api_enums::Connector::Stripebilling => Self::Stripebilling, // api_enums::Connector::Taxjar => Self::Taxjar, // api_enums::Connector::Thunes => Self::Thunes, api_enums::Connector::Trustpay => Self::Trustpay, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index d0eb96efcc8..09718d56181 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -83,6 +83,7 @@ mod shift4; mod square; mod stax; mod stripe; +mod stripebilling; mod taxjar; mod trustpay; mod tsys; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 6509e1e411f..d30a5008887 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -316,5 +316,8 @@ api_key= "API Key" [moneris] api_key= "API Key" +[stripebilling] +api_key= "API Key" + [paystack] api_key = "API Key" \ No newline at end of file diff --git a/crates/router/tests/connectors/stripebilling.rs b/crates/router/tests/connectors/stripebilling.rs new file mode 100644 index 00000000000..8fccb9cb885 --- /dev/null +++ b/crates/router/tests/connectors/stripebilling.rs @@ -0,0 +1,421 @@ +use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; +use masking::Secret; +use router::types::{self, api, storage::enums}; +use test_utils::connector_auth; + +use crate::utils::{self, ConnectorActions}; + +#[derive(Clone, Copy)] +struct StripebillingTest; +impl ConnectorActions for StripebillingTest {} +impl utils::Connector for StripebillingTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Stripebilling; + utils::construct_connector_data_old( + Box::new(Stripebilling::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .stripebilling + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "stripebilling".to_string() + } +} + +static CONNECTOR: StripebillingTest = StripebillingTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenarios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: PaymentMethodData::Card(Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 521e58136aa..bb40cc51eaa 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -87,6 +87,7 @@ pub struct ConnectorAuthentication { pub square: Option<BodyKey>, pub stax: Option<HeaderKey>, pub stripe: Option<HeaderKey>, + pub stripebilling: Option<HeaderKey>, pub taxjar: Option<HeaderKey>, pub threedsecureio: Option<HeaderKey>, pub thunes: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 5c2571cec1a..526899b7fff 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -161,6 +161,7 @@ square.base_url = "https://connect.squareupsandbox.com/" square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" +stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" @@ -254,6 +255,7 @@ cards = [ "square", "stax", "stripe", + "stripebilling", "taxjar", "threedsecureio", "thunes", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index f2c55f54adc..046042bfa73 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe stripebilling taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
feat
add template code for stripebilling (#7228)
bfa1645b847fb881eb2370d5dbfef6fd0b53725d
2023-11-24 20:34:27
Apoorv Dixit
feat(user): implement change password for user (#2959)
false
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 2a896cc3877..4e9f2f28417 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -1,6 +1,6 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; -use crate::user::{ConnectAccountRequest, ConnectAccountResponse}; +use crate::user::{ChangePasswordRequest, ConnectAccountRequest, ConnectAccountResponse}; impl ApiEventMetric for ConnectAccountResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { @@ -12,3 +12,5 @@ impl ApiEventMetric for ConnectAccountResponse { } impl ApiEventMetric for ConnectAccountRequest {} + +common_utils::impl_misc_api_event_type!(ChangePasswordRequest); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 91f7702c654..41ea9cc5193 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -19,3 +19,9 @@ pub struct ConnectAccountResponse { #[serde(skip_serializing)] pub user_id: String, } + +#[derive(serde::Deserialize, Debug, serde::Serialize)] +pub struct ChangePasswordRequest { + pub new_password: Secret<String>, + pub old_password: Secret<String>, +} diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index b4d48365dc8..b86c395b981 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -13,6 +13,8 @@ pub enum UserErrors { InvalidCredentials, #[error("UserExists")] UserExists, + #[error("InvalidOldPassword")] + InvalidOldPassword, #[error("EmailParsingError")] EmailParsingError, #[error("NameParsingError")] @@ -27,6 +29,8 @@ pub enum UserErrors { InvalidEmailError, #[error("DuplicateOrganizationId")] DuplicateOrganizationId, + #[error("MerchantIdNotFound")] + MerchantIdNotFound, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -49,6 +53,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon "An account already exists with this email", None, )), + Self::InvalidOldPassword => AER::BadRequest(ApiError::new( + sub_code, + 6, + "Old password incorrect. Please enter the correct password", + None, + )), Self::EmailParsingError => { AER::BadRequest(ApiError::new(sub_code, 7, "Invalid Email", None)) } @@ -73,6 +83,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon "An Organization with the id already exists", None, )), + Self::MerchantIdNotFound => { + AER::BadRequest(ApiError::new(sub_code, 18, "Invalid Merchant ID", None)) + } } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 8b4cf45fe5e..94cd482a229 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,11 +1,17 @@ use api_models::user as api; use diesel_models::enums::UserStatus; -use error_stack::IntoReport; +use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, Secret}; use router_env::env; use super::errors::{UserErrors, UserResponse}; -use crate::{consts, routes::AppState, services::ApplicationResponse, types::domain}; +use crate::{ + consts, + db::user::UserInterface, + routes::AppState, + services::{authentication::UserFromToken, ApplicationResponse}, + types::domain, +}; pub async fn connect_account( state: AppState, @@ -77,3 +83,35 @@ pub async fn connect_account( Err(UserErrors::InternalServerError.into()) } } + +pub async fn change_password( + state: AppState, + request: api::ChangePasswordRequest, + user_from_token: UserFromToken, +) -> UserResponse<()> { + let user: domain::UserFromStorage = + UserInterface::find_user_by_id(&*state.store, &user_from_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + user.compare_password(request.old_password) + .change_context(UserErrors::InvalidOldPassword)?; + + let new_password_hash = + crate::utils::user::password::generate_password_hash(request.new_password)?; + + let _ = UserInterface::update_user_by_user_id( + &*state.store, + user.get_user_id(), + diesel_models::user::UserUpdate::AccountUpdate { + name: None, + password: Some(new_password_hash), + is_verified: None, + }, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 96bb47ea4e9..84848e03012 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -759,6 +759,7 @@ impl User { .service(web::resource("/signup").route(web::post().to(user_connect_account))) .service(web::resource("/v2/signin").route(web::post().to(user_connect_account))) .service(web::resource("/v2/signup").route(web::post().to(user_connect_account))) + .service(web::resource("/change_password").route(web::post().to(change_password))) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index a9cf7b44a73..219948bdd4d 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -144,7 +144,7 @@ impl From<Flow> for ApiIdentifier { | Flow::GsmRuleUpdate | Flow::GsmRuleDelete => Self::Gsm, - Flow::UserConnectAccount => Self::User, + Flow::UserConnectAccount | Flow::ChangePassword => Self::User, } } } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 0ff11ce087b..7d3d183eda7 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -29,3 +29,21 @@ pub async fn user_connect_account( )) .await } + +pub async fn change_password( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<user_api::ChangePasswordRequest>, +) -> HttpResponse { + let flow = Flow::ChangePassword; + Box::pin(api::server_wrap( + flow, + state.clone(), + &http_req, + json_payload.into_inner(), + |state, user, req| user::change_password(state, req, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 876804b7bb9..e24c7cebcb2 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -14,6 +14,8 @@ use super::authorization::{self, permissions::Permission}; use super::jwt; #[cfg(feature = "olap")] use crate::consts; +#[cfg(feature = "olap")] +use crate::core::errors::UserResult; use crate::{ configs::settings, core::{ @@ -97,7 +99,7 @@ impl AuthToken { role_id: String, settings: &settings::Settings, org_id: String, - ) -> errors::UserResult<String> { + ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); let token_payload = Self { @@ -111,6 +113,14 @@ impl AuthToken { } } +#[derive(Clone)] +pub struct UserFromToken { + pub user_id: String, + pub merchant_id: String, + pub role_id: String, + pub org_id: String, +} + pub trait AuthInfo { fn get_merchant_id(&self) -> Option<&str>; } @@ -421,6 +431,34 @@ where } } +#[cfg(feature = "olap")] +#[async_trait] +impl<A> AuthenticateAndFetch<UserFromToken, A> for JWTAuth +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(UserFromToken, AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + + Ok(( + UserFromToken { + user_id: payload.user_id.clone(), + merchant_id: payload.merchant_id.clone(), + org_id: payload.org_id, + role_id: payload.role_id, + }, + AuthenticationType::MerchantJWT { + merchant_id: payload.merchant_id, + user_id: Some(payload.user_id), + }, + )) + } +} + pub struct JWTAuthMerchantFromRoute { pub merchant_id: String, pub required_permission: Permission, @@ -519,6 +557,53 @@ where } } +pub struct DashboardNoPermissionAuth; + +#[cfg(feature = "olap")] +#[async_trait] +impl<A> AuthenticateAndFetch<UserFromToken, A> for DashboardNoPermissionAuth +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(UserFromToken, AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + + Ok(( + UserFromToken { + user_id: payload.user_id.clone(), + merchant_id: payload.merchant_id.clone(), + org_id: payload.org_id, + role_id: payload.role_id, + }, + AuthenticationType::MerchantJWT { + merchant_id: payload.merchant_id, + user_id: Some(payload.user_id), + }, + )) + } +} + +#[cfg(feature = "olap")] +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for DashboardNoPermissionAuth +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + + Ok(((), AuthenticationType::NoAuth)) + } +} + pub trait ClientSecretFetch { fn get_client_secret(&self) -> Option<&String>; } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 178f837fce1..7978e98e52c 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -255,6 +255,8 @@ pub enum Flow { DecisionManagerDeleteConfig, /// Retrieve Decision Manager Config DecisionManagerRetrieveConfig, + /// Change password flow + ChangePassword, } ///
feat
implement change password for user (#2959)
67bfb1cfecd4a4ad8503eaf57837073bb1980bdd
2024-07-17 22:43:51
Shankar Singh C
feat(router): Add support for passing the domain dynamically in the session call (#5347)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index c04af204493..619f345a333 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -745,6 +745,7 @@ pub struct HeaderPayload { pub x_hs_latency: Option<bool>, pub browser_name: Option<api_enums::BrowserName>, pub x_client_platform: Option<api_enums::ClientPlatform>, + pub x_merchant_domain: Option<String>, } impl HeaderPayload { diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 883203ad99e..4441e349d9f 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -210,6 +210,7 @@ async fn create_applepay_session_token( apple_pay_merchant_cert_key, apple_pay_merchant_identifier, merchant_business_country, + merchant_configured_domain_optional, ) = match apple_pay_metadata { payment_types::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined_metadata, @@ -232,7 +233,7 @@ async fn create_applepay_session_token( let apple_pay_session_request = get_session_request_for_simplified_apple_pay( merchant_identifier.clone(), - session_token_data, + session_token_data.clone(), ); let apple_pay_merchant_cert = state @@ -256,6 +257,7 @@ async fn create_applepay_session_token( apple_pay_merchant_cert_key, merchant_identifier, merchant_business_country, + Some(session_token_data.initiative_context), ) } payment_types::ApplePayCombinedMetadata::Manual { @@ -264,8 +266,10 @@ async fn create_applepay_session_token( } => { logger::info!("Apple pay manual flow"); - let apple_pay_session_request = - get_session_request_for_manual_apple_pay(session_token_data.clone()); + let apple_pay_session_request = get_session_request_for_manual_apple_pay( + session_token_data.clone(), + header_payload.x_merchant_domain.clone(), + ); let merchant_business_country = session_token_data.merchant_business_country; @@ -276,6 +280,7 @@ async fn create_applepay_session_token( session_token_data.certificate_keys, session_token_data.merchant_identifier, merchant_business_country, + session_token_data.initiative_context, ) } }, @@ -284,6 +289,7 @@ async fn create_applepay_session_token( let apple_pay_session_request = get_session_request_for_manual_apple_pay( apple_pay_metadata.session_token_data.clone(), + header_payload.x_merchant_domain.clone(), ); let merchant_business_country = apple_pay_metadata @@ -299,6 +305,7 @@ async fn create_applepay_session_token( .clone(), apple_pay_metadata.session_token_data.merchant_identifier, merchant_business_country, + apple_pay_metadata.session_token_data.initiative_context, ) } }; @@ -383,9 +390,9 @@ async fn create_applepay_session_token( .attach_printable("Failed to obtain apple pay session request")?; let applepay_session_request = build_apple_pay_session_request( state, - apple_pay_session_request, - apple_pay_merchant_cert, - apple_pay_merchant_cert_key, + apple_pay_session_request.clone(), + apple_pay_merchant_cert.clone(), + apple_pay_merchant_cert_key.clone(), )?; let response = services::call_connector_api( @@ -395,10 +402,43 @@ async fn create_applepay_session_token( ) .await; - // logging the error if present in session call response - log_session_response_if_error(&response); + let updated_response = match ( + response.as_ref().ok(), + header_payload.x_merchant_domain.clone(), + ) { + (Some(Err(error)), Some(_)) => { + logger::error!( + "Retry apple pay session call with the merchant configured domain {error:?}" + ); + let merchant_configured_domain = merchant_configured_domain_optional + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed to get initiative_context for apple pay session call retry", + )?; + let apple_pay_retry_session_request = + payment_types::ApplepaySessionRequest { + initiative_context: merchant_configured_domain, + ..apple_pay_session_request + }; + let applepay_retry_session_request = build_apple_pay_session_request( + state, + apple_pay_retry_session_request, + apple_pay_merchant_cert, + apple_pay_merchant_cert_key, + )?; + services::call_connector_api( + state, + applepay_retry_session_request, + "create_apple_pay_session_token", + ) + .await + } + _ => response, + }; - response + // logging the error if present in session call response + log_session_response_if_error(&updated_response); + updated_response .ok() .and_then(|apple_pay_res| { apple_pay_res @@ -454,6 +494,7 @@ fn get_session_request_for_simplified_apple_pay( fn get_session_request_for_manual_apple_pay( session_token_data: payment_types::SessionTokenInfo, + merchant_domain: Option<String>, ) -> RouterResult<payment_types::ApplepaySessionRequest> { let initiative_context = session_token_data .initiative_context @@ -463,7 +504,7 @@ fn get_session_request_for_manual_apple_pay( merchant_identifier: session_token_data.merchant_identifier.clone(), display_name: session_token_data.display_name.clone(), initiative: session_token_data.initiative.to_string(), - initiative_context, + initiative_context: merchant_domain.unwrap_or(initiative_context), }) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 69a76be5bc0..38000f7b664 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -79,6 +79,7 @@ pub mod headers { pub const CONTENT_LENGTH: &str = "Content-Length"; pub const BROWSER_NAME: &str = "x-browser-name"; pub const X_CLIENT_PLATFORM: &str = "x-client-platform"; + pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain"; } pub mod pii { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 9a42916f68d..d32f62ed0be 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -21,7 +21,7 @@ use super::domain; use crate::{ core::errors, headers::{ - BROWSER_NAME, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, + BROWSER_NAME, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, }, services::authentication::get_header_value_by_key, @@ -1157,6 +1157,9 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { .unwrap_or(api_enums::ClientPlatform::Unknown) }); + let x_merchant_domain = + get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string()); + Ok(Self { payment_confirm_source, client_source, @@ -1164,6 +1167,7 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { x_hs_latency: Some(x_hs_latency), browser_name, x_client_platform, + x_merchant_domain, }) } }
feat
Add support for passing the domain dynamically in the session call (#5347)
f9ead15334fab4515ab2498b45c1d319a7fcc53f
2025-03-06 13:36:27
Arindam Sahoo
chore(postman): postman tests fixes (#7159)
false
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json index f1199e53330..3175fdd1dd5 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json @@ -40,7 +40,7 @@ "card": { "card_number": "4242424242424242", "card_exp_month": "01", - "card_exp_year": "25", + "card_exp_year": "35", "card_holder_name": "joseph Doe", "card_cvc": "123" } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Capture/event.test.js index 962c263b0c4..a5befc1b69b 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Capture/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Capture/event.test.js @@ -51,12 +51,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "succeeded" for "status" +// Response body should have value "processing" for "status" if (jsonData?.status) { pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'", + "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("succeeded"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js index 48276c3fd67..c359d358cc3 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js @@ -47,12 +47,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "Succeeded" for "status" +// Response body should have value "processing" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'", + "[POST]::/payments/:id - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("succeeded"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } @@ -82,12 +82,12 @@ if (jsonData?.amount_received) { ); } -// Response body should have value "0" for "amount_capturable" +// Response body should have value full amount for "amount_capturable" if (jsonData?.amount) { pm.test( "[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'", function () { - pm.expect(jsonData.amount_capturable).to.eql(0); + pm.expect(jsonData.amount_capturable).to.eql(jsonData.amount); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Create/event.test.js index b3499d9a0d1..793ef9732aa 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Create/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Create/event.test.js @@ -1,6 +1,6 @@ -// Validate status 2xx -pm.test("[POST]::/refunds - Status code is 2xx", function () { - pm.response.to.be.success; +// Validate status 4xx +pm.test("[POST]::/refunds - Status code is 4xx", function () { + pm.response.to.have.status(400); }); // Validate if response header has matching content-type @@ -24,6 +24,13 @@ if (jsonData?.refund_id) { jsonData.refund_id, ); } else { + pm.collectionVariables.set("refund_id", null); + pm.test( + "[POST]::/refunds - Content check if 'error.message' matches 'This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured'", + function () { + pm.expect(jsonData.error.message).to.eql("This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured"); + }, + ); console.log( "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", ); @@ -48,8 +55,3 @@ if (jsonData?.status) { }, ); } - -// Validate the connector -pm.test("[POST]::/payments - connector", function () { - pm.expect(jsonData.connector).to.eql("cybersource"); -}); diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Retrieve/event.test.js index cce8d2b8ea9..aa1df1bab97 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Retrieve/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Refunds - Retrieve/event.test.js @@ -1,6 +1,6 @@ -// Validate status 2xx -pm.test("[GET]::/refunds/:id - Status code is 2xx", function () { - pm.response.to.be.success; +// Validate status 4xx +pm.test("[POST]::/refunds - Status code is 4xx", function () { + pm.response.to.have.status(404); }); // Validate if response header has matching content-type @@ -16,19 +16,6 @@ try { jsonData = pm.response.json(); } catch (e) {} -// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id -if (jsonData?.refund_id) { - pm.collectionVariables.set("refund_id", jsonData.refund_id); - console.log( - "- use {{refund_id}} as collection variable for value", - jsonData.refund_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", - ); -} - // Response body should have value "pending" for "status" if (jsonData?.status) { pm.test( @@ -39,12 +26,19 @@ if (jsonData?.status) { ); } -// Response body should have value "6540" for "amount" -if (jsonData?.status) { +// Response body should have value "540" for "amount" +if (jsonData?.status && pm.collectionVariables.get("refund_id") !== null) { pm.test( "[POST]::/refunds - Content check if value for 'amount' matches '540'", function () { pm.expect(jsonData.amount).to.eql(540); }, ); +} else { + pm.test( + "[POST]::/refunds - Content check if value for 'error.message' matches 'Refund does not exist in our records.'", + function () { + pm.expect(jsonData.error.message).to.eql("Refund does not exist in our records."); + }, + ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json index dbc19ce0181..1480a1b6c1f 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json @@ -51,7 +51,7 @@ "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", - "card_holder_name": "CLBRW1", + "card_holder_name": "Juspay Hyperswitch", "card_cvc": "737" } }, diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/.meta.json deleted file mode 100644 index f429c3305a2..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/.meta.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "childrenOrder": [ - "Payments-Create", - "Incremental Authorization", - "Payments - Retrieve", - "Payments - Capture", - "Refunds - Create", - "Refunds - Retrieve" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/event.test.js deleted file mode 100644 index dbf6517a0de..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/event.test.js +++ /dev/null @@ -1,15 +0,0 @@ -pm.test("[POST]::/payments:id/incremental_authorizations - Content check if value for 'amount' matches '1001'", function () { - // Parse the response JSON - var jsonData = pm.response.json(); - - // Check if the 'amount' in the response matches the expected value - pm.expect(jsonData.incremental_authorizations[0].amount).to.eql(1001); -}); - -pm.test("[POST]::/payments:id/incremental_authorizations - Content check if value for 'status' matches 'success'", function () { - // Parse the response JSON - var jsonData = pm.response.json(); - - // Check if the 'status' in the response matches the expected value - pm.expect(jsonData.incremental_authorizations[0].status).to.eql("success"); -}); diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/request.json deleted file mode 100644 index 7370c98307d..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/request.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 1001 - } - }, - "url": { - "raw": "{{baseUrl}}/payments/{{payment_id}}/incremental_authorization", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "{{payment_id}}", - "incremental_authorization" - ] - } -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/event.test.js deleted file mode 100644 index 772fa019b9f..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/event.test.js +++ /dev/null @@ -1,81 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments/:id/capture - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test( - "[POST]::/payments/:id/capture - Content-Type is application/json", - function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); - }, -); - -// Validate if response has JSON Body -pm.test("[POST]::/payments/:id/capture - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "succeeded" for "status" -if (jsonData?.status) { - pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'", - function () { - pm.expect(jsonData.status).to.eql("succeeded"); - }, - ); -} - -// Response body should have value "1001" for "amount" -if (jsonData?.amount) { - pm.test( - "[post]:://payments/:id/capture - Content check if value for 'amount' matches '1001'", - function () { - pm.expect(jsonData.amount).to.eql(1001); - }, - ); -} - -// Response body should have value "1001" for "amount_received" -if (jsonData?.amount_received) { - pm.test( - "[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '1001'", - function () { - pm.expect(jsonData.amount_received).to.eql(1001); - }, - ); -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/request.json deleted file mode 100644 index 236b80311e2..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/request.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount_to_capture": 1001, - "statement_descriptor_name": "Joseph", - "statement_descriptor_suffix": "JS" - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/capture", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To capture the funds for an uncaptured payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/event.test.js deleted file mode 100644 index 41883b25ac7..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/event.test.js +++ /dev/null @@ -1,35 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[POST]::/payments - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); -}); - -// Validate if response has JSON Body -pm.test("[POST]::/payments - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - - -// Set response object as internal variable -let jsonData = {}; -try {jsonData = pm.response.json();}catch(e){} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log("- use {{payment_id}} as collection variable for value",jsonData.payment_id); -} else { - console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.'); -}; - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log("- use {{client_secret}} as collection variable for value",jsonData.client_secret); -} else { - console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.'); -}; \ No newline at end of file diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/request.json deleted file mode 100644 index 7a24f361249..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/request.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - }, - { - "key": "Authorization", - "value": "", - "type": "text", - "disabled": true - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 1000, - "currency": "USD", - "confirm": true, - "capture_method": "manual", - "customer_id": "{{customer_id}}", - "email": "[email protected]", - "amount_to_capture": 1000, - "description": "Its my first payment request", - "capture_on": "2022-09-10T10:11:12Z", - "return_url": "https://google.com", - "name": "Preetam", - "phone": "999999999", - "phone_country_code": "+65", - "authentication_type": "no_three_ds", - "payment_method": "card", - "payment_method_type": "debit", - "payment_method_data": { - "card": { - "card_number": "4111111111111111", - "card_exp_month": "09", - "card_exp_year": "2027", - "card_holder_name": "", - "card_cvc": "975" - } - }, - "connector_metadata": { - "noon": { - "order_category": "pay" - } - }, - "browser_info": { - "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", - "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", - "language": "nl-NL", - "color_depth": 24, - "screen_height": 723, - "screen_width": 1536, - "time_zone": 0, - "java_enabled": true, - "java_script_enabled": true, - "ip_address": "128.0.0.1" - }, - "billing": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "PL", - "first_name": "preetam", - "last_name": "revankar" - }, - "phone": { - "number": "9123456789", - "country_code": "+91" - } - }, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "PL", - "first_name": "joseph", - "last_name": "Doe" - }, - "phone": { - "number": "9123456789", - "country_code": "+91" - } - }, - "order_details": [ - { - "product_name": "Apple iphone 15", - "quantity": 1, - "amount": 1000, - "account_name": "transaction_processing" - } - ], - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "request_incremental_authorization": true, - "metadata": { - "count_tickets": 1, - "transaction_number": "5590045" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/event.test.js deleted file mode 100644 index 8cf4006b877..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/event.test.js +++ /dev/null @@ -1,41 +0,0 @@ -// Validate status 2xx -pm.test("[GET]::/payments/:id - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[GET]::/payments/:id - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); -}); - -// Validate if response has JSON Body -pm.test("[GET]::/payments/:id - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try {jsonData = pm.response.json();}catch(e){} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log("- use {{payment_id}} as collection variable for value",jsonData.payment_id); -} else { - console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.'); -}; - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log("- use {{client_secret}} as collection variable for value",jsonData.client_secret); -} else { - console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.'); -}; - - -// Response body should have value "requires_capture" for "status" -if (jsonData?.status) { -pm.test("[POST]::/payments - Content check if value for 'status' matches 'requires_capture'", function() { - pm.expect(jsonData.status).to.eql("requires_capture"); -})}; \ No newline at end of file diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/request.json deleted file mode 100644 index 5b5a18ce870..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/request.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id?expand_attempts=true&force_sync=true", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "query": [ - { - "key": "expand_attempts", - "value": "true" - }, - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/event.test.js deleted file mode 100644 index 5b54b717e2d..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/event.test.js +++ /dev/null @@ -1,50 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/refunds - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[POST]::/refunds - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id -if (jsonData?.refund_id) { - pm.collectionVariables.set("refund_id", jsonData.refund_id); - console.log( - "- use {{refund_id}} as collection variable for value", - jsonData.refund_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", - ); -} - -// Response body should have value "pending" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'status' matches 'pending'", - function () { - pm.expect(jsonData.status).to.eql("pending"); - }, - ); -} - -// Response body should have value "1001" for "amount" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'amount' matches '6540'", - function () { - pm.expect(jsonData.amount).to.eql(1001); - }, - ); -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/request.json deleted file mode 100644 index d48ee5a25bc..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/request.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "payment_id": "{{payment_id}}", - "amount": 1001, - "reason": "Customer returned product", - "refund_type": "instant", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/event.test.js deleted file mode 100644 index 2b906dedf6c..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/event.test.js +++ /dev/null @@ -1,50 +0,0 @@ -// Validate status 2xx -pm.test("[GET]::/refunds/:id - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[GET]::/refunds/:id - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id -if (jsonData?.refund_id) { - pm.collectionVariables.set("refund_id", jsonData.refund_id); - console.log( - "- use {{refund_id}} as collection variable for value", - jsonData.refund_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", - ); -} - -// Response body should have value "pending" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'status' matches 'pending'", - function () { - pm.expect(jsonData.status).to.eql("pending"); - }, - ); -} - -// Response body should have value "1001" for "amount" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'amount' matches '1001'", - function () { - pm.expect(jsonData.amount).to.eql(1001); - }, - ); -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/request.json deleted file mode 100644 index 6c28619e856..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/request.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Incremental Authorization/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant-copy/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Capture/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/List payment methods for a Merchant/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create-copy/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Verify PML for mandate/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/.meta.json deleted file mode 100644 index 522a1196294..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/.meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "childrenOrder": [ - "Payments - Create", - "Incremental Authorization", - "Payments - Retrieve", - "Payments - Capture" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/event.test.js deleted file mode 100644 index dbf6517a0de..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/event.test.js +++ /dev/null @@ -1,15 +0,0 @@ -pm.test("[POST]::/payments:id/incremental_authorizations - Content check if value for 'amount' matches '1001'", function () { - // Parse the response JSON - var jsonData = pm.response.json(); - - // Check if the 'amount' in the response matches the expected value - pm.expect(jsonData.incremental_authorizations[0].amount).to.eql(1001); -}); - -pm.test("[POST]::/payments:id/incremental_authorizations - Content check if value for 'status' matches 'success'", function () { - // Parse the response JSON - var jsonData = pm.response.json(); - - // Check if the 'status' in the response matches the expected value - pm.expect(jsonData.incremental_authorizations[0].status).to.eql("success"); -}); diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/request.json deleted file mode 100644 index 7370c98307d..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/request.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 1001 - } - }, - "url": { - "raw": "{{baseUrl}}/payments/{{payment_id}}/incremental_authorization", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "{{payment_id}}", - "incremental_authorization" - ] - } -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/event.test.js deleted file mode 100644 index 772fa019b9f..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/event.test.js +++ /dev/null @@ -1,81 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments/:id/capture - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test( - "[POST]::/payments/:id/capture - Content-Type is application/json", - function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); - }, -); - -// Validate if response has JSON Body -pm.test("[POST]::/payments/:id/capture - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "succeeded" for "status" -if (jsonData?.status) { - pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'", - function () { - pm.expect(jsonData.status).to.eql("succeeded"); - }, - ); -} - -// Response body should have value "1001" for "amount" -if (jsonData?.amount) { - pm.test( - "[post]:://payments/:id/capture - Content check if value for 'amount' matches '1001'", - function () { - pm.expect(jsonData.amount).to.eql(1001); - }, - ); -} - -// Response body should have value "1001" for "amount_received" -if (jsonData?.amount_received) { - pm.test( - "[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '1001'", - function () { - pm.expect(jsonData.amount_received).to.eql(1001); - }, - ); -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/request.json deleted file mode 100644 index 236b80311e2..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/request.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount_to_capture": 1001, - "statement_descriptor_name": "Joseph", - "statement_descriptor_suffix": "JS" - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/capture", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To capture the funds for an uncaptured payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/event.test.js deleted file mode 100644 index 41883b25ac7..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/event.test.js +++ /dev/null @@ -1,35 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[POST]::/payments - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); -}); - -// Validate if response has JSON Body -pm.test("[POST]::/payments - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - - -// Set response object as internal variable -let jsonData = {}; -try {jsonData = pm.response.json();}catch(e){} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log("- use {{payment_id}} as collection variable for value",jsonData.payment_id); -} else { - console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.'); -}; - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log("- use {{client_secret}} as collection variable for value",jsonData.client_secret); -} else { - console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.'); -}; \ No newline at end of file diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/request.json deleted file mode 100644 index 7a24f361249..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/request.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - }, - { - "key": "Authorization", - "value": "", - "type": "text", - "disabled": true - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 1000, - "currency": "USD", - "confirm": true, - "capture_method": "manual", - "customer_id": "{{customer_id}}", - "email": "[email protected]", - "amount_to_capture": 1000, - "description": "Its my first payment request", - "capture_on": "2022-09-10T10:11:12Z", - "return_url": "https://google.com", - "name": "Preetam", - "phone": "999999999", - "phone_country_code": "+65", - "authentication_type": "no_three_ds", - "payment_method": "card", - "payment_method_type": "debit", - "payment_method_data": { - "card": { - "card_number": "4111111111111111", - "card_exp_month": "09", - "card_exp_year": "2027", - "card_holder_name": "", - "card_cvc": "975" - } - }, - "connector_metadata": { - "noon": { - "order_category": "pay" - } - }, - "browser_info": { - "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", - "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", - "language": "nl-NL", - "color_depth": 24, - "screen_height": 723, - "screen_width": 1536, - "time_zone": 0, - "java_enabled": true, - "java_script_enabled": true, - "ip_address": "128.0.0.1" - }, - "billing": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "PL", - "first_name": "preetam", - "last_name": "revankar" - }, - "phone": { - "number": "9123456789", - "country_code": "+91" - } - }, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "PL", - "first_name": "joseph", - "last_name": "Doe" - }, - "phone": { - "number": "9123456789", - "country_code": "+91" - } - }, - "order_details": [ - { - "product_name": "Apple iphone 15", - "quantity": 1, - "amount": 1000, - "account_name": "transaction_processing" - } - ], - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "request_incremental_authorization": true, - "metadata": { - "count_tickets": 1, - "transaction_number": "5590045" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/event.test.js deleted file mode 100644 index 8cf4006b877..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/event.test.js +++ /dev/null @@ -1,41 +0,0 @@ -// Validate status 2xx -pm.test("[GET]::/payments/:id - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[GET]::/payments/:id - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); -}); - -// Validate if response has JSON Body -pm.test("[GET]::/payments/:id - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try {jsonData = pm.response.json();}catch(e){} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log("- use {{payment_id}} as collection variable for value",jsonData.payment_id); -} else { - console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.'); -}; - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log("- use {{client_secret}} as collection variable for value",jsonData.client_secret); -} else { - console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.'); -}; - - -// Response body should have value "requires_capture" for "status" -if (jsonData?.status) { -pm.test("[POST]::/payments - Content check if value for 'status' matches 'requires_capture'", function() { - pm.expect(jsonData.status).to.eql("requires_capture"); -})}; \ No newline at end of file diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/request.json deleted file mode 100644 index 5b5a18ce870..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/request.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id?expand_attempts=true&force_sync=true", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "query": [ - { - "key": "expand_attempts", - "value": "true" - }, - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates-copy/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario13-Incremental auth/Refunds - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/List - Mandates/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Incremental Authorization/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Capture/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Revoke mandates/Revoke - Mandates/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/request.json similarity index 98% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/request.json index 48692ab2b3e..96fd92bff03 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/request.json @@ -49,7 +49,7 @@ "card": { "card_number": "4000000000001000", "card_exp_month": "01", - "card_exp_year": "25", + "card_exp_year": "35", "card_holder_name": "joseph Doe", "card_cvc": "123" } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario14-Incremental auth for mandates/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Create 3ds payment/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/.meta.json deleted file mode 100644 index 784f5e06db4..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/.meta.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "childrenOrder": [ - "Payments - Create", - "Incremental Authorization", - "Payments - Retrieve", - "Payments - Capture", - "Refunds - Create", - "Refunds - Retrieve" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/event.test.js deleted file mode 100644 index dbf6517a0de..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/event.test.js +++ /dev/null @@ -1,15 +0,0 @@ -pm.test("[POST]::/payments:id/incremental_authorizations - Content check if value for 'amount' matches '1001'", function () { - // Parse the response JSON - var jsonData = pm.response.json(); - - // Check if the 'amount' in the response matches the expected value - pm.expect(jsonData.incremental_authorizations[0].amount).to.eql(1001); -}); - -pm.test("[POST]::/payments:id/incremental_authorizations - Content check if value for 'status' matches 'success'", function () { - // Parse the response JSON - var jsonData = pm.response.json(); - - // Check if the 'status' in the response matches the expected value - pm.expect(jsonData.incremental_authorizations[0].status).to.eql("success"); -}); diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/request.json deleted file mode 100644 index 7370c98307d..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Incremental Authorization/request.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "method": "POST", - "header": [], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 1001 - } - }, - "url": { - "raw": "{{baseUrl}}/payments/{{payment_id}}/incremental_authorization", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - "{{payment_id}}", - "incremental_authorization" - ] - } -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/event.test.js deleted file mode 100644 index 70312d39fe2..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/event.test.js +++ /dev/null @@ -1,81 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments/:id/capture - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test( - "[POST]::/payments/:id/capture - Content-Type is application/json", - function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); - }, -); - -// Validate if response has JSON Body -pm.test("[POST]::/payments/:id/capture - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log( - "- use {{payment_id}} as collection variable for value", - jsonData.payment_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.", - ); -} - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log( - "- use {{client_secret}} as collection variable for value", - jsonData.client_secret, - ); -} else { - console.log( - "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", - ); -} - -// Response body should have value "partially_captured" for "status" -if (jsonData?.status) { - pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'", - function () { - pm.expect(jsonData.status).to.eql("partially_captured"); - }, - ); -} - -// Response body should have value "1001" for "amount" -if (jsonData?.amount) { - pm.test( - "[post]:://payments/:id/capture - Content check if value for 'amount' matches '1001'", - function () { - pm.expect(jsonData.amount).to.eql(1001); - }, - ); -} - -// Response body should have value "500" for "amount_received" -if (jsonData?.amount_received) { - pm.test( - "[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '500'", - function () { - pm.expect(jsonData.amount_received).to.eql(500); - }, - ); -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/request.json deleted file mode 100644 index 4f054db2954..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/request.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount_to_capture": 500, - "statement_descriptor_name": "Joseph", - "statement_descriptor_suffix": "JS" - } - }, - "url": { - "raw": "{{baseUrl}}/payments/:id/capture", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "capture" - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}", - "description": "(Required) unique payment id" - } - ] - }, - "description": "To capture the funds for an uncaptured payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/event.test.js deleted file mode 100644 index 41883b25ac7..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/event.test.js +++ /dev/null @@ -1,35 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/payments - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[POST]::/payments - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); -}); - -// Validate if response has JSON Body -pm.test("[POST]::/payments - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - - -// Set response object as internal variable -let jsonData = {}; -try {jsonData = pm.response.json();}catch(e){} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log("- use {{payment_id}} as collection variable for value",jsonData.payment_id); -} else { - console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.'); -}; - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log("- use {{client_secret}} as collection variable for value",jsonData.client_secret); -} else { - console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.'); -}; \ No newline at end of file diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/request.json deleted file mode 100644 index 2bb53f5fc53..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/request.json +++ /dev/null @@ -1,150 +0,0 @@ -{ - "auth": { - "type": "apikey", - "apikey": [ - { - "key": "value", - "value": "{{api_key}}", - "type": "string" - }, - { - "key": "key", - "value": "api-key", - "type": "string" - }, - { - "key": "in", - "value": "header", - "type": "string" - } - ] - }, - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - }, - { - "key": "Authorization", - "value": "", - "type": "text", - "disabled": true - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "amount": 1000, - "currency": "USD", - "confirm": true, - "capture_method": "manual", - "customer_id": "{{customer_id}}", - "email": "[email protected]", - "amount_to_capture": 1000, - "description": "Its my first payment request", - "capture_on": "2022-09-10T10:11:12Z", - "return_url": "https://google.com", - "name": "Preetam", - "phone": "999999999", - "phone_country_code": "+65", - "authentication_type": "no_three_ds", - "payment_method": "card", - "payment_method_type": "debit", - "payment_method_data": { - "card": { - "card_number": "4111111111111111", - "card_exp_month": "09", - "card_exp_year": "2027", - "card_holder_name": "", - "card_cvc": "975" - } - }, - "connector_metadata": { - "noon": { - "order_category": "pay" - } - }, - "browser_info": { - "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", - "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", - "language": "nl-NL", - "color_depth": 24, - "screen_height": 723, - "screen_width": 1536, - "time_zone": 0, - "java_enabled": true, - "java_script_enabled": true, - "ip_address": "128.0.0.1" - }, - "billing": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "PL", - "first_name": "preetam", - "last_name": "revankar" - }, - "phone": { - "number": "9123456789", - "country_code": "+91" - } - }, - "shipping": { - "address": { - "line1": "1467", - "line2": "Harrison Street", - "line3": "Harrison Street", - "city": "San Fransico", - "state": "California", - "zip": "94122", - "country": "PL", - "first_name": "joseph", - "last_name": "Doe" - }, - "phone": { - "number": "9123456789", - "country_code": "+91" - } - }, - "order_details": [ - { - "product_name": "Apple iphone 15", - "quantity": 1, - "amount": 1000, - "account_name": "transaction_processing" - } - ], - "statement_descriptor_name": "joseph", - "statement_descriptor_suffix": "JS", - "request_incremental_authorization": true, - "metadata": { - "count_tickets": 1, - "transaction_number": "5590045" - } - } - }, - "url": { - "raw": "{{baseUrl}}/payments", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments" - ] - }, - "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/event.test.js deleted file mode 100644 index 8cf4006b877..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/event.test.js +++ /dev/null @@ -1,41 +0,0 @@ -// Validate status 2xx -pm.test("[GET]::/payments/:id - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[GET]::/payments/:id - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); -}); - -// Validate if response has JSON Body -pm.test("[GET]::/payments/:id - Response has JSON Body", function () { - pm.response.to.have.jsonBody(); -}); - -// Set response object as internal variable -let jsonData = {}; -try {jsonData = pm.response.json();}catch(e){} - -// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id -if (jsonData?.payment_id) { - pm.collectionVariables.set("payment_id", jsonData.payment_id); - console.log("- use {{payment_id}} as collection variable for value",jsonData.payment_id); -} else { - console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.'); -}; - -// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret -if (jsonData?.client_secret) { - pm.collectionVariables.set("client_secret", jsonData.client_secret); - console.log("- use {{client_secret}} as collection variable for value",jsonData.client_secret); -} else { - console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.'); -}; - - -// Response body should have value "requires_capture" for "status" -if (jsonData?.status) { -pm.test("[POST]::/payments - Content check if value for 'status' matches 'requires_capture'", function() { - pm.expect(jsonData.status).to.eql("requires_capture"); -})}; \ No newline at end of file diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/request.json deleted file mode 100644 index 5b5a18ce870..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/request.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/payments/:id?expand_attempts=true&force_sync=true", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], - "query": [ - { - "key": "expand_attempts", - "value": "true" - }, - { - "key": "force_sync", - "value": "true" - } - ], - "variable": [ - { - "key": "id", - "value": "{{payment_id}}" - } - ] - }, - "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/event.test.js deleted file mode 100644 index 98db0f1b7a5..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/event.test.js +++ /dev/null @@ -1,50 +0,0 @@ -// Validate status 2xx -pm.test("[POST]::/refunds - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[POST]::/refunds - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id -if (jsonData?.refund_id) { - pm.collectionVariables.set("refund_id", jsonData.refund_id); - console.log( - "- use {{refund_id}} as collection variable for value", - jsonData.refund_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", - ); -} - -// Response body should have value "pending" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'status' matches 'pending'", - function () { - pm.expect(jsonData.status).to.eql("pending"); - }, - ); -} - -// Response body should have value "500" for "amount" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'amount' matches '500'", - function () { - pm.expect(jsonData.amount).to.eql(500); - }, - ); -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/request.json deleted file mode 100644 index 241a13121e9..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/request.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - }, - { - "key": "Accept", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "options": { - "raw": { - "language": "json" - } - }, - "raw_json_formatted": { - "payment_id": "{{payment_id}}", - "amount": 500, - "reason": "Customer returned product", - "refund_type": "instant", - "metadata": { - "udf1": "value1", - "new_customer": "true", - "login_date": "2019-09-10T10:11:12Z" - } - } - }, - "url": { - "raw": "{{baseUrl}}/refunds", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds" - ] - }, - "description": "To create a refund against an already processed payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/event.test.js deleted file mode 100644 index 437b5a3c487..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/event.test.js +++ /dev/null @@ -1,50 +0,0 @@ -// Validate status 2xx -pm.test("[GET]::/refunds/:id - Status code is 2xx", function () { - pm.response.to.be.success; -}); - -// Validate if response header has matching content-type -pm.test("[GET]::/refunds/:id - Content-Type is application/json", function () { - pm.expect(pm.response.headers.get("Content-Type")).to.include( - "application/json", - ); -}); - -// Set response object as internal variable -let jsonData = {}; -try { - jsonData = pm.response.json(); -} catch (e) {} - -// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id -if (jsonData?.refund_id) { - pm.collectionVariables.set("refund_id", jsonData.refund_id); - console.log( - "- use {{refund_id}} as collection variable for value", - jsonData.refund_id, - ); -} else { - console.log( - "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", - ); -} - -// Response body should have value "pending" for "status" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'status' matches 'pending'", - function () { - pm.expect(jsonData.status).to.eql("pending"); - }, - ); -} - -// Response body should have value "500" for "amount" -if (jsonData?.status) { - pm.test( - "[POST]::/refunds - Content check if value for 'amount' matches '500'", - function () { - pm.expect(jsonData.amount).to.eql(500); - }, - ); -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/request.json deleted file mode 100644 index 6c28619e856..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/request.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "method": "GET", - "header": [ - { - "key": "Accept", - "value": "application/json" - } - ], - "url": { - "raw": "{{baseUrl}}/refunds/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "refunds", - ":id" - ], - "variable": [ - { - "key": "id", - "value": "{{refund_id}}", - "description": "(Required) unique refund id" - } - ] - }, - "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment" -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Capture/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Create 3ds mandate/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/event.prerequest.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Confirm/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve-copy/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario15-Incremental auth with partial capture/Refunds - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant-copy/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/response.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Create a mandate without customer acceptance/Recurring Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Capture/event.test.js index 44a6caa3e3a..c48127e8cd0 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Capture/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Capture/event.test.js @@ -50,12 +50,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "succeeded" for "status" +// Response body should have value "processing" for "status" while capturing a payment manually if (jsonData?.status) { pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'", + "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("succeeded"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Retrieve/event.test.js index f88687240aa..c64b962a3cf 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Retrieve/event.test.js @@ -47,12 +47,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "succeeded" for "status" +// Response body should have value "processing" for "status" while capturing a payment manually if (jsonData?.status) { pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", + "[POST]::/payments - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("succeeded"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Capture/event.test.js index ad7ec549dd5..7ac33d76eae 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Capture/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Capture/event.test.js @@ -50,12 +50,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "succeeded" for "status" +// Response body should have value "processing" for "status" while partially capturing a payment if (jsonData?.status) { pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'", + "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("partially_captured"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Retrieve/event.test.js index 27ce6277ba8..f256a9a417f 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario4a-Create payment with partial capture/Payments - Retrieve/event.test.js @@ -47,12 +47,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "succeeded" for "status" +// Response body should have value "processing" for "status" while partially capturing a payment if (jsonData?.status) { pm.test( - "[POST]::/payments - Content check if value for 'status' matches 'partially_captured'", + "[POST]::/payments - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("partially_captured"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Capture/event.test.js index 44a6caa3e3a..b5c042e78c8 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Capture/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Capture/event.test.js @@ -50,12 +50,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "succeeded" for "status" +// Response body should have value "processing" for "status" in case of Manual capture for recurring payments if (jsonData?.status) { pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'", + "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("succeeded"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Retrieve-copy/event.test.js index fe8fa706b96..952a7f0bfb4 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Retrieve-copy/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario7a-Manual capture for recurring payments/Payments - Retrieve-copy/event.test.js @@ -48,12 +48,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "Succeeded" for "status" +// Response body should have value "processing" for "status" while retrieving a payment captured manually if (jsonData?.status) { pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'", + "[POST]::/payments/:id - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("succeeded"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json index 03891f4045c..35bf67cdd4e 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json +++ b/postman/collection-dir/cybersource/Flow Testcases/QuickStart/Payment Connector - Create/request.json @@ -48,6 +48,7 @@ }, "test_mode": false, "disabled": false, + "metadata": {}, "payment_methods_enabled": [ { "payment_method": "card", diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/List payment methods for a Merchant/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/event.test.js similarity index 93% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/event.test.js index ad7ec549dd5..f8451fe02ef 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/event.test.js @@ -50,12 +50,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "succeeded" for "status" +// Response body should have value "processing" for "status" if (jsonData?.status) { pm.test( - "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'", + "[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("partially_captured"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Capture/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create-copy/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario16-Verify PML for mandate/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/event.test.js similarity index 91% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/event.test.js index 550547e3399..678c058ebfd 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/event.test.js @@ -47,12 +47,12 @@ if (jsonData?.client_secret) { ); } -// Response body should have value "Succeeded" for "status" +// Response body should have value "processing" for "status" if (jsonData?.status) { pm.test( - "[POST]::/payments/:id - Content check if value for 'status' matches 'partially_captured'", + "[POST]::/payments/:id - Content check if value for 'status' matches 'processing'", function () { - pm.expect(jsonData.status).to.eql("partially_captured"); + pm.expect(jsonData.status).to.eql("processing"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates-copy/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/event.test.js similarity index 74% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/event.test.js index 07721f97af3..6809c1e704c 100644 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/event.test.js +++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/event.test.js @@ -47,12 +47,12 @@ if (jsonData?.error?.type) { ); } -// Response body should have value "The refund amount exceeds the amount captured" for "error message" +// Response body should have value "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured" for "error message" if (jsonData?.error?.type) { pm.test( - "[POST]::/payments/:id/confirm - Content check if value for 'error.message' matches 'The refund amount exceeds the amount captured'", + "[POST]::/payments/:id/confirm - Content check if value for 'error.message' matches 'This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured'", function () { - pm.expect(jsonData.error.message).to.eql("The refund amount exceeds the amount captured"); + pm.expect(jsonData.error.message).to.eql("This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured"); }, ); } diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Refund exceeds amount captured/Refunds - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/List - Mandates/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates-copy/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario17-Revoke mandates/Revoke - Mandates/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Revoke for revoked mandates/Revoke - Mandates/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario18-Create 3ds payment/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Recurring Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds mandate/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Confirm/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Recurring payment for revoked mandates/Revoke - Mandates/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Revoke - Mandates/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/event.prerequest.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/event.prerequest.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Setup_future_usage is off_session for normal payments/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.prerequest.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.prerequest.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.prerequest.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/List payment methods for a Customer/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/event.prerequest.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/event.prerequest.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/event.prerequest.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/event.prerequest.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Confirm/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/event.prerequest.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/event.prerequest.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/event.prerequest.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/event.prerequest.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is null for normal payments/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Confirm/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is on_session for mandates payments -confirm false/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/List payment methods for a Customer/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Confirm/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario16-Setup_future_usage is null for normal payments/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve-copy/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create a mandate without customer acceptance/Recurring Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario6-Refund exceeds amount/Refunds - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Payments - Retrieve/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund exceeds amount/Refunds - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Capture/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates-copy/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario7-Refund for unsuccessful payment/Refunds - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Revoke - Mandates/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Refund exceeds amount captured/Refunds - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Payments - Retrieve/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Create/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Payments - Retrieve/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Create a recurring payment with greater mandate amount/Recurring Payments - Create/response.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Payments - Retrieve/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario8-Refund for unsuccessful payment/Refunds - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Retrieve/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/.event.meta.json deleted file mode 100644 index 688c85746ef..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/.event.meta.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "eventOrder": [ - "event.test.js" - ] -} diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/response.json deleted file mode 100644 index fe51488c706..00000000000 --- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Recurring Payments - Create/response.json +++ /dev/null @@ -1 +0,0 @@ -[] diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Setup_future_usage is off_session for normal payments/.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/.event.meta.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/.event.meta.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario12-Revoke for revoked mandates/Payments - Retrieve/.event.meta.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/.event.meta.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/event.test.js b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/event.test.js similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/event.test.js rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/event.test.js diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/request.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario10-Manual multiple capture/Payments - Create/request.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/request.json diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/response.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/response.json similarity index 100% rename from postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario13-Recurring payment for revoked mandates/Recurring Payments - Create/response.json rename to postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Manual multiple capture/Payments - Create/response.json diff --git a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js index b62f99d61fd..b07811aed26 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js +++ b/postman/collection-dir/nmi/Flow Testcases/Variation Cases/Scenario9-Create a mandate payment/Payments - Create/event.test.js @@ -36,7 +36,7 @@ if (jsonData?.error?.message) { pm.test( "[POST]::/payments/:id/confirm - Content check if value for 'error.reason' matches ' mandate payment is not supported by nmi'" , function () { - pm.expect(jsonData.error.reason).to.eql(" mandate payment is not supported by nmi"); + pm.expect(jsonData.error.reason).to.eql("credit mandate payment is not supported by nmi"); }, ); } \ No newline at end of file diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario6-Refund full payment/Payments - Retrieve/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario6-Refund full payment/Payments - Retrieve/event.test.js index 0652a2d92fd..999814916d9 100644 --- a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario6-Refund full payment/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario6-Refund full payment/Payments - Retrieve/event.test.js @@ -68,4 +68,4 @@ if (jsonData?.status) { pm.expect(jsonData.status).to.eql("succeeded"); }, ); -} +} \ No newline at end of file diff --git a/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario6-Refund full payment/Refunds - Create/event.prerequest.js b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario6-Refund full payment/Refunds - Create/event.prerequest.js new file mode 100644 index 00000000000..8b106df67e0 --- /dev/null +++ b/postman/collection-dir/trustpay/Flow Testcases/Happy Cases/Scenario6-Refund full payment/Refunds - Create/event.prerequest.js @@ -0,0 +1,4 @@ +// Add a delay of 10 seconds +setTimeout(function () { + console.log("Delay of 10 seconds completed."); +}, 10000); \ No newline at end of file diff --git a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Create/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Create/event.test.js index a6947db94c0..efb9b6ee803 100644 --- a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Create/event.test.js +++ b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Create/event.test.js @@ -59,3 +59,13 @@ if (jsonData?.client_secret) { "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } + +// Response body should have value "succeeded" for "status" +if (jsonData?.status) { + pm.test( + "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", + function () { + pm.expect(jsonData.status).to.eql("succeeded"); + }, + ); +} \ No newline at end of file diff --git a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js index d0a02af7436..58ce99b81da 100644 --- a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js +++ b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js @@ -59,3 +59,13 @@ if (jsonData?.client_secret) { "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } + +// Response body should have value "Succeeded" for "status" +if (jsonData?.status) { + pm.test( + "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'", + function () { + pm.expect(jsonData.status).to.eql("succeeded"); + }, + ); +} \ No newline at end of file diff --git a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Create/event.prerequest.js b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Create/event.prerequest.js new file mode 100644 index 00000000000..8b106df67e0 --- /dev/null +++ b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Create/event.prerequest.js @@ -0,0 +1,4 @@ +// Add a delay of 10 seconds +setTimeout(function () { + console.log("Delay of 10 seconds completed."); +}, 10000); \ No newline at end of file diff --git a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Create/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Create/event.test.js index dbc930608cb..05e511d3135 100644 --- a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Create/event.test.js +++ b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Create/event.test.js @@ -28,3 +28,23 @@ if (jsonData?.refund_id) { "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", ); } + +// Response body should have value "succeeded" for "status" +if (jsonData?.status) { + pm.test( + "[POST]::/refunds - Content check if value for 'status' matches 'succeeded'", + function () { + pm.expect(jsonData.status).to.eql("succeeded"); + }, + ); +} + +// Response body should have value "600" for "amount" +if (jsonData?.status) { + pm.test( + "[POST]::/refunds - Content check if value for 'amount' matches '600'", + function () { + pm.expect(jsonData.amount).to.eql(600); + }, + ); +} diff --git a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js index bbd8e544e2c..0b562c615dc 100644 --- a/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js +++ b/postman/collection-dir/trustpay/Flow Testcases/QuickStart/Refunds - Retrieve/event.test.js @@ -28,3 +28,23 @@ if (jsonData?.refund_id) { "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.", ); } + +// Response body should have value "succeeded" for "status" +if (jsonData?.status) { + pm.test( + "[POST]::/refunds - Content check if value for 'status' matches 'succeeded'", + function () { + pm.expect(jsonData.status).to.eql("succeeded"); + }, + ); +} + +// Response body should have value "600" for "amount" +if (jsonData?.status) { + pm.test( + "[POST]::/refunds - Content check if value for 'amount' matches '600'", + function () { + pm.expect(jsonData.amount).to.eql(600); + }, + ); +}
chore
postman tests fixes (#7159)
5afd2c2a67f325960668f2b27c3519581f5877e1
2024-03-22 05:48:46
github-actions
chore(version): 2024.03.22.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5434e83f0a1..e967966117d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.03.22.0 + +### Features + +- **events:** Add APIs to list webhook events and webhook delivery attempts ([#4131](https://github.com/juspay/hyperswitch/pull/4131)) ([`14e1bba`](https://github.com/juspay/hyperswitch/commit/14e1bbaf071d1178f91124fe85580f178cb1cf96)) +- **global-search-regex-escape:** Escape reserved characters which break global search query ([#4135](https://github.com/juspay/hyperswitch/pull/4135)) ([`4f8461b`](https://github.com/juspay/hyperswitch/commit/4f8461b2a949fd2a6d24b8b42f1bf8bab55cfeeb)) + +### Miscellaneous Tasks + +- Update Slack workspace URL ([#4168](https://github.com/juspay/hyperswitch/pull/4168)) ([`75b4bac`](https://github.com/juspay/hyperswitch/commit/75b4bacc984d11cb755a8c36821ec41d3f1e2187)) + +**Full Changelog:** [`2024.03.21.1...2024.03.22.0`](https://github.com/juspay/hyperswitch/compare/2024.03.21.1...2024.03.22.0) + +- - - + ## 2024.03.21.1 ### Features
chore
2024.03.22.0
680505f21ad0c809f007773517dd444b211f4c99
2023-09-18 15:36:06
BallaNitesh
fix: remove x-request-id from headers before connector calls (#2182)
false
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index dc25d567864..b10feebe16f 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -453,17 +453,7 @@ pub async fn send_request( request.certificate_key, )?; - let mut headers_with_request_id = request.headers; - headers_with_request_id.insert(( - crate::headers::X_REQUEST_ID.to_string(), - state - .api_client - .get_request_id() - .ok_or(errors::ApiClientError::InternalServerErrorReceived) - .into_report()? - .into(), - )); - let headers = headers_with_request_id.construct_header_map()?; + let headers = request.headers.construct_header_map()?; let metrics_tag = router_env::opentelemetry::KeyValue { key: consts::METRICS_HOST_TAG_NAME.into(), value: url.host_str().unwrap_or_default().to_string().into(),
fix
remove x-request-id from headers before connector calls (#2182)
6db60b8cd4319d0246c72494fa65082108ffd06e
2023-09-26 12:01:25
chikke srujan
refactor(connector): [bluesnap]Enhance currency Mapping with ConnectorCurrencyCommon Trait (#2193)
false
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index 04206dd80e5..9819b91246e 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -63,6 +63,10 @@ impl ConnectorCommon for Bluesnap { "bluesnap" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -405,7 +409,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = bluesnap::BluesnapCaptureRequest::try_from(req)?; + let connector_router_data = bluesnap::BluesnapRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount_to_capture, + req, + ))?; + let connector_req = bluesnap::BluesnapCaptureRequest::try_from(&connector_router_data)?; let bluesnap_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<bluesnap::BluesnapCaptureRequest>::encode_to_string_of_json, @@ -584,9 +594,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P &self, req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_router_data = bluesnap::BluesnapRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; match req.is_three_ds() && req.request.is_card() { true => { - let connector_req = bluesnap::BluesnapPaymentsTokenRequest::try_from(req)?; + let connector_req = + bluesnap::BluesnapPaymentsTokenRequest::try_from(&connector_router_data)?; let bluesnap_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json, @@ -595,7 +612,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P Ok(Some(bluesnap_req)) } _ => { - let connector_req = bluesnap::BluesnapPaymentsRequest::try_from(req)?; + let connector_req = + bluesnap::BluesnapPaymentsRequest::try_from(&connector_router_data)?; let bluesnap_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json, @@ -711,7 +729,14 @@ impl &self, req: &types::PaymentsCompleteAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = bluesnap::BluesnapCompletePaymentsRequest::try_from(req)?; + let connector_router_data = bluesnap::BluesnapRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + bluesnap::BluesnapCompletePaymentsRequest::try_from(&connector_router_data)?; let bluesnap_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json, @@ -802,7 +827,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = bluesnap::BluesnapRefundRequest::try_from(req)?; + let connector_router_data = bluesnap::BluesnapRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = bluesnap::BluesnapRefundRequest::try_from(&connector_router_data)?; let bluesnap_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<bluesnap::BluesnapRefundRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 80dc3668ffc..d2e1efa527a 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -21,6 +21,37 @@ use crate::{ utils::{Encode, OptionExt}, }; +#[derive(Debug, Serialize)] +pub struct BluesnapRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for BluesnapRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapPaymentsRequest { @@ -168,10 +199,14 @@ pub struct BluesnapPaymentsTokenRequest { exp_date: Secret<String>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsTokenRequest { +impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> + for BluesnapPaymentsTokenRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data { + fn try_from( + item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data { api::PaymentMethodData::Card(ref ccard) => Ok(Self { cc_number: ccard.card_number.clone(), exp_date: ccard.get_expiry_date_as_mmyyyy("/"), @@ -197,170 +232,180 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsTokenReque } } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest { +impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for BluesnapPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let auth_mode = match item.request.capture_method { + fn try_from( + item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let auth_mode = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly, _ => BluesnapTxnType::AuthCapture, }; - let (payment_method, card_holder_info) = match item.request.payment_method_data.clone() { - api::PaymentMethodData::Card(ref ccard) => Ok(( - PaymentMethodDetails::CreditCard(Card { - card_number: ccard.card_number.clone(), - expiration_month: ccard.card_exp_month.clone(), - expiration_year: ccard.get_expiry_year_4_digit(), - security_code: ccard.card_cvc.clone(), - }), - get_card_holder_info(item.get_billing_address()?, item.request.get_email()?)?, - )), - api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { - api_models::payments::WalletData::GooglePay(payment_method_data) => { - let gpay_object = Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( - &BluesnapGooglePayObject { - payment_method_data: utils::GooglePayWalletData::from( - payment_method_data, - ), - }, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(( - PaymentMethodDetails::Wallet(BluesnapWallet { - wallet_type: BluesnapWalletTypes::GooglePay, - encoded_payment_token: Secret::new( - consts::BASE64_ENGINE.encode(gpay_object), - ), - }), - None, - )) - } - api_models::payments::WalletData::ApplePay(payment_method_data) => { - let apple_pay_payment_data = payment_method_data - .get_applepay_decoded_payment_data() - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data - .expose()[..] - .as_bytes() - .parse_struct("ApplePayEncodedPaymentData") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - let billing = item - .address - .billing - .to_owned() - .get_required_value("billing") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "billing", - })?; - - let billing_address = billing - .address - .get_required_value("billing_address") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "billing", - })?; - - let mut address = Vec::new(); - if let Some(add) = billing_address.line1.to_owned() { - address.push(add) + let (payment_method, card_holder_info) = + match item.router_data.request.payment_method_data.clone() { + api::PaymentMethodData::Card(ref ccard) => Ok(( + PaymentMethodDetails::CreditCard(Card { + card_number: ccard.card_number.clone(), + expiration_month: ccard.card_exp_month.clone(), + expiration_year: ccard.get_expiry_year_4_digit(), + security_code: ccard.card_cvc.clone(), + }), + get_card_holder_info( + item.router_data.get_billing_address()?, + item.router_data.request.get_email()?, + )?, + )), + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + api_models::payments::WalletData::GooglePay(payment_method_data) => { + let gpay_object = + Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( + &BluesnapGooglePayObject { + payment_method_data: utils::GooglePayWalletData::from( + payment_method_data, + ), + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(( + PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::GooglePay, + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(gpay_object), + ), + }), + None, + )) } - if let Some(add) = billing_address.line2.to_owned() { - address.push(add) + api_models::payments::WalletData::ApplePay(payment_method_data) => { + let apple_pay_payment_data = payment_method_data + .get_applepay_decoded_payment_data() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let apple_pay_payment_data: ApplePayEncodedPaymentData = + apple_pay_payment_data.expose()[..] + .as_bytes() + .parse_struct("ApplePayEncodedPaymentData") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let billing = item + .router_data + .address + .billing + .to_owned() + .get_required_value("billing") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "billing", + })?; + + let billing_address = billing + .address + .get_required_value("billing_address") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "billing", + })?; + + let mut address = Vec::new(); + if let Some(add) = billing_address.line1.to_owned() { + address.push(add) + } + if let Some(add) = billing_address.line2.to_owned() { + address.push(add) + } + if let Some(add) = billing_address.line3.to_owned() { + address.push(add) + } + + let apple_pay_object = + Encode::<EncodedPaymentToken>::encode_to_string_of_json( + &EncodedPaymentToken { + token: ApplepayPaymentData { + payment_data: apple_pay_payment_data, + payment_method: payment_method_data + .payment_method + .to_owned() + .into(), + transaction_identifier: payment_method_data + .transaction_identifier, + }, + billing_contact: BillingDetails { + country_code: billing_address.country, + address_lines: Some(address), + family_name: billing_address.last_name.to_owned(), + given_name: billing_address.first_name.to_owned(), + postal_code: billing_address.zip, + }, + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + Ok(( + PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::ApplePay, + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(apple_pay_object), + ), + }), + get_card_holder_info( + item.router_data.get_billing_address()?, + item.router_data.request.get_email()?, + )?, + )) } - if let Some(add) = billing_address.line3.to_owned() { - address.push(add) + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) + | payments::WalletData::WeChatPayQr(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("bluesnap"), + )) } - - let apple_pay_object = Encode::<EncodedPaymentToken>::encode_to_string_of_json( - &EncodedPaymentToken { - token: ApplepayPaymentData { - payment_data: apple_pay_payment_data, - payment_method: payment_method_data - .payment_method - .to_owned() - .into(), - transaction_identifier: payment_method_data.transaction_identifier, - }, - billing_contact: BillingDetails { - country_code: billing_address.country, - address_lines: Some(address), - family_name: billing_address.last_name.to_owned(), - given_name: billing_address.first_name.to_owned(), - postal_code: billing_address.zip, - }, - }, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - Ok(( - PaymentMethodDetails::Wallet(BluesnapWallet { - wallet_type: BluesnapWalletTypes::ApplePay, - encoded_payment_token: Secret::new( - consts::BASE64_ENGINE.encode(apple_pay_object), - ), - }), - get_card_holder_info( - item.get_billing_address()?, - item.request.get_email()?, - )?, - )) - } - payments::WalletData::AliPayQr(_) - | payments::WalletData::AliPayRedirect(_) - | payments::WalletData::AliPayHkRedirect(_) - | payments::WalletData::MomoRedirect(_) - | payments::WalletData::KakaoPayRedirect(_) - | payments::WalletData::GoPayRedirect(_) - | payments::WalletData::GcashRedirect(_) - | payments::WalletData::ApplePayRedirect(_) - | payments::WalletData::ApplePayThirdPartySdk(_) - | payments::WalletData::DanaRedirect {} - | payments::WalletData::GooglePayRedirect(_) - | payments::WalletData::GooglePayThirdPartySdk(_) - | payments::WalletData::MbWayRedirect(_) - | payments::WalletData::MobilePayRedirect(_) - | payments::WalletData::PaypalRedirect(_) - | payments::WalletData::PaypalSdk(_) - | payments::WalletData::SamsungPay(_) - | payments::WalletData::TwintRedirect {} - | payments::WalletData::VippsRedirect {} - | payments::WalletData::TouchNGoRedirect(_) - | payments::WalletData::WeChatPayRedirect(_) - | payments::WalletData::CashappQr(_) - | payments::WalletData::SwishQr(_) - | payments::WalletData::WeChatPayQr(_) => { + }, + payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), )) } - }, - payments::PaymentMethodData::PayLater(_) - | payments::PaymentMethodData::BankRedirect(_) - | payments::PaymentMethodData::BankDebit(_) - | payments::PaymentMethodData::BankTransfer(_) - | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::MandatePayment - | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) - | payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("bluesnap"), - )) - } - }?; + }?; Ok(Self { - amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + amount: item.amount.to_owned(), payment_method, - currency: item.request.currency, + currency: item.router_data.request.currency, card_transaction_type: auth_mode, three_d_secure: None, transaction_fraud_info: Some(TransactionFraudInfo { - fraud_session_id: item.payment_id.clone(), + fraud_session_id: item.router_data.payment_id.clone(), }), card_holder_info, - merchant_transaction_id: Some(item.connector_request_reference_id.clone()), + merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()), }) } } @@ -493,10 +538,15 @@ pub struct BluesnapCompletePaymentsRequest { merchant_transaction_id: Option<String>, } -impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for BluesnapCompletePaymentsRequest { +impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for BluesnapCompletePaymentsRequest +{ type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { let redirection_response: BluesnapRedirectionResponse = item + .router_data .request .redirect_response .as_ref() @@ -508,6 +558,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for BluesnapCompletePa .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let pf_token = item + .router_data .request .redirect_response .clone() @@ -528,13 +579,13 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for BluesnapCompletePa .parse_struct("BluesnapThreeDsResult") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let auth_mode = match item.request.capture_method { + let auth_mode = match item.router_data.request.capture_method { Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly, _ => BluesnapTxnType::AuthCapture, }; Ok(Self { - amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, - currency: item.request.currency, + amount: item.amount.to_owned(), + currency: item.router_data.request.currency, card_transaction_type: auth_mode, three_d_secure: Some(BluesnapThreeDSecureInfo { three_d_secure_reference_id: redirection_result @@ -545,13 +596,13 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for BluesnapCompletePa .three_d_secure_reference_id, }), transaction_fraud_info: Some(TransactionFraudInfo { - fraud_session_id: item.payment_id.clone(), + fraud_session_id: item.router_data.payment_id.clone(), }), card_holder_info: get_card_holder_info( - item.get_billing_address()?, - item.request.get_email()?, + item.router_data.get_billing_address()?, + item.router_data.request.get_email()?, )?, - merchant_transaction_id: Some(item.connector_request_reference_id.clone()), + merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()), pf_token, }) } @@ -610,17 +661,21 @@ pub struct BluesnapCaptureRequest { amount: Option<String>, } -impl TryFrom<&types::PaymentsCaptureRouterData> for BluesnapCaptureRequest { +impl TryFrom<&BluesnapRouterData<&types::PaymentsCaptureRouterData>> for BluesnapCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + fn try_from( + item: &BluesnapRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { let card_transaction_type = BluesnapTxnType::Capture; - let transaction_id = item.request.connector_transaction_id.to_string(); - let amount = - utils::to_currency_base_unit(item.request.amount_to_capture, item.request.currency)?; + let transaction_id = item + .router_data + .request + .connector_transaction_id + .to_string(); Ok(Self { card_transaction_type, transaction_id, - amount: Some(amount), + amount: Some(item.amount.to_owned()), }) } } @@ -798,15 +853,14 @@ pub struct BluesnapRefundRequest { reason: Option<String>, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for BluesnapRefundRequest { +impl<F> TryFrom<&BluesnapRouterData<&types::RefundsRouterData<F>>> for BluesnapRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item: &BluesnapRouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { Ok(Self { - reason: item.request.reason.clone(), - amount: Some(utils::to_currency_base_unit( - item.request.refund_amount, - item.request.currency, - )?), + reason: item.router_data.request.reason.clone(), + amount: Some(item.amount.to_owned()), }) } }
refactor
[bluesnap]Enhance currency Mapping with ConnectorCurrencyCommon Trait (#2193)
a48caef836efb5bfcd758d1035cc27a736707367
2023-01-17 14:11:58
Sangamesh Kulkarni
feat: token flow for wallet (#388)
false
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index f7c677363ea..5e3d40aa5cd 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -687,7 +687,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( .customer_id .ne(&payment_data.payment_intent.customer_id), || { - Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer payment method and customer passed in payment are not same".into() }) + Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payment method and customer passed in payment are not same".into() }) }, )?; payment_data.token = Some(token.to_string()); @@ -707,6 +707,37 @@ pub async fn make_pm_data<'a, F: Clone, R>( } (_, _) => pm, } + } else if payment_method_type == Some(storage_enums::PaymentMethodType::Wallet) { + let (pm, supplementary_data) = + vault::Vault::get_payment_method_data_from_locker(state, &token).await?; + + utils::when( + supplementary_data + .customer_id + .ne(&payment_data.payment_intent.customer_id), + || { + Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payment method and customer passed in payment are not same".into() }) + }, + )?; + payment_data.token = Some(token.to_string()); + match pm.clone() { + Some(api::PaymentMethod::Wallet(wallet_data)) => { + if wallet_data.token.is_some() { + let updated_pm = api::PaymentMethod::Wallet(wallet_data); + vault::Vault::store_payment_method_data_in_locker( + state, + Some(token), + &updated_pm, + payment_data.payment_intent.customer_id.to_owned(), + ) + .await?; + Some(updated_pm) + } else { + pm + } + } + _ => pm, + } } else { utils::when(payment_method_type.is_none(), || { Err(errors::ApiErrorResponse::MissingRequiredField {
feat
token flow for wallet (#388)
94a5eb35335afb4c38f4af62aef1a195f30ec448
2023-07-17 17:41:22
Sahkal Poddar
feat(router): restricted customer update in payments-confirm and payments-update call via clientAuth (#1659)
false
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1082c85ad3a..80958f641bb 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -49,6 +49,7 @@ pub async fn payments_operation_core<F, Req, Op, FData>( operation: Op, req: Req, call_connector_action: CallConnectorAction, + auth_flow: services::AuthFlow, ) -> RouterResult<(PaymentData<F>, Req, Option<domain::Customer>)> where F: Send + Clone + Sync, @@ -70,7 +71,6 @@ where let operation: BoxedOperation<'_, F, Req> = Box::new(operation); tracing::Span::current().record("merchant_id", merchant_account.merchant_id.as_str()); - let (operation, validate_result) = operation .to_validate_request()? .validate_request(&req, &merchant_account)?; @@ -85,6 +85,7 @@ where validate_result.mandate_type.to_owned(), &merchant_account, &key_store, + auth_flow, ) .await?; @@ -246,6 +247,7 @@ where operation.clone(), req, call_connector_action, + auth_flow, ) .await?; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index ba3d0432b58..8fd63210493 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2550,3 +2550,28 @@ pub async fn get_additional_payment_data( } } } + +pub fn validate_customer_access( + payment_intent: &storage::PaymentIntent, + auth_flow: services::AuthFlow, + request: &api::PaymentsRequest, +) -> Result<(), errors::ApiErrorResponse> { + if auth_flow == services::AuthFlow::Client && request.customer_id.is_some() { + let is_not_same_customer = request + .clone() + .customer_id + .and_then(|customer| { + payment_intent + .clone() + .customer_id + .map(|payment_customer| payment_customer != customer) + }) + .unwrap_or(false); + if is_not_same_customer { + Err(errors::ApiErrorResponse::GenericUnauthorized { + message: "Unauthorised access to update customer".to_string(), + })?; + } + } + Ok(()) +} diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 21d4846a7c5..bbbebfa8ef7 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -26,6 +26,7 @@ use crate::{ core::errors::{self, CustomResult, RouterResult}, db::StorageInterface, routes::AppState, + services, types::{ self, api, domain, storage::{self, enums}, @@ -94,6 +95,7 @@ pub trait GetTracker<F, D, R>: Send { mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, mechant_key_store: &domain::MerchantKeyStore, + auth_flow: services::AuthFlow, ) -> RouterResult<(BoxedOperation<'a, F, R>, D, Option<CustomerDetails>)>; } diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index c21b545737c..8256de6982c 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -14,6 +14,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, PaymentIdTypeExt}, domain, @@ -37,6 +38,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 16002726ca1..4984dbd0f05 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -13,6 +13,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, PaymentIdTypeExt}, domain, @@ -38,6 +39,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest>, payments::PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 8c4c1688c03..6c16eb85ded 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -14,6 +14,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ self, api::{self, PaymentIdTypeExt}, @@ -39,6 +40,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 434b9444ac3..301fd23006c 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -15,6 +15,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ self, api::{self, PaymentIdTypeExt}, @@ -28,7 +29,6 @@ use crate::{ #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(ops = "all", flow = "authorize")] pub struct PaymentConfirm; - #[async_trait] impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm { #[instrument(skip_all)] @@ -40,6 +40,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, PaymentData<F>, @@ -59,6 +60,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + helpers::validate_customer_access(&payment_intent, auth_flow, request)?; + helpers::validate_payment_status_against_not_allowed_statuses( &payment_intent.status, &[ @@ -499,7 +502,6 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir operations::ValidateResult<'a>, )> { helpers::validate_customer_details_in_request(request)?; - let given_payment_id = match &request.payment_id { Some(id_type) => Some( id_type diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index f5fc016a1e5..b621e59c9bc 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -46,6 +46,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index be6e5a14371..34f5b66c18a 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -16,6 +16,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ self, api::{self, enums as api_enums, PaymentIdTypeExt}, @@ -71,6 +72,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, _mechant_key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::VerifyRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index a2f014fac7a..4aa523e0d2a 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -15,6 +15,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, PaymentIdTypeExt}, domain, @@ -40,6 +41,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsSessionRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index cb9cc845edc..282b89edc2d 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -13,6 +13,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, PaymentIdTypeExt}, domain, @@ -36,6 +37,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, mechant_key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsStartRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 4e8ae9d21b4..bcb268eb4a0 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -14,6 +14,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api, domain, storage::{self, enums}, @@ -163,6 +164,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, PaymentData<F>, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 17171c8438d..daeaeb32d70 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -15,6 +15,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, PaymentIdTypeExt}, domain, @@ -39,6 +40,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + auth_flow: services::AuthFlow, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, PaymentData<F>, @@ -63,6 +65,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa .setup_future_usage .or(payment_intent.setup_future_usage); + helpers::validate_customer_access(&payment_intent, auth_flow, request)?; + helpers::validate_card_data(request.payment_method_data.clone())?; helpers::validate_payment_status_against_not_allowed_statuses( @@ -548,7 +552,6 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate operations::ValidateResult<'a>, )> { helpers::validate_customer_details_in_request(request)?; - let given_payment_id = match &request.payment_id { Some(id_type) => Some( id_type diff --git a/crates/router/src/scheduler/workflows/payment_sync.rs b/crates/router/src/scheduler/workflows/payment_sync.rs index b14cd8bc1b1..805aeef3167 100644 --- a/crates/router/src/scheduler/workflows/payment_sync.rs +++ b/crates/router/src/scheduler/workflows/payment_sync.rs @@ -7,6 +7,7 @@ use crate::{ errors, routes::AppState, scheduler::{consumer, process_data, utils}, + services, types::{ api, storage::{self, enums, ProcessTrackerExt}, @@ -54,6 +55,7 @@ impl ProcessTrackerWorkflow for PaymentsSyncWorkflow { operations::PaymentStatus, tracking_data.clone(), payment_flows::CallConnectorAction::Trigger, + services::AuthFlow::Client, ) .await?;
feat
restricted customer update in payments-confirm and payments-update call via clientAuth (#1659)
bfca26d9fd7a45ba9e52ceb79eb399b9ad382a72
2023-02-28 18:30:03
Narayan Bhat
feat: store card network for cards (#687)
false
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index ed0a5c875d5..1d2daccbcf3 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -41,6 +41,10 @@ pub struct CreatePaymentMethod { /// The unique identifier of the customer. #[schema(example = "cus_meowerunwiuwiwqw")] pub customer_id: Option<String>, + + /// The card network + #[schema(example = "Visa")] + pub card_network: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] @@ -54,6 +58,10 @@ pub struct UpdatePaymentMethod { "card_holder_name": "John Doe"}))] pub card: Option<CardDetail>, + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + #[schema(value_type = Option<CardNetwork>,example = "Visa")] + pub card_network: Option<api_enums::CardNetwork>, + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<serde_json::Value>, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 7359375414d..66173a3ab88 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -48,6 +48,7 @@ pub async fn create_payment_method( payment_method: req.payment_method.foreign_into(), payment_method_type: req.payment_method_type.map(ForeignInto::foreign_into), payment_method_issuer: req.payment_method_issuer.clone(), + scheme: req.card_network.clone(), metadata: req.metadata.clone(), ..storage::PaymentMethodNew::default() }) @@ -129,6 +130,10 @@ pub async fn update_customer_payment_method( card: req.card, metadata: req.metadata, customer_id: Some(pm.customer_id), + card_network: req + .card_network + .as_ref() + .map(|card_network| card_network.to_string()), }; add_payment_method(state, new_pm, &merchant_account).await } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index cdb1fc961af..1325a5dea95 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -517,11 +517,15 @@ pub(crate) async fn call_payment_method( let payment_method_request = api::CreatePaymentMethod { payment_method: payment_method_type.foreign_into(), payment_method_type: None, - payment_method_issuer: None, + payment_method_issuer: card.card_issuer.clone(), payment_method_issuer_code: None, card: Some(card_detail), metadata: None, customer_id: Some(customer_id), + card_network: card + .card_network + .as_ref() + .map(|card_network| card_network.to_string()), }; let resp = cards::add_payment_method( state, @@ -553,6 +557,7 @@ pub(crate) async fn call_payment_method( card: None, metadata: None, customer_id: None, + card_network: None, }; let resp = cards::add_payment_method(state, payment_method_request, merchant_account)
feat
store card network for cards (#687)
f91d4ae11b02def92c1dde743a0c01b5aac5703f
2023-11-22 22:01:07
DEEPANSHU BANSAL
feat(connector): [BANKOFAMERICA] Implement Google Pay (#2940)
false
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index a6fa8652b27..f6cda8ac23c 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1,4 +1,5 @@ use api_models::payments; +use base64::Engine; use common_utils::pii; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -87,6 +88,7 @@ pub struct BankOfAmericaPaymentsRequest { #[serde(rename_all = "camelCase")] pub struct ProcessingInformation { capture: bool, + payment_solution: Option<String>, } #[derive(Debug, Serialize)] @@ -97,10 +99,24 @@ pub struct CaptureOptions { } #[derive(Debug, Serialize)] -pub struct PaymentInformation { +#[serde(rename_all = "camelCase")] +pub struct CardPaymentInformation { card: Card, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GooglePayPaymentInformation { + fluid_data: FluidData, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum PaymentInformation { + Cards(CardPaymentInformation), + GooglePay(GooglePayPaymentInformation), +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { @@ -112,6 +128,12 @@ pub struct Card { card_type: Option<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FluidData { + value: Secret<String>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { @@ -177,12 +199,165 @@ impl From<CardIssuer> for String { } } +#[derive(Debug, Serialize)] +pub enum PaymentSolution { + ApplePay, + GooglePay, +} + +impl From<PaymentSolution> for String { + fn from(solution: PaymentSolution) -> Self { + let payment_solution = match solution { + PaymentSolution::ApplePay => "001", + PaymentSolution::GooglePay => "012", + }; + payment_solution.to_string() + } +} + +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + BillTo, + )> for OrderInformationWithBill +{ + fn from( + (item, bill_to): ( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + BillTo, + ), + ) -> Self { + Self { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + }, + bill_to, + } + } +} + +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + Option<PaymentSolution>, + )> for ProcessingInformation +{ + fn from( + (item, solution): ( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + Option<PaymentSolution>, + ), + ) -> Self { + Self { + capture: matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ), + payment_solution: solution.map(String::from), + } + } +} + +impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> + for ClientReferenceInformation +{ + fn from(item: &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientReferenceInformation { code: Option<String>, } +impl + TryFrom<( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + payments::Card, + )> for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + payments::Card, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + + let processing_information = ProcessingInformation::from((item, None)); + let client_reference_information = ClientReferenceInformation::from(item); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + }) + } +} + +impl + TryFrom<( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + payments::GooglePayWalletData, + )> for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, google_pay_data): ( + &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + payments::GooglePayWalletData, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + + let payment_information = PaymentInformation::GooglePay(GooglePayPaymentInformation { + fluid_data: FluidData { + value: Secret::from( + consts::BASE64_ENGINE.encode(google_pay_data.tokenization_data.token), + ), + }, + }); + + let processing_information = + ProcessingInformation::from((item, Some(PaymentSolution::GooglePay))); + let client_reference_information = ClientReferenceInformation::from(item); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + }) + } +} + impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> for BankOfAmericaPaymentsRequest { @@ -191,52 +366,41 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> item: &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - api::PaymentMethodData::Card(ccard) => { - let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; - - let order_information = OrderInformationWithBill { - amount_details: Amount { - total_amount: item.amount.to_owned(), - currency: item.router_data.request.currency, - }, - bill_to, - }; - let card_issuer = ccard.get_card_issuer(); - let card_type = match card_issuer { - Ok(issuer) => Some(String::from(issuer)), - Err(_) => None, - }; - let payment_information = PaymentInformation { - card: Card { - number: ccard.card_number, - expiration_month: ccard.card_exp_month, - expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, - card_type, - }, - }; - - let processing_information = ProcessingInformation { - capture: matches!( - item.router_data.request.capture_method, - Some(enums::CaptureMethod::Automatic) | None - ), - }; - - let client_reference_information = ClientReferenceInformation { - code: Some(item.router_data.connector_request_reference_id.clone()), - }; - - Ok(Self { - processing_information, - payment_information, - order_information, - client_reference_information, - }) - } + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + payments::WalletData::GooglePay(google_pay_data) => { + Self::try_from((item, google_pay_data)) + } + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePay(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::WeChatPayQr(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Bank of America"), + ) + .into()), + }, payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::Wallet(_) | payments::PaymentMethodData::PayLater(_) | payments::PaymentMethodData::BankRedirect(_) | payments::PaymentMethodData::BankDebit(_)
feat
[BANKOFAMERICA] Implement Google Pay (#2940)
3806cd35c763cc4517b761b4e3b0e736c60fac9f
2024-03-06 18:14:34
DEEPANSHU BANSAL
feat(connector): [AUTHORIZEDOTNET] Add billing address in payments request (#3981)
false
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 8ba610d66d4..2d6f2e040a4 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -7,10 +7,17 @@ use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData}, + connector::utils::{ + self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData, + }, core::errors, services, - types::{self, api, storage::enums, transformers::ForeignFrom}, + types::{ + self, + api::{self, enums as api_enums}, + storage::enums, + transformers::ForeignFrom, + }, utils::OptionExt, }; @@ -231,6 +238,8 @@ struct TransactionRequest { amount: f64, currency_code: String, payment: PaymentDetails, + order: Order, + bill_to: Option<BillTo>, processing_options: Option<ProcessingOptions>, #[serde(skip_serializing_if = "Option::is_none")] subsequent_auth_information: Option<SubsequentAuthInformation>, @@ -243,6 +252,24 @@ pub struct ProcessingOptions { is_subsequent_auth: bool, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BillTo { + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + address: Option<Secret<String>>, + city: Option<String>, + state: Option<Secret<String>>, + zip: Option<Secret<String>>, + country: Option<api_enums::CountryAlpha2>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Order { + description: String, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct SubsequentAuthInformation { @@ -341,12 +368,27 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> }), None => None, }; - + let bill_to = item + .router_data + .get_billing_address_details_as_optional() + .map(|address| BillTo { + first_name: address.first_name.clone(), + last_name: address.last_name.clone(), + address: address.line1.clone(), + city: address.city.clone(), + state: address.state.clone(), + zip: address.zip.clone(), + country: address.country, + }); let transaction_request = TransactionRequest { transaction_type: TransactionType::from(item.router_data.request.capture_method), amount: item.amount, - payment: payment_details, currency_code: item.router_data.request.currency.to_string(), + payment: payment_details, + order: Order { + description: item.router_data.connector_request_reference_id.clone(), + }, + bill_to, processing_options, subsequent_auth_information, authorization_indicator_type,
feat
[AUTHORIZEDOTNET] Add billing address in payments request (#3981)
95c7ca99d1b5009f4cc8664825c5e63a165006c7
2023-05-17 00:05:50
Derek Leverenz
feat(router): implement `ApiKeyInterface` for `MockDb` (#1101)
false
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 89d51908cdf..2b55db74a62 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -82,6 +82,7 @@ pub struct MockDb { processes: Arc<Mutex<Vec<storage::ProcessTracker>>>, connector_response: Arc<Mutex<Vec<storage::ConnectorResponse>>>, redis: Arc<redis_interface::RedisConnectionPool>, + api_keys: Arc<Mutex<Vec<storage::ApiKey>>>, } impl MockDb { @@ -96,6 +97,7 @@ impl MockDb { processes: Default::default(), connector_response: Default::default(), redis: Arc::new(crate::connection::redis_connection(redis).await), + api_keys: Default::default(), } } } diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs index 86d8b35dfd1..3d1c2d6bb34 100644 --- a/crates/router/src/db/api_keys.rs +++ b/crates/router/src/db/api_keys.rs @@ -126,55 +126,252 @@ impl ApiKeyInterface for Store { impl ApiKeyInterface for MockDb { async fn insert_api_key( &self, - _api_key: storage::ApiKeyNew, + api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_api_keys = self.api_keys.lock().await; + // don't allow duplicate key_ids, a those would be a unique constraint violation in the + // real db as it is used as the primary key + if locked_api_keys.iter().any(|k| k.key_id == api_key.key_id) { + Err(errors::StorageError::MockDbError)?; + } + let stored_key = storage::ApiKey { + key_id: api_key.key_id, + merchant_id: api_key.merchant_id, + name: api_key.name, + description: api_key.description, + hashed_api_key: api_key.hashed_api_key, + prefix: api_key.prefix, + created_at: api_key.created_at, + expires_at: api_key.expires_at, + last_used: api_key.last_used, + }; + locked_api_keys.push(stored_key.clone()); + + Ok(stored_key) } async fn update_api_key( &self, - _merchant_id: String, - _key_id: String, - _api_key: storage::ApiKeyUpdate, + merchant_id: String, + key_id: String, + api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_api_keys = self.api_keys.lock().await; + // find a key with the given merchant_id and key_id and update, otherwise return an error + let mut key_to_update = locked_api_keys + .iter_mut() + .find(|k| k.merchant_id == merchant_id && k.key_id == key_id) + .ok_or(errors::StorageError::MockDbError)?; + + match api_key { + storage::ApiKeyUpdate::Update { + name, + description, + expires_at, + last_used, + } => { + if let Some(name) = name { + key_to_update.name = name; + } + // only update these fields if the value was Some(_) + if description.is_some() { + key_to_update.description = description; + } + if let Some(expires_at) = expires_at { + key_to_update.expires_at = expires_at; + } + if last_used.is_some() { + key_to_update.last_used = last_used + } + } + storage::ApiKeyUpdate::LastUsedUpdate { last_used } => { + key_to_update.last_used = Some(last_used); + } + } + + Ok(key_to_update.clone()) } async fn revoke_api_key( &self, - _merchant_id: &str, - _key_id: &str, + merchant_id: &str, + key_id: &str, ) -> CustomResult<bool, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut locked_api_keys = self.api_keys.lock().await; + // find the key to remove, if it exists + if let Some(pos) = locked_api_keys + .iter() + .position(|k| k.merchant_id == merchant_id && k.key_id == key_id) + { + // use `remove` instead of `swap_remove` so we have a consistent order, which might + // matter to someone using limit/offset in `list_api_keys_by_merchant_id` + locked_api_keys.remove(pos); + Ok(true) + } else { + Ok(false) + } } async fn find_api_key_by_merchant_id_key_id_optional( &self, - _merchant_id: &str, - _key_id: &str, + merchant_id: &str, + key_id: &str, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + Ok(self + .api_keys + .lock() + .await + .iter() + .find(|k| k.merchant_id == merchant_id && k.key_id == key_id) + .cloned()) } async fn find_api_key_by_hash_optional( &self, - _hashed_api_key: storage::HashedApiKey, + hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + Ok(self + .api_keys + .lock() + .await + .iter() + .find(|k| k.hashed_api_key == hashed_api_key) + .cloned()) } async fn list_api_keys_by_merchant_id( &self, - _merchant_id: &str, - _limit: Option<i64>, - _offset: Option<i64>, + merchant_id: &str, + limit: Option<i64>, + offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { - // [#172]: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + // mimic the SQL limit/offset behavior + let offset: usize = if let Some(offset) = offset { + if offset < 0 { + Err(errors::StorageError::MockDbError)?; + } + offset + .try_into() + .map_err(|_| errors::StorageError::MockDbError)? + } else { + 0 + }; + + let limit: usize = if let Some(limit) = limit { + if limit < 0 { + Err(errors::StorageError::MockDbError)?; + } + limit + .try_into() + .map_err(|_| errors::StorageError::MockDbError)? + } else { + usize::MAX + }; + + let keys_for_merchant_id: Vec<storage::ApiKey> = self + .api_keys + .lock() + .await + .iter() + .filter(|k| k.merchant_id == merchant_id) + .skip(offset) + .take(limit) + .cloned() + .collect(); + + Ok(keys_for_merchant_id) + } +} + +#[cfg(test)] +mod tests { + use time::macros::datetime; + + use crate::{ + db::{api_keys::ApiKeyInterface, MockDb}, + types::storage, + }; + + #[allow(clippy::unwrap_used)] + #[tokio::test] + async fn test_mockdb_api_key_interface() { + let mockdb = MockDb::new(&Default::default()).await; + + let key1 = mockdb + .insert_api_key(storage::ApiKeyNew { + key_id: "key_id1".into(), + merchant_id: "merchant1".into(), + name: "Key 1".into(), + description: None, + hashed_api_key: "hashed_key1".to_string().into(), + prefix: "abc".into(), + created_at: datetime!(2023-02-01 0:00), + expires_at: Some(datetime!(2023-03-01 0:00)), + last_used: None, + }) + .await + .unwrap(); + + mockdb + .insert_api_key(storage::ApiKeyNew { + key_id: "key_id2".into(), + merchant_id: "merchant1".into(), + name: "Key 2".into(), + description: None, + hashed_api_key: "hashed_key2".to_string().into(), + prefix: "abc".into(), + created_at: datetime!(2023-03-01 0:00), + expires_at: None, + last_used: None, + }) + .await + .unwrap(); + + let found_key1 = mockdb + .find_api_key_by_merchant_id_key_id_optional("merchant1", "key_id1") + .await + .unwrap() + .unwrap(); + assert_eq!(found_key1.key_id, key1.key_id); + assert!(mockdb + .find_api_key_by_merchant_id_key_id_optional("merchant1", "does_not_exist") + .await + .unwrap() + .is_none()); + + mockdb + .update_api_key( + "merchant1".into(), + "key_id1".into(), + storage::ApiKeyUpdate::LastUsedUpdate { + last_used: datetime!(2023-02-04 1:11), + }, + ) + .await + .unwrap(); + let updated_key1 = mockdb + .find_api_key_by_merchant_id_key_id_optional("merchant1", "key_id1") + .await + .unwrap() + .unwrap(); + assert_eq!(updated_key1.last_used, Some(datetime!(2023-02-04 1:11))); + + assert_eq!( + mockdb + .list_api_keys_by_merchant_id("merchant1", None, None) + .await + .unwrap() + .len(), + 2 + ); + mockdb.revoke_api_key("merchant1", "key_id1").await.unwrap(); + assert_eq!( + mockdb + .list_api_keys_by_merchant_id("merchant1", None, None) + .await + .unwrap() + .len(), + 1 + ); } } diff --git a/crates/storage_models/src/api_keys.rs b/crates/storage_models/src/api_keys.rs index 650ea0c7fa1..b3620945977 100644 --- a/crates/storage_models/src/api_keys.rs +++ b/crates/storage_models/src/api_keys.rs @@ -3,7 +3,7 @@ use time::PrimitiveDateTime; use crate::schema::api_keys; -#[derive(Debug, Identifiable, Queryable)] +#[derive(Debug, Clone, Identifiable, Queryable)] #[diesel(table_name = api_keys, primary_key(key_id))] pub struct ApiKey { pub key_id: String, @@ -77,7 +77,7 @@ impl From<ApiKeyUpdate> for ApiKeyUpdateInternal { } } -#[derive(Debug, AsExpression)] +#[derive(Debug, Clone, AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Text)] pub struct HashedApiKey(String);
feat
implement `ApiKeyInterface` for `MockDb` (#1101)
ed021c1d9961a2723c9b2fecf9f35ff16ef08294
2024-06-26 19:10:09
Sai Harsha Vardhan
feat(router): add payments manual-update api (#5045)
false
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index f639e093e6e..4ed4e006669 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -14,8 +14,9 @@ use crate::{ PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, - PaymentsIncrementalAuthorizationRequest, PaymentsRejectRequest, PaymentsRequest, - PaymentsResponse, PaymentsRetrieveRequest, PaymentsStartRequest, RedirectionResponse, + PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, + PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest, + PaymentsStartRequest, RedirectionResponse, }, }; impl ApiEventMetric for PaymentsRetrieveRequest { @@ -239,3 +240,11 @@ impl ApiEventMetric for PaymentsExternalAuthenticationRequest { } impl ApiEventMetric for ExtendedCardInfoResponse {} + +impl ApiEventMetric for PaymentsManualUpdateRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_id.clone(), + }) + } +} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 1d4418bee15..777e876b1b5 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4653,6 +4653,25 @@ pub struct PaymentsExternalAuthenticationRequest { pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] +pub struct PaymentsManualUpdateRequest { + /// The identifier for the payment + #[serde(skip)] + pub payment_id: String, + /// The identifier for the payment attempt + pub attempt_id: String, + /// Merchant ID + pub merchant_id: String, + /// The status of the attempt + pub attempt_status: Option<enums::AttemptStatus>, + /// Error code of the connector + pub error_code: Option<String>, + /// Error message of the connector + pub error_message: Option<String>, + /// Error reason of the connector + pub error_reason: Option<String>, +} + #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 1b62473b9a0..0aeef652d07 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -351,6 +351,15 @@ pub enum PaymentAttemptUpdate { authentication_id: Option<String>, updated_by: String, }, + ManualUpdate { + status: Option<storage_enums::AttemptStatus>, + error_code: Option<String>, + error_message: Option<String>, + error_reason: Option<String>, + updated_by: String, + unified_code: Option<String>, + unified_message: Option<String>, + }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -884,6 +893,24 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, ..Default::default() }, + PaymentAttemptUpdate::ManualUpdate { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + } => Self { + status, + error_code: error_code.map(Some), + error_message: error_message.map(Some), + error_reason: error_reason.map(Some), + updated_by, + unified_code: unified_code.map(Some), + unified_message: unified_message.map(Some), + ..Default::default() + }, } } } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 7fad83e7a0f..6326eeef646 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -206,6 +206,10 @@ pub enum PaymentIntentUpdate { CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, + ManualUpdate { + status: Option<storage_enums::IntentStatus>, + updated_by: String, + }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -508,6 +512,11 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { shipping_address_id, ..Default::default() }, + PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { + status, + updated_by, + ..Default::default() + }, } } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index d8b5288c85c..4f50948b480 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -454,6 +454,15 @@ pub enum PaymentAttemptUpdate { authentication_id: Option<String>, updated_by: String, }, + ManualUpdate { + status: Option<storage_enums::AttemptStatus>, + error_code: Option<String>, + error_message: Option<String>, + error_reason: Option<String>, + updated_by: String, + unified_code: Option<String>, + unified_message: Option<String>, + }, } impl ForeignIDRef for PaymentAttempt { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 2c99360d4f9..66ecf7ec57f 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -214,6 +214,10 @@ pub enum PaymentIntentUpdate { CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, + ManualUpdate { + status: Option<storage_enums::IntentStatus>, + updated_by: String, + }, } #[derive(Clone, Debug, Default)] @@ -442,6 +446,12 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { shipping_address_id, ..Default::default() }, + PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { + status, + modified_at: Some(common_utils::date_time::now()), + updated_by, + ..Default::default() + }, } } } @@ -611,6 +621,9 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { } => Self::CompleteAuthorizeUpdate { shipping_address_id, }, + PaymentIntentUpdate::ManualUpdate { status, updated_by } => { + Self::ManualUpdate { status, updated_by } + } } } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 78c9ca5cd50..459ada8fb4f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4134,3 +4134,115 @@ pub async fn get_extended_card_info( payments_api::ExtendedCardInfoResponse { payload }, )) } + +#[cfg(feature = "olap")] +pub async fn payments_manual_update( + state: SessionState, + req: api_models::payments::PaymentsManualUpdateRequest, +) -> RouterResponse<serde_json::Value> { + let api_models::payments::PaymentsManualUpdateRequest { + payment_id, + attempt_id, + merchant_id, + attempt_status, + error_code, + error_message, + error_reason, + } = req; + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + &merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) + .attach_printable("Error while fetching the key store by merchant_id")?; + let merchant_account = state + .store + .find_merchant_account_by_merchant_id(&merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) + .attach_printable("Error while fetching the merchant_account by merchant_id")?; + let payment_attempt = state + .store + .find_payment_attempt_by_payment_id_merchant_id_attempt_id( + &payment_id, + &merchant_id, + &attempt_id.clone(), + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable( + "Error while fetching the payment_attempt by payment_id, merchant_id and attempt_id", + )?; + let payment_intent = state + .store + .find_payment_intent_by_payment_id_merchant_id( + &payment_id, + &merchant_account.merchant_id, + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Error while fetching the payment_intent by payment_id, merchant_id")?; + let option_gsm = if let Some(((code, message), connector_name)) = error_code + .as_ref() + .zip(error_message.as_ref()) + .zip(payment_attempt.connector.as_ref()) + { + helpers::get_gsm_record( + &state, + Some(code.to_string()), + Some(message.to_string()), + connector_name.to_string(), + // We need to get the unified_code and unified_message of the Authorize flow + "Authorize".to_string(), + ) + .await + } else { + None + }; + // Update the payment_attempt + let attempt_update = storage::PaymentAttemptUpdate::ManualUpdate { + status: attempt_status, + error_code, + error_message, + error_reason, + updated_by: merchant_account.storage_scheme.to_string(), + unified_code: option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()), + unified_message: option_gsm.and_then(|gsm| gsm.unified_message), + }; + let updated_payment_attempt = state + .store + .update_payment_attempt_with_attempt_id( + payment_attempt.clone(), + attempt_update, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Error while updating the payment_attempt")?; + // If the payment_attempt is active attempt for an intent, update the intent status + if payment_intent.active_attempt.get_id() == payment_attempt.attempt_id { + let intent_status = enums::IntentStatus::foreign_from(updated_payment_attempt.status); + let payment_intent_update = storage::PaymentIntentUpdate::ManualUpdate { + status: Some(intent_status), + updated_by: merchant_account.storage_scheme.to_string(), + }; + state + .store + .update_payment_intent( + payment_intent, + payment_intent_update, + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable("Error while updating payment_intent")?; + } + Ok(services::ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index b91129f4575..0124f6ae6a5 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -460,6 +460,10 @@ impl Payments { ) .service(web::resource("/filter").route(web::post().to(get_filters_for_payments))) .service(web::resource("/v2/filter").route(web::get().to(get_payment_filters))) + .service( + web::resource("/{payment_id}/manual-update") + .route(web::put().to(payments_manual_update)), + ) } #[cfg(feature = "oltp")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index b18720652cf..e5c4f1c8e95 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -124,7 +124,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsExternalAuthentication | Flow::PaymentsAuthorize | Flow::GetExtendedCardInfo - | Flow::PaymentsCompleteAuthorize => Self::Payments, + | Flow::PaymentsCompleteAuthorize + | Flow::PaymentsManualUpdate => Self::Payments, Flow::PayoutsCreate | Flow::PayoutsRetrieve diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index e6e4d238677..912421f4650 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1394,6 +1394,35 @@ pub async fn post_3ds_payments_authorize( .await } +#[cfg(feature = "olap")] +pub async fn payments_manual_update( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<payment_types::PaymentsManualUpdateRequest>, + path: web::Path<String>, +) -> impl Responder { + let flow = Flow::PaymentsManualUpdate; + let mut payload = json_payload.into_inner(); + let payment_id = path.into_inner(); + + let locking_action = payload.get_locking_input(flow.clone()); + + tracing::Span::current().record("payment_id", &payment_id); + + payload.payment_id = payment_id; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, _auth, req, _req_state| payments::payments_manual_update(state, req), + &auth::AdminApiAuth, + locking_action, + )) + .await +} + /// Retrieve endpoint for merchant to fetch the encrypted customer payment method data #[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))] pub async fn retrieve_extended_card_info( @@ -1654,3 +1683,19 @@ impl GetLockingInput for payment_types::PaymentsExternalAuthenticationRequest { } } } + +impl GetLockingInput for payment_types::PaymentsManualUpdateRequest { + fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction + where + F: types::FlowMetric, + lock_utils::ApiIdentifier: From<F>, + { + api_locking::LockAction::Hold { + input: api_locking::LockingInput { + unique_locking_key: self.payment_id.to_owned(), + api_identifier: lock_utils::ApiIdentifier::from(flow), + override_lock_retries: None, + }, + } + } +} diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index d8303831221..e1dbf452eff 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -8,11 +8,11 @@ pub use api_models::payments::{ PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest, - PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, - PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, - PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails, - RedirectionResponse, SessionToken, TimeRange, UrlDetails, VerifyRequest, VerifyResponse, - WalletData, + PaymentsManualUpdateRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse, + PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, + PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, + PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, TimeRange, UrlDetails, + VerifyRequest, VerifyResponse, WalletData, }; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0d146a9eb2b..46bb93f06e7 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -446,6 +446,8 @@ pub enum Flow { ToggleConnectorAgnosticMit, /// Get the extended card info associated to a payment_id GetExtendedCardInfo, + /// Manually update the payment details like status, error code, error message etc. + PaymentsManualUpdate, } /// diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 4828c8b3705..f464ef66a1d 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1748,6 +1748,23 @@ impl DataModelExt for PaymentAttemptUpdate { authentication_id, updated_by, }, + Self::ManualUpdate { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + } => DieselPaymentAttemptUpdate::ManualUpdate { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + }, } } @@ -2079,6 +2096,23 @@ impl DataModelExt for PaymentAttemptUpdate { authentication_id, updated_by, }, + DieselPaymentAttemptUpdate::ManualUpdate { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + } => Self::ManualUpdate { + status, + error_code, + error_message, + error_reason, + updated_by, + unified_code, + unified_message, + }, } } }
feat
add payments manual-update api (#5045)
6e7b38a622d1399260f9a144e07a58bc6a7a6655
2024-08-20 14:50:58
Narayan Bhat
feat(business_profile_v2): business profile v2 create and retrieve endpoint (#5606)
false
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.yml index c94751b989d..17e31053348 100644 --- a/.github/workflows/CI-pr.yml +++ b/.github/workflows/CI-pr.yml @@ -283,10 +283,6 @@ jobs: name: Check compilation for V2 features runs-on: ubuntu-latest - env: - # Allow the `clippy::todo` lint for v2 checks - RUSTFLAGS: "-D warnings -A clippy::todo" - steps: - name: Checkout repository uses: actions/checkout@v4 @@ -318,8 +314,17 @@ jobs: tool: just checksum: true - - name: Cargo hack_v2 + - name: Run cargo-hack on v2 features in select crates shell: bash env: GH_TOKEN: ${{ github.token }} + RUSTFLAGS: "-D warnings -A clippy::todo" run: just hack_v2 + + - name: Run cargo check with v2 features enabled + shell: bash + # env: + # # Not denying warnings for now. + # # We only want to ensure successful compilation for now. + # RUSTFLAGS: "-D warnings -A clippy::todo" + run: just check_v2 diff --git a/.typos.toml b/.typos.toml index 2f68e039cde..0697f226c38 100644 --- a/.typos.toml +++ b/.typos.toml @@ -2,7 +2,8 @@ check-filename = true [default.extend-identifiers] -"ABD" = "ABD" # Aberdeenshire, UK ISO 3166-2 code +ABD = "ABD" # Aberdeenshire, UK ISO 3166-2 code +ACTIVITE = "ACTIVITE" # French translation of activity AER = "AER" # An alias to Api Error Response ANG = "ANG" # Netherlands Antillean guilder currency code BA = "BA" # Bosnia and Herzegovina country code @@ -62,20 +63,6 @@ extend-exclude = [ "openapi/open_api_spec.yaml", # no longer updated "crates/router/src/utils/user/blocker_emails.txt", # this file contains various email domains "CHANGELOG.md", # This file contains all the commits - "crates/router/locales/ar.yml", # locales - "crates/router/locales/ca.yml", # locales - "crates/router/locales/de.yml", # locales - "crates/router/locales/es.yml", # locales - "crates/router/locales/fr-BE.yml", # locales - "crates/router/locales/fr.yml", # locales - "crates/router/locales/he.yml", # locales - "crates/router/locales/it.yml", # locales - "crates/router/locales/ja.yml", # locales - "crates/router/locales/nl.yml", # locales - "crates/router/locales/pl.yml", # locales - "crates/router/locales/pt.yml", # locales - "crates/router/locales/ru.yml", # locales - "crates/router/locales/sv.yml", # locales - "crates/router/locales/zh.yml", # locales - "crates/router/src/core/payment_link/locale.js" # this file contains converision of static strings in various languages + "crates/router/locales/*.yml", # locales + "crates/router/src/core/payment_link/locale.js", # this file contains conversion of static strings in various languages ] diff --git a/Cargo.lock b/Cargo.lock index c0ff88bfcf6..cf7718d8875 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -451,6 +451,7 @@ dependencies = [ "indexmap 2.3.0", "masking", "mime", + "nutype", "reqwest", "router_derive", "serde", diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index a52ebcdf9be..458e1ae9ff0 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -2684,7 +2684,7 @@ }, "payment_response_hash_key": { "type": "string", - "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used.", + "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.", "nullable": true }, "redirect_to_merchant_with_http_post": { @@ -2738,7 +2738,7 @@ "items": { "type": "string" }, - "description": "Verified applepay domains for a particular profile", + "description": "Verified Apple Pay domains for a particular profile", "nullable": true }, "session_expiry": { @@ -2847,7 +2847,7 @@ }, "payment_response_hash_key": { "type": "string", - "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used.", + "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response.", "nullable": true }, "redirect_to_merchant_with_http_post": { @@ -2899,7 +2899,7 @@ "items": { "type": "string" }, - "description": "Verified applepay domains for a particular profile", + "description": "Verified Apple Pay domains for a particular profile", "nullable": true }, "session_expiry": { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 0caaef1e535..8b082caa373 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -7162,7 +7162,7 @@ }, "payment_response_hash_key": { "type": "string", - "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used.", + "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.", "nullable": true }, "redirect_to_merchant_with_http_post": { @@ -7216,7 +7216,7 @@ "items": { "type": "string" }, - "description": "Verified applepay domains for a particular profile", + "description": "Verified Apple Pay domains for a particular profile", "nullable": true }, "session_expiry": { @@ -7325,7 +7325,7 @@ }, "payment_response_hash_key": { "type": "string", - "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used.", + "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response.", "nullable": true }, "redirect_to_merchant_with_http_post": { @@ -7377,7 +7377,7 @@ "items": { "type": "string" }, - "description": "Verified applepay domains for a particular profile", + "description": "Verified Apple Pay domains for a particular profile", "nullable": true }, "session_expiry": { @@ -11511,7 +11511,7 @@ }, "payment_response_hash_key": { "type": "string", - "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used.", + "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.", "nullable": true }, "redirect_to_merchant_with_http_post": { @@ -11691,7 +11691,7 @@ }, "payment_response_hash_key": { "type": "string", - "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used.", + "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.", "example": "xkkdf909012sdjki2dkh5sdf", "nullable": true, "maxLength": 255 @@ -11874,7 +11874,7 @@ }, "payment_response_hash_key": { "type": "string", - "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used.", + "description": "Refers to the hash key used for calculating the signature for webhooks and redirect response.", "nullable": true }, "redirect_to_merchant_with_http_post": { diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 9935e41faa5..e342fb3db91 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -39,6 +39,7 @@ strum = { version = "0.26", features = ["derive"] } time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } +nutype = { version = "0.4.2", features = ["serde"] } # First party crates cards = { version = "0.1.0", path = "../cards" } diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index f494b29712b..b073c219517 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -26,7 +26,10 @@ use super::payments::AddressDetails; not(feature = "merchant_account_v2") ))] use crate::routing; -use crate::{enums as api_enums, payment_methods}; +use crate::{ + consts::{MAX_ORDER_FULFILLMENT_EXPIRY, MIN_ORDER_FULFILLMENT_EXPIRY}, + enums as api_enums, payment_methods, +}; #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantAccountListRequest { @@ -80,7 +83,7 @@ pub struct MerchantAccountCreate { #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, - /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used. + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled. @@ -300,7 +303,7 @@ pub struct MerchantAccountUpdate { #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, - /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used. + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled @@ -462,7 +465,7 @@ pub struct MerchantAccountResponse { #[schema(default = false, example = true)] pub enable_payment_response_hash: bool, - /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used. + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")] pub payment_response_hash_key: Option<String>, @@ -1851,6 +1854,10 @@ pub struct MerchantConnectorDetails { pub metadata: Option<pii::SecretSerdeValue>, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] #[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] #[serde(deny_unknown_fields)] pub struct BusinessProfileCreate { @@ -1866,7 +1873,7 @@ pub struct BusinessProfileCreate { #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, - /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used. + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled @@ -1897,7 +1904,90 @@ pub struct BusinessProfileCreate { #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, - /// Verified applepay domains for a particular profile + /// Verified Apple Pay domains for a particular profile + pub applepay_verified_domains: Option<Vec<String>>, + + /// Client Secret Default expiry for all payments created under this business profile + #[schema(example = 900)] + pub session_expiry: Option<u32>, + + /// Default Payment Link config for all payment links created under this business profile + pub payment_link_config: Option<BusinessPaymentLinkConfig>, + + /// External 3DS authentication details + pub authentication_connector_details: Option<AuthenticationConnectorDetails>, + + /// Whether to use the billing details passed when creating the intent as payment method billing + pub use_billing_as_payment_method_billing: Option<bool>, + + /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] + pub collect_shipping_details_from_wallet_connector: Option<bool>, + + /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] + pub collect_billing_details_from_wallet_connector: Option<bool>, + + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector + /// agnostic, i.e., MITs may be processed through different connector than CIT (customer + /// initiated transaction) based on the routing rules. + /// If set to `false`, MIT will go through the same connector as the CIT. + pub is_connector_agnostic_mit_enabled: Option<bool>, + + /// Default payout link config + #[schema(value_type = Option<BusinessPayoutLinkConfig>)] + pub payout_link_config: Option<BusinessPayoutLinkConfig>, + + /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. + #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] + pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, +} + +#[nutype::nutype( + validate(greater_or_equal = MIN_ORDER_FULFILLMENT_EXPIRY, less_or_equal = MAX_ORDER_FULFILLMENT_EXPIRY), + derive(Clone, Debug, Deserialize,Serialize) +)] +pub struct OrderFulfillmentTime(i64); + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] +#[serde(deny_unknown_fields)] +pub struct BusinessProfileCreate { + /// The name of business profile + #[schema(max_length = 64)] + pub profile_name: String, + + /// The URL to redirect after the completion of the operation + #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] + pub return_url: Option<url::Url>, + + /// A boolean value to indicate if payment response hash needs to be enabled + #[schema(default = true, example = true)] + pub enable_payment_response_hash: Option<bool>, + + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. + pub payment_response_hash_key: Option<String>, + + /// A boolean value to indicate if redirect to merchant with http post needs to be enabled + #[schema(default = false, example = true)] + pub redirect_to_merchant_with_http_post: Option<bool>, + + /// Webhook related details + pub webhook_details: Option<WebhookDetails>, + + /// Metadata is useful for storing additional, unstructured information on an object. + #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, + + /// Will be used to determine the time till which your payment will be active once the payment session starts + #[schema(value_type = u32, example = 900)] + pub order_fulfillment_time: Option<OrderFulfillmentTime>, + + /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment + #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] + pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, + + /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this business profile @@ -1936,6 +2026,10 @@ pub struct BusinessProfileCreate { pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct BusinessProfileResponse { /// The identifier for Merchant Account @@ -1958,7 +2052,7 @@ pub struct BusinessProfileResponse { #[schema(default = true, example = true)] pub enable_payment_response_hash: bool, - /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used. + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled @@ -1989,7 +2083,7 @@ pub struct BusinessProfileResponse { #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, - /// Verified applepay domains for a particular profile + /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this business profile @@ -2032,6 +2126,94 @@ pub struct BusinessProfileResponse { pub outgoing_webhook_custom_http_headers: Option<HashMap<String, Secret<String>>>, } +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive(Clone, Debug, ToSchema, Serialize)] +pub struct BusinessProfileResponse { + /// The identifier for Merchant Account + #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] + pub merchant_id: id_type::MerchantId, + + /// The identifier for business profile. This must be used for creating merchant accounts, payments and payouts + #[schema(max_length = 64, example = "pro_abcdefghijklmnopqrstuvwxyz")] + pub id: String, + + /// Name of the business profile + #[schema(max_length = 64)] + pub profile_name: String, + + /// The URL to redirect after the completion of the operation + #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] + pub return_url: Option<String>, + + /// A boolean value to indicate if payment response hash needs to be enabled + #[schema(default = true, example = true)] + pub enable_payment_response_hash: bool, + + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. + pub payment_response_hash_key: Option<String>, + + /// A boolean value to indicate if redirect to merchant with http post needs to be enabled + #[schema(default = false, example = true)] + pub redirect_to_merchant_with_http_post: bool, + + /// Webhook related details + pub webhook_details: Option<WebhookDetails>, + + /// Metadata is useful for storing additional, unstructured information on an object. + #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] + pub metadata: Option<pii::SecretSerdeValue>, + + /// Verified Apple Pay domains for a particular profile + pub applepay_verified_domains: Option<Vec<String>>, + + /// Client Secret Default expiry for all payments created under this business profile + #[schema(example = 900)] + pub session_expiry: Option<i64>, + + /// Default Payment Link config for all payment links created under this business profile + #[schema(value_type = Option<BusinessPaymentLinkConfig>)] + pub payment_link_config: Option<BusinessPaymentLinkConfig>, + + /// External 3DS authentication details + pub authentication_connector_details: Option<AuthenticationConnectorDetails>, + + // Whether to use the billing details passed when creating the intent as payment method billing + pub use_billing_as_payment_method_billing: Option<bool>, + + /// Merchant's config to support extended card info feature + pub extended_card_info_config: Option<ExtendedCardInfoConfig>, + + /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] + pub collect_shipping_details_from_wallet_connector: Option<bool>, + + /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + #[schema(default = false, example = false)] + pub collect_billing_details_from_wallet_connector: Option<bool>, + + /// Indicates if the MIT (merchant initiated transaction) payments can be made connector + /// agnostic, i.e., MITs may be processed through different connector than CIT (customer + /// initiated transaction) based on the routing rules. + /// If set to `false`, MIT will go through the same connector as the CIT. + pub is_connector_agnostic_mit_enabled: Option<bool>, + + /// Default payout link config + #[schema(value_type = Option<BusinessPayoutLinkConfig>)] + pub payout_link_config: Option<BusinessPayoutLinkConfig>, + + /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. + #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] + pub outgoing_webhook_custom_http_headers: Option<HashMap<String, Secret<String>>>, + + /// Will be used to determine the time till which your payment will be active once the payment session starts + #[schema(value_type = u32, example = 900)] + pub order_fulfillment_time: Option<OrderFulfillmentTime>, + + /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment + #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] + pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, +} + #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct BusinessProfileUpdate { @@ -2047,7 +2229,7 @@ pub struct BusinessProfileUpdate { #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, - /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a default value is used. + /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled @@ -2078,7 +2260,7 @@ pub struct BusinessProfileUpdate { #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, - /// Verified applepay domains for a particular profile + /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this business profile @@ -2097,11 +2279,11 @@ pub struct BusinessProfileUpdate { // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, - /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + /// A boolean value to indicate if customer shipping details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, - /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple pay, Google pay etc) + /// A boolean value to indicate if customer billing details needs to be collected from wallet connector (Eg. Apple Pay, Google Pay, etc.) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, diff --git a/crates/api_models/src/consts.rs b/crates/api_models/src/consts.rs new file mode 100644 index 00000000000..1a9c79080c6 --- /dev/null +++ b/crates/api_models/src/consts.rs @@ -0,0 +1,5 @@ +/// Max payment intent fulfillment expiry +pub const MAX_ORDER_FULFILLMENT_EXPIRY: i64 = 1800; + +/// Min payment intent fulfillment expiry +pub const MIN_ORDER_FULFILLMENT_EXPIRY: i64 = 60; diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 938a6f2379b..daa329a7631 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -6,6 +6,7 @@ pub mod blocklist; pub mod cards_info; pub mod conditional_configs; pub mod connector_onboarding; +pub mod consts; pub mod currency; pub mod customers; pub mod disputes; diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index fd155963968..28c0cf74414 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -77,6 +77,9 @@ pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; /// Payment intent fulfillment time (in seconds) pub const DEFAULT_INTENT_FULFILLMENT_TIME: i64 = 15 * 60; +/// Payment order fulfillment time (in seconds) +pub const DEFAULT_ORDER_FULFILLMENT_TIME: i64 = 15 * 60; + /// Default bool for Display sdk only pub const DEFAULT_DISPLAY_SDK_ONLY: bool = false; diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index 23b4f2be4fe..38b89cbfaf7 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -50,6 +50,9 @@ pub enum ParsingError { /// Failed to parse String value to Decimal value conversion because `error` #[error("Failed to parse String value to Decimal value conversion because {error}")] StringToDecimalConversionFailure { error: String }, + /// Failed to convert the given integer because of integer overflow error + #[error("Integer Overflow error")] + IntegerOverflow, } /// Validation errors. diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index cf873d4b61f..08778597375 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -1,8 +1,6 @@ use std::collections::{HashMap, HashSet}; use common_enums::AuthenticationConnectors; -// #[cfg(all(feature = "v2", feature = "business_profile_v2"))] -// use common_enums::OrderFulfillmentTimeOrigin; use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; @@ -231,7 +229,6 @@ pub struct BusinessProfile { pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, - pub intent_fulfillment_time: Option<i64>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, @@ -247,8 +244,8 @@ pub struct BusinessProfile { pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub routing_algorithm_id: Option<String>, - // pub order_fulfillment_time: Option<i64>, - // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<String>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, @@ -269,7 +266,6 @@ pub struct BusinessProfileNew { pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, - pub intent_fulfillment_time: Option<i64>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, @@ -285,8 +281,8 @@ pub struct BusinessProfileNew { pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub routing_algorithm_id: Option<String>, - // pub order_fulfillment_time: Option<i64>, - // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<String>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, @@ -304,7 +300,6 @@ pub struct BusinessProfileUpdateInternal { pub redirect_to_merchant_with_http_post: Option<bool>, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, - pub intent_fulfillment_time: Option<i64>, pub is_recon_enabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, @@ -320,8 +315,8 @@ pub struct BusinessProfileUpdateInternal { pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub routing_algorithm_id: Option<String>, - // pub order_fulfillment_time: Option<i64>, - // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<String>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, @@ -353,9 +348,8 @@ impl BusinessProfileUpdateInternal { collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers, routing_algorithm_id, - intent_fulfillment_time, - // order_fulfillment_time, - // order_fulfillment_time_origin, + order_fulfillment_time, + order_fulfillment_time_origin, frm_routing_algorithm_id, payout_routing_algorithm_id, default_fallback_routing, @@ -400,10 +394,9 @@ impl BusinessProfileUpdateInternal { outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .or(source.outgoing_webhook_custom_http_headers), routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id), - intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), - // order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time), - // order_fulfillment_time_origin: order_fulfillment_time_origin - // .or(source.order_fulfillment_time_origin), + order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time), + order_fulfillment_time_origin: order_fulfillment_time_origin + .or(source.order_fulfillment_time_origin), frm_routing_algorithm_id: frm_routing_algorithm_id.or(source.frm_routing_algorithm_id), payout_routing_algorithm_id: payout_routing_algorithm_id .or(source.payout_routing_algorithm_id), @@ -446,9 +439,8 @@ impl From<BusinessProfileNew> for BusinessProfile { .collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers: new.outgoing_webhook_custom_http_headers, routing_algorithm_id: new.routing_algorithm_id, - intent_fulfillment_time: new.intent_fulfillment_time, - // order_fulfillment_time: new.order_fulfillment_time, - // order_fulfillment_time_origin: new.order_fulfillment_time_origin, + order_fulfillment_time: new.order_fulfillment_time, + order_fulfillment_time_origin: new.order_fulfillment_time_origin, frm_routing_algorithm_id: new.frm_routing_algorithm_id, payout_routing_algorithm_id: new.payout_routing_algorithm_id, default_fallback_routing: new.default_fallback_routing, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 59822bbdfb0..12f515b9cac 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -188,7 +188,6 @@ diesel::table! { redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, - intent_fulfillment_time -> Nullable<Int8>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, @@ -204,6 +203,8 @@ diesel::table! { outgoing_webhook_custom_http_headers -> Nullable<Bytea>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, + order_fulfillment_time -> Nullable<Int8>, + order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>, #[max_length = 64] frm_routing_algorithm_id -> Nullable<Varchar>, #[max_length = 64] diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index fa9af562cf3..2af48930ede 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -420,7 +420,6 @@ pub struct BusinessProfile { pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, - pub intent_fulfillment_time: Option<i64>, pub is_recon_enabled: bool, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, @@ -435,13 +434,28 @@ pub struct BusinessProfile { pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub routing_algorithm_id: Option<String>, - // pub order_fulfillment_time: Option<i64>, - // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<String>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, } +impl BusinessProfile { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") + ))] + pub fn get_order_fulfillment_time(&self) -> Option<i64> { + self.intent_fulfillment_time + } + + #[cfg(all(feature = "v2", feature = "business_profile_v2"))] + pub fn get_order_fulfillment_time(&self) -> Option<i64> { + self.order_fulfillment_time + } +} + #[cfg(all(feature = "v2", feature = "business_profile_v2"))] #[derive(Debug)] pub struct BusinessProfileGeneralUpdate { @@ -452,7 +466,6 @@ pub struct BusinessProfileGeneralUpdate { pub redirect_to_merchant_with_http_post: Option<bool>, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, - pub intent_fulfillment_time: Option<i64>, pub is_recon_enabled: Option<bool>, pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, @@ -466,8 +479,8 @@ pub struct BusinessProfileGeneralUpdate { pub is_connector_agnostic_mit_enabled: Option<bool>, pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, pub routing_algorithm_id: Option<String>, - // pub order_fulfillment_time: Option<i64>, - // pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<String>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, @@ -507,7 +520,6 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { redirect_to_merchant_with_http_post, webhook_details, metadata, - intent_fulfillment_time, is_recon_enabled, applepay_verified_domains, payment_link_config, @@ -521,8 +533,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, routing_algorithm_id, - // order_fulfillment_time, - // order_fulfillment_time_origin, + order_fulfillment_time, + order_fulfillment_time_origin, frm_routing_algorithm_id, payout_routing_algorithm_id, default_fallback_routing, @@ -536,7 +548,6 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { redirect_to_merchant_with_http_post, webhook_details, metadata, - intent_fulfillment_time, is_recon_enabled, applepay_verified_domains, payment_link_config, @@ -552,8 +563,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .map(Encryption::from), routing_algorithm_id, - // order_fulfillment_time, - // order_fulfillment_time_origin, + order_fulfillment_time, + order_fulfillment_time_origin, frm_routing_algorithm_id, payout_routing_algorithm_id, default_fallback_routing, @@ -585,9 +596,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, routing_algorithm_id, - intent_fulfillment_time: None, - // order_fulfillment_time: None, - // order_fulfillment_time_origin: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, payout_routing_algorithm_id, default_fallback_routing: None, @@ -618,9 +628,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { outgoing_webhook_custom_http_headers: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, - intent_fulfillment_time: None, - // order_fulfillment_time: None, - // order_fulfillment_time_origin: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, }, @@ -650,9 +659,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { outgoing_webhook_custom_http_headers: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, - intent_fulfillment_time: None, - // order_fulfillment_time: None, - // order_fulfillment_time_origin: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing: None, }, @@ -682,9 +690,8 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { outgoing_webhook_custom_http_headers: None, routing_algorithm_id: None, payout_routing_algorithm_id: None, - intent_fulfillment_time: None, - // order_fulfillment_time: None, - // order_fulfillment_time_origin: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, frm_routing_algorithm_id: None, default_fallback_routing, }, @@ -730,9 +737,8 @@ impl super::behaviour::Conversion for BusinessProfile { .map(Encryption::from), routing_algorithm_id: self.routing_algorithm_id, payout_routing_algorithm_id: self.payout_routing_algorithm_id, - intent_fulfillment_time: self.intent_fulfillment_time, - // order_fulfillment_time: self.order_fulfillment_time, - // order_fulfillment_time_origin: self.order_fulfillment_time_origin, + order_fulfillment_time: self.order_fulfillment_time, + order_fulfillment_time_origin: self.order_fulfillment_time_origin, frm_routing_algorithm_id: self.frm_routing_algorithm_id, default_fallback_routing: self.default_fallback_routing, }) @@ -789,10 +795,8 @@ impl super::behaviour::Conversion for BusinessProfile { }) .await?, routing_algorithm_id: item.routing_algorithm_id, - - intent_fulfillment_time: item.intent_fulfillment_time, - // order_fulfillment_time: item.order_fulfillment_time, - // order_fulfillment_time_origin: item.order_fulfillment_time_origin, + order_fulfillment_time: item.order_fulfillment_time, + order_fulfillment_time_origin: item.order_fulfillment_time_origin, frm_routing_algorithm_id: item.frm_routing_algorithm_id, payout_routing_algorithm_id: item.payout_routing_algorithm_id, default_fallback_routing: item.default_fallback_routing, @@ -835,9 +839,8 @@ impl super::behaviour::Conversion for BusinessProfile { .outgoing_webhook_custom_http_headers .map(Encryption::from), routing_algorithm_id: self.routing_algorithm_id, - intent_fulfillment_time: self.intent_fulfillment_time, - // order_fulfillment_time: self.order_fulfillment_time, - // order_fulfillment_time_origin: self.order_fulfillment_time_origin, + order_fulfillment_time: self.order_fulfillment_time, + order_fulfillment_time_origin: self.order_fulfillment_time_origin, frm_routing_algorithm_id: self.frm_routing_algorithm_id, payout_routing_algorithm_id: self.payout_routing_algorithm_id, default_fallback_routing: self.default_fallback_routing, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 00bfe2f7c19..1f5fb068408 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3270,25 +3270,23 @@ pub fn get_frm_config_as_secret( } } -#[cfg(any(feature = "v1", feature = "v2"))] +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] pub async fn create_and_insert_business_profile( state: &SessionState, request: api::BusinessProfileCreate, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<domain::BusinessProfile> { - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "merchant_account_v2") - ))] - let business_profile_new = - admin::create_business_profile(state, merchant_account, request, key_store).await?; - - #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] - let business_profile_new = { - let _ = merchant_account; - admin::create_business_profile(state, request, key_store).await? - }; + let business_profile_new = admin::create_business_profile_from_merchant_account( + state, + merchant_account, + request, + key_store, + ) + .await?; let profile_name = business_profile_new.profile_name.clone(); @@ -3304,23 +3302,261 @@ pub async fn create_and_insert_business_profile( .attach_printable("Failed to insert Business profile because of duplication error") } -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(any(feature = "merchant_account_v2", feature = "business_profile_v2")) -))] +#[cfg(feature = "olap")] +#[async_trait::async_trait] +trait BusinessProfileCreateBridge { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") + ))] + async fn create_domain_model_from_request( + self, + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key: &domain::MerchantKeyStore, + ) -> RouterResult<domain::BusinessProfile>; + + #[cfg(all(feature = "v2", feature = "business_profile_v2"))] + async fn create_domain_model_from_request( + self, + state: &SessionState, + key: &domain::MerchantKeyStore, + merchant_id: &id_type::MerchantId, + ) -> RouterResult<domain::BusinessProfile>; +} + +#[cfg(feature = "olap")] +#[async_trait::async_trait] +impl BusinessProfileCreateBridge for api::BusinessProfileCreate { + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") + ))] + async fn create_domain_model_from_request( + self, + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + ) -> RouterResult<domain::BusinessProfile> { + use common_utils::ext_traits::AsyncExt; + + if let Some(session_expiry) = &self.session_expiry { + helpers::validate_session_expiry(session_expiry.to_owned())?; + } + + if let Some(intent_fulfillment_expiry) = &self.intent_fulfillment_time { + helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry.to_owned())?; + } + + if let Some(ref routing_algorithm) = self.routing_algorithm { + let _: api_models::routing::RoutingAlgorithm = routing_algorithm + .clone() + .parse_value("RoutingAlgorithm") + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "routing_algorithm", + }) + .attach_printable("Invalid routing algorithm given")?; + } + + // Generate a unique profile id + let profile_id = common_utils::generate_id_with_default_len("pro"); + let profile_name = self.profile_name.unwrap_or("default".to_string()); + + let current_time = date_time::now(); + + let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); + + let payment_response_hash_key = self + .payment_response_hash_key + .or(merchant_account.payment_response_hash_key.clone()) + .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); + + let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); + let outgoing_webhook_custom_http_headers = self + .outgoing_webhook_custom_http_headers + .async_map(|headers| cards::create_encrypted_data(state, key_store, headers)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; + + let payout_link_config = self + .payout_link_config + .map(|payout_conf| match payout_conf.config.validate() { + Ok(_) => Ok(payout_conf.foreign_into()), + Err(e) => Err(error_stack::report!( + errors::ApiErrorResponse::InvalidRequestData { + message: e.to_string() + } + )), + }) + .transpose()?; + + Ok(domain::BusinessProfile { + profile_id, + merchant_id: merchant_account.get_id().clone(), + profile_name, + created_at: current_time, + modified_at: current_time, + return_url: self + .return_url + .map(|return_url| return_url.to_string()) + .or(merchant_account.return_url.clone()), + enable_payment_response_hash: self + .enable_payment_response_hash + .unwrap_or(merchant_account.enable_payment_response_hash), + payment_response_hash_key: Some(payment_response_hash_key), + redirect_to_merchant_with_http_post: self + .redirect_to_merchant_with_http_post + .unwrap_or(merchant_account.redirect_to_merchant_with_http_post), + webhook_details: webhook_details.or(merchant_account.webhook_details.clone()), + metadata: self.metadata, + routing_algorithm: None, + intent_fulfillment_time: self + .intent_fulfillment_time + .map(i64::from) + .or(merchant_account.intent_fulfillment_time) + .or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)), + frm_routing_algorithm: self + .frm_routing_algorithm + .or(merchant_account.frm_routing_algorithm.clone()), + #[cfg(feature = "payouts")] + payout_routing_algorithm: self + .payout_routing_algorithm + .or(merchant_account.payout_routing_algorithm.clone()), + #[cfg(not(feature = "payouts"))] + payout_routing_algorithm: None, + is_recon_enabled: merchant_account.is_recon_enabled, + applepay_verified_domains: self.applepay_verified_domains, + payment_link_config, + session_expiry: self + .session_expiry + .map(i64::from) + .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), + authentication_connector_details: self + .authentication_connector_details + .map(ForeignInto::foreign_into), + payout_link_config, + is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + use_billing_as_payment_method_billing: self + .use_billing_as_payment_method_billing + .or(Some(true)), + collect_shipping_details_from_wallet_connector: self + .collect_shipping_details_from_wallet_connector + .or(Some(false)), + collect_billing_details_from_wallet_connector: self + .collect_billing_details_from_wallet_connector + .or(Some(false)), + outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers + .map(Into::into), + }) + } + + #[cfg(all(feature = "v2", feature = "business_profile_v2"))] + async fn create_domain_model_from_request( + self, + state: &SessionState, + key_store: &domain::MerchantKeyStore, + merchant_id: &id_type::MerchantId, + ) -> RouterResult<domain::BusinessProfile> { + if let Some(session_expiry) = &self.session_expiry { + helpers::validate_session_expiry(session_expiry.to_owned())?; + } + + // Generate a unique profile id + // TODO: the profile_id should be generated from the profile_name + let profile_id = common_utils::generate_id_with_default_len("pro"); + let profile_name = self.profile_name; + + let current_time = date_time::now(); + + let webhook_details = self.webhook_details.map(ForeignInto::foreign_into); + + let payment_response_hash_key = self + .payment_response_hash_key + .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); + + let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into); + let outgoing_webhook_custom_http_headers = self + .outgoing_webhook_custom_http_headers + .async_map(|headers| cards::create_encrypted_data(state, key_store, headers)) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; + + let payout_link_config = self + .payout_link_config + .map(|payout_conf| match payout_conf.config.validate() { + Ok(_) => Ok(payout_conf.foreign_into()), + Err(e) => Err(error_stack::report!( + errors::ApiErrorResponse::InvalidRequestData { + message: e.to_string() + } + )), + }) + .transpose()?; + + Ok(domain::BusinessProfile { + profile_id, + merchant_id: merchant_id.clone(), + profile_name, + created_at: current_time, + modified_at: current_time, + return_url: self.return_url.map(|return_url| return_url.to_string()), + enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or(true), + payment_response_hash_key: Some(payment_response_hash_key), + redirect_to_merchant_with_http_post: self + .redirect_to_merchant_with_http_post + .unwrap_or(true), + webhook_details, + metadata: self.metadata, + is_recon_enabled: false, + applepay_verified_domains: self.applepay_verified_domains, + payment_link_config, + session_expiry: self + .session_expiry + .map(i64::from) + .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), + authentication_connector_details: self + .authentication_connector_details + .map(ForeignInto::foreign_into), + payout_link_config, + is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + use_billing_as_payment_method_billing: self + .use_billing_as_payment_method_billing + .or(Some(true)), + collect_shipping_details_from_wallet_connector: self + .collect_shipping_details_from_wallet_connector + .or(Some(false)), + collect_billing_details_from_wallet_connector: self + .collect_billing_details_from_wallet_connector + .or(Some(false)), + outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers + .map(Into::into), + routing_algorithm_id: None, + frm_routing_algorithm_id: None, + payout_routing_algorithm_id: None, + order_fulfillment_time: self + .order_fulfillment_time + .map(|order_fulfillment_time| i64::from(order_fulfillment_time.into_inner())) + .or(Some(common_utils::consts::DEFAULT_ORDER_FULFILLMENT_TIME)), + order_fulfillment_time_origin: self.order_fulfillment_time_origin, + default_fallback_routing: None, + }) + } +} + +#[cfg(feature = "olap")] pub async fn create_business_profile( state: SessionState, request: api::BusinessProfileCreate, merchant_id: &id_type::MerchantId, ) -> RouterResponse<api_models::admin::BusinessProfileResponse> { - if let Some(session_expiry) = &request.session_expiry { - helpers::validate_session_expiry(session_expiry.to_owned())?; - } - - if let Some(intent_fulfillment_expiry) = &request.intent_fulfillment_time { - helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry.to_owned())?; - } - let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db @@ -3339,20 +3575,33 @@ pub async fn create_business_profile( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - if let Some(ref routing_algorithm) = request.routing_algorithm { - let _: api_models::routing::RoutingAlgorithm = routing_algorithm - .clone() - .parse_value("RoutingAlgorithm") - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "routing_algorithm", - }) - .attach_printable("Invalid routing algorithm given")?; - } + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") + ))] + let business_profile = request + .create_domain_model_from_request(&state, &merchant_account, &key_store) + .await?; - let business_profile = - create_and_insert_business_profile(&state, request, merchant_account.clone(), &key_store) - .await?; + #[cfg(all(feature = "v2", feature = "business_profile_v2"))] + let business_profile = request + .create_domain_model_from_request(&state, &key_store, merchant_account.get_id()) + .await?; + + let profile_id = business_profile.profile_id.clone(); + let business_profile = db + .insert_business_profile(key_manager_state, &key_store, business_profile) + .await + .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { + message: format!("Business Profile with the profile_id {profile_id} already exists"), + }) + .attach_printable("Failed to insert Business profile because of duplication error")?; + + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") + ))] if merchant_account.default_profile.is_some() { let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile; db.update_merchant( @@ -3372,19 +3621,6 @@ pub async fn create_business_profile( )) } -#[cfg(all( - feature = "v2", - feature = "merchant_account_v2", - feature = "business_profile_v2" -))] -pub async fn create_business_profile( - _state: SessionState, - _request: api::BusinessProfileCreate, - _merchant_id: &id_type::MerchantId, -) -> RouterResponse<api_models::admin::BusinessProfileResponse> { - todo!() -} - pub async fn list_business_profile( state: SessionState, merchant_id: id_type::MerchantId, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 32b5cc7d7b4..3ce9c9ab5af 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -4034,7 +4034,7 @@ pub async fn list_customer_payment_method( let intent_fulfillment_time = business_profile .as_ref() - .and_then(|b_profile| b_profile.intent_fulfillment_time) + .and_then(|b_profile| b_profile.get_order_fulfillment_time()) .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME); let hyperswitch_token_data = pm_list_context @@ -4307,7 +4307,7 @@ impl SavedPMLPaymentsInfo { let intent_fulfillment_time = self .business_profile .as_ref() - .and_then(|b_profile| b_profile.intent_fulfillment_time) + .and_then(|b_profile| b_profile.get_order_fulfillment_time()) .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME); ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method)) @@ -4513,7 +4513,9 @@ async fn generate_saved_pm_response( pi.is_connector_agnostic_mit_enabled, pi.requires_cvv, pi.off_session_payment_flag, - pi.business_profile.map(|profile| profile.profile_id), + pi.business_profile + .as_ref() + .map(|profile| profile.profile_id.clone()), ) }) .unwrap_or((false, false, false, Default::default())); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 30c0d8a01e8..a8ec32cb55b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4016,7 +4016,7 @@ where routing_data, connector_data, mandate_type, - business_profile.is_connector_agnostic_mit_enabled.clone(), + business_profile.is_connector_agnostic_mit_enabled, ) .await } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 81717b953ad..b2ecae090c2 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2146,7 +2146,7 @@ pub async fn store_in_vault_and_generate_ppmt( }); let intent_fulfillment_time = business_profile - .and_then(|b_profile| b_profile.intent_fulfillment_time) + .and_then(|b_profile| b_profile.get_order_fulfillment_time()) .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME); if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token { diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index 3775c8b4e2a..2257bd3e01f 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -312,7 +312,7 @@ impl SurchargeMetadata { )); } let intent_fulfillment_time = business_profile - .intent_fulfillment_time + .get_order_fulfillment_time() .unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME); redis_conn .set_hash_fields(&redis_key, value_list, Some(intent_fulfillment_time)) diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index a746f15a98f..43da2bb2bd0 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -306,7 +306,7 @@ impl MerchantConnectorAccounts { where T: std::hash::Hash + Eq, { - self.filter_and_map(|mca| mca.profile_id.as_deref() == Some(profile_id), func) + self.filter_and_map(|mca| mca.profile_id == profile_id, func) } } diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 5e3a9c49e8e..6feb30a08c6 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -254,7 +254,13 @@ struct HeaderMapStruct<'a> { #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] impl<'a> HeaderMapStruct<'a> { - pub fn get_mandatory_header_value_by_key( + pub fn from(request: &'a HttpRequest) -> Self { + HeaderMapStruct { + headers: request.headers(), + } + } + + fn get_mandatory_header_value_by_key( &self, key: String, ) -> Result<&str, error_stack::Report<ApiErrorResponse>> { @@ -271,6 +277,20 @@ impl<'a> HeaderMapStruct<'a> { key )) } + + pub fn get_merchant_id_from_header( + &self, + ) -> crate::errors::RouterResult<common_utils::id_type::MerchantId> { + self.get_mandatory_header_value_by_key(headers::X_MERCHANT_ID.into()) + .map(|val| val.to_owned()) + .and_then(|merchant_id| { + common_utils::id_type::MerchantId::wrap(merchant_id) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable( + "Error while converting MerchantId from `x-merchant-id` string header", + ) + }) + } } /// Merchant Connector - Create @@ -454,25 +474,13 @@ pub async fn connector_retrieve( let id = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner(); - let header_map = HeaderMapStruct { - headers: req.headers(), - }; - - let merchant_id = match header_map - .get_mandatory_header_value_by_key(headers::X_MERCHANT_ID.into()) - .map(|val| val.to_owned()) - .and_then(|merchant_id| { - common_utils::id_type::MerchantId::wrap(merchant_id) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable( - "Error while converting MerchantId from merchant_id string header", - ) - }) { + let merchant_id = match HeaderMapStruct::from(&req).get_merchant_id_from_header() { Ok(val) => val, Err(err) => { return api::log_and_return_error_response(err); } }; + api::server_wrap( flow, state, @@ -734,16 +742,7 @@ pub async fn connector_delete( let header_map = HeaderMapStruct { headers: req.headers(), }; - let merchant_id = match header_map - .get_mandatory_header_value_by_key(headers::X_MERCHANT_ID.into()) - .map(|val| val.to_owned()) - .and_then(|merchant_id| { - common_utils::id_type::MerchantId::wrap(merchant_id) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable( - "Error while converting MerchantId from merchant_id string header", - ) - }) { + let merchant_id = match header_map.get_merchant_id_from_header() { Ok(val) => val, Err(err) => { return api::log_and_return_error_response(err); @@ -817,6 +816,11 @@ pub async fn merchant_account_toggle_all_kv( .await } +#[cfg(all( + feature = "olap", + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] #[instrument(skip_all, fields(flow = ?Flow::BusinessProfileCreate))] pub async fn business_profile_create( state: web::Data<AppState>, @@ -846,6 +850,47 @@ pub async fn business_profile_create( )) .await } + +#[cfg(all(feature = "olap", feature = "v2", feature = "business_profile_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileCreate))] +pub async fn business_profile_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<admin::BusinessProfileCreate>, +) -> HttpResponse { + let flow = Flow::BusinessProfileCreate; + let payload = json_payload.into_inner(); + + let merchant_id = match HeaderMapStruct::from(&req).get_merchant_id_from_header() { + Ok(val) => val, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| create_business_profile(state, req, &merchant_id), + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id: merchant_id.clone(), + required_permission: Permission::MerchantAccountWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] #[instrument(skip_all, fields(flow = ?Flow::BusinessProfileRetrieve))] pub async fn business_profile_retrieve( state: web::Data<AppState>, @@ -873,6 +918,43 @@ pub async fn business_profile_retrieve( )) .await } + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileRetrieve))] +pub async fn business_profile_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> HttpResponse { + let flow = Flow::BusinessProfileRetrieve; + let profile_id = path.into_inner(); + + let merchant_id = match HeaderMapStruct::from(&req).get_merchant_id_from_header() { + Ok(val) => val, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + profile_id, + |state, _, profile_id, _| retrieve_business_profile(state, profile_id, merchant_id.clone()), + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id: merchant_id.clone(), + required_permission: Permission::MerchantAccountRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::BusinessProfileUpdate))] pub async fn business_profile_update( state: web::Data<AppState>, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2bb1a5eee8e..5fe71a6a8da 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1466,8 +1466,10 @@ impl BusinessProfile { pub fn server(state: AppState) -> Scope { web::scope("/v2/profiles") .app_data(web::Data::new(state)) + .service(web::resource("").route(web::post().to(business_profile_create))) .service( web::scope("/{profile_id}") + .service(web::resource("").route(web::get().to(business_profile_retrieve))) .service( web::resource("/fallback_routing") .route(web::get().to(routing::routing_retrieve_default_config)) diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index e6266f148f1..30edfc187b8 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -308,7 +308,7 @@ pub async fn routing_update_default_config( auth.merchant_account, auth.key_store, wrapper.profile_id, - wrapper.updated_config, + wrapper.connectors, ) }, #[cfg(not(feature = "release"))] diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 56a6c4ec2b2..eb56e3a1db1 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -111,7 +111,7 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { } #[cfg(all( any(feature = "v1", feature = "v2"), - not(any(feature = "business_profile_v2", feature = "merchant_account_v2",)) + not(feature = "business_profile_v2") ))] impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse { type Error = error_stack::Report<errors::ParsingError>; @@ -166,11 +166,7 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse { } } -#[cfg(all( - feature = "v2", - feature = "merchant_account_v2", - feature = "business_profile_v2" -))] +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse { type Error = error_stack::Report<errors::ParsingError>; @@ -187,9 +183,15 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse { }) .transpose()?; + let order_fulfillment_time = item + .order_fulfillment_time + .map(|time| api_models::admin::OrderFulfillmentTime::new(time)) + .transpose() + .change_context(errors::ParsingError::IntegerOverflow)?; + Ok(Self { merchant_id: item.merchant_id, - profile_id: item.profile_id, + id: item.profile_id, profile_name: item.profile_name, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, @@ -197,14 +199,6 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse { redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, webhook_details: item.webhook_details.map(ForeignInto::foreign_into), metadata: item.metadata, - // TODO: Remove routing algorithm from api models of business profile - routing_algorithm: todo!(), - intent_fulfillment_time: item.intent_fulfillment_time, - // TODO: Remove frm algorithm from api models of business profile - frm_routing_algorithm: todo!(), - #[cfg(feature = "payouts")] - // TODO: Remove payout algorithm from api models of business profile - payout_routing_algorithm: todo!(), applepay_verified_domains: item.applepay_verified_domains, payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into), session_expiry: item.session_expiry, @@ -223,27 +217,17 @@ impl ForeignTryFrom<domain::BusinessProfile> for BusinessProfileResponse { .collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, + order_fulfillment_time, + order_fulfillment_time_origin: item.order_fulfillment_time_origin, }) } } -#[cfg(all( - feature = "v2", - feature = "merchant_account_v2", - feature = "business_profile_v2" -))] -pub async fn create_business_profile( - _state: &SessionState, - _request: BusinessProfileCreate, - _key_store: &MerchantKeyStore, -) -> Result<domain::BusinessProfile, error_stack::Report<errors::ApiErrorResponse>> { - todo!() -} #[cfg(all( any(feature = "v1", feature = "v2"), not(any(feature = "merchant_account_v2", feature = "business_profile_v2")) ))] -pub async fn create_business_profile( +pub async fn create_business_profile_from_merchant_account( state: &SessionState, merchant_account: domain::MerchantAccount, request: BusinessProfileCreate, @@ -266,7 +250,7 @@ pub async fn create_business_profile( .or(merchant_account.payment_response_hash_key) .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); - let payment_link_config_value = request.payment_link_config.map(ForeignInto::foreign_into); + let payment_link_config = request.payment_link_config.map(ForeignInto::foreign_into); let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers .async_map(|headers| { @@ -325,7 +309,7 @@ pub async fn create_business_profile( payout_routing_algorithm: None, is_recon_enabled: merchant_account.is_recon_enabled, applepay_verified_domains: request.applepay_verified_domains, - payment_link_config: payment_link_config_value, + payment_link_config, session_expiry: request .session_expiry .map(i64::from) diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index f4e4257c02b..94405a0249b 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -700,8 +700,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { }) } - #[cfg(feature = "olap")] - #[cfg(all(feature = "v2", feature = "customer_v2"))] + #[cfg(all(feature = "olap", feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn filter_payouts_and_attempts( &self, @@ -765,7 +764,11 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { }) } - #[cfg(feature = "olap")] + #[cfg(all( + any(feature = "v1", feature = "v2"), + feature = "olap", + not(feature = "customer_v2") + ))] #[instrument(skip_all)] async fn filter_active_payout_ids_by_constraints( &self, @@ -841,6 +844,16 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { .into() }) } + + #[cfg(all(feature = "olap", feature = "v2", feature = "customer_v2"))] + #[instrument(skip_all)] + async fn filter_active_payout_ids_by_constraints( + &self, + merchant_id: &common_utils::id_type::MerchantId, + constraints: &PayoutFetchConstraints, + ) -> error_stack::Result<Vec<String>, StorageError> { + todo!() + } } impl DataModelExt for Payouts { diff --git a/justfile b/justfile index c3cea28c674..ab50ec03013 100644 --- a/justfile +++ b/justfile @@ -63,6 +63,21 @@ check_v2 *FLAGS: cargo check {{ check_flags }} --features "${FEATURES}" {{ FLAGS }} set +x +run_v2: + #! /usr/bin/env bash + set -euo pipefail + + FEATURES="$(cargo metadata --all-features --format-version 1 --no-deps | \ + jq -r ' + [ .packages[] | select(.name == "router") | .features | keys[] # Obtain features of `router` package + | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ] # Select v2 features + | join(",") # Construct a comma-separated string of features for passing to `cargo` + ')" + + set -x + cargo run --package router --features "${FEATURES}" + set +x + check *FLAGS: #! /usr/bin/env bash set -euo pipefail diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql index 94c02697c50..8d02eca5385 100644 --- a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql +++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql @@ -1,22 +1,17 @@ -- This adds back dropped columns in `up.sql`. -- However, if the old columns were dropped, then we won't have data previously -- stored in these columns. -ALTER TABLE - business_profile -ADD - COLUMN routing_algorithm JSON DEFAULT NULL, - -- ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, -ADD - COLUMN frm_routing_algorithm JSONB DEFAULT NULL, -ADD - COLUMN payout_routing_algorithm JSONB DEFAULT NULL; +ALTER TABLE business_profile +ADD COLUMN routing_algorithm JSON DEFAULT NULL, + ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, + ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL, + ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL; -ALTER TABLE - business_profile DROP COLUMN routing_algorithm_id, - -- DROP COLUMN order_fulfillment_time, - -- DROP COLUMN order_fulfillment_time_origin, +ALTER TABLE business_profile DROP COLUMN routing_algorithm_id, + DROP COLUMN order_fulfillment_time, + DROP COLUMN order_fulfillment_time_origin, DROP COLUMN frm_routing_algorithm_id, DROP COLUMN payout_routing_algorithm_id, DROP COLUMN default_fallback_routing; --- DROP TYPE "OrderFulfillmentTimeOrigin"; \ No newline at end of file +DROP TYPE "OrderFulfillmentTimeOrigin"; diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql index d2275ad2362..6f65cf01997 100644 --- a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql +++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql @@ -1,21 +1,16 @@ --- CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm'); -ALTER TABLE - business_profile -ADD - COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL, - -- ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL, - -- ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL, -ADD - COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL, -ADD - COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL, -ADD - COLUMN default_fallback_routing JSONB DEFAULT NULL; +CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm'); + +ALTER TABLE business_profile +ADD COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL, + ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL, + ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL, + ADD COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL, + ADD COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL, + ADD COLUMN default_fallback_routing JSONB DEFAULT NULL; -- Note: This query should not be run on higher environments as this leads to data loss. -- The application will work fine even without these queries being run. -ALTER TABLE - business_profile DROP COLUMN routing_algorithm, - -- DROP COLUMN intent_fulfillment_time, +ALTER TABLE business_profile DROP COLUMN routing_algorithm, + DROP COLUMN intent_fulfillment_time, DROP COLUMN frm_routing_algorithm, - DROP COLUMN payout_routing_algorithm; \ No newline at end of file + DROP COLUMN payout_routing_algorithm;
feat
business profile v2 create and retrieve endpoint (#5606)
8032e0290b0a0ee33a640740b3bd4567a939712c
2023-06-18 20:36:57
Sangamesh Kulkarni
feat: applepay through trustpay (#1422)
false
diff --git a/config/config.example.toml b/config/config.example.toml index cb058a50945..b8d5ad0a07d 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -112,6 +112,9 @@ basilisk_host = "" # Basilisk host locker_setup = "legacy_locker" # With locker to use while in the deployed environment (eg. legacy_locker, basilisk_locker) locker_signing_key_id = "1" # Key_id to sign basilisk hs locker +[delayed_session_response] +connectors_with_delayed_session_response = "trustpay" # List of connectors which has delayed session response + [jwekey] # 4 priv/pub key pair locker_key_identifier1 = "" # key identifier for key rotation , should be same as basilisk locker_key_identifier2 = "" # key identifier for key rotation , should be same as basilisk diff --git a/config/development.toml b/config/development.toml index cc8bb1e03ad..70389c38d46 100644 --- a/config/development.toml +++ b/config/development.toml @@ -262,3 +262,6 @@ refund_duration = 1000 refund_tolerance = 100 refund_retrieve_duration = 500 refund_retrieve_tolerance = 100 + +[delayed_session_response] +connectors_with_delayed_session_response = "trustpay" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 23432aa2dd4..21321f5cb56 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -148,6 +148,9 @@ cards = [ "zen", ] +[delayed_session_response] +connectors_with_delayed_session_response = "trustpay" + [scheduler] stream = "SCHEDULER_STREAM" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5363f396f0a..6e8542c518c 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -829,6 +829,8 @@ pub enum WalletData { ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), + /// Wallet data for apple pay third party sdk flow + ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow @@ -864,6 +866,9 @@ pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct ApplePayThirdPartySdkData {} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} @@ -1125,6 +1130,8 @@ pub enum NextActionData { DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, + /// contains third party sdk session token response + ThirdPartySdkSessionToken { session_token: Option<SessionToken> }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -1679,7 +1686,7 @@ pub struct PaymentsSessionRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, @@ -1687,7 +1694,7 @@ pub struct GpayAllowedMethodsParameters { pub allowed_card_networks: Vec<String>, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector pub gateway: String, @@ -1703,7 +1710,7 @@ pub struct GpayTokenParameters { pub stripe_publishable_key: Option<String>, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] @@ -1712,7 +1719,7 @@ pub struct GpayTokenizationSpecification { pub parameters: GpayTokenParameters, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] @@ -1723,7 +1730,7 @@ pub struct GpayAllowedPaymentMethods { pub tokenization_specification: GpayTokenizationSpecification, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] @@ -1736,7 +1743,7 @@ pub struct GpayTransactionInfo { pub total_price: String, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The name of the merchant pub merchant_name: String, @@ -1802,7 +1809,7 @@ pub struct SessionTokenInfo { pub initiative_context: String, } -#[derive(Debug, Clone, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { @@ -1814,9 +1821,11 @@ pub enum SessionToken { Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), + /// Whenever there is no session token response or an error in session response + NoSessionTokenReceived, } -#[derive(Debug, Clone, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpaySessionTokenResponse { /// The merchant info @@ -1828,7 +1837,7 @@ pub struct GpaySessionTokenResponse { pub connector: String, } -#[derive(Debug, Clone, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna @@ -1837,26 +1846,58 @@ pub struct KlarnaSessionTokenResponse { pub session_id: String, } -#[derive(Debug, Clone, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// The session token for PayPal pub session_token: String, } -#[derive(Debug, Clone, serde::Serialize, ToSchema)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay pub session_token_data: ApplePaySessionResponse, /// Payment request object for Apple Pay - pub payment_request_data: ApplePayPaymentRequest, + pub payment_request_data: Option<ApplePayPaymentRequest>, + /// The session token is w.r.t this connector pub connector: String, + /// Identifier for the delayed session response + pub delayed_session_token: bool, + /// The next action for the sdk (ex: calling confirm or sync call) + pub sdk_next_action: SdkNextAction, } -#[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)] +#[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] +pub struct SdkNextAction { + /// The type of next action + pub next_action: NextActionCall, +} + +#[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum NextActionCall { + /// The next action call is confirm + Confirm, + /// The next action call is sync + Sync, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(untagged)] +pub enum ApplePaySessionResponse { + /// We get this session response, when third party sdk is involved + ThirdPartySdk(ThirdPartySdkSessionResponse), + /// We get this session response, when there is no involvement of third party sdk + /// This is the common response most of the times + NoThirdPartySdk(NoThirdPartySdkSessionResponse), + /// This is for the empty session response + NoSessionResponse, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] -pub struct ApplePaySessionResponse { +pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires @@ -1881,7 +1922,22 @@ pub struct ApplePaySessionResponse { pub psp_id: String, } -#[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +pub struct ThirdPartySdkSessionResponse { + pub secrets: SecretInfoToInitiateSdk, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] +pub struct SecretInfoToInitiateSdk { + // Authorization secrets used by client to initiate sdk + #[schema(value_type = String)] + pub display: Secret<String>, + // Authorization secrets used by client for payment + #[schema(value_type = String)] + pub payment: Secret<String>, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] @@ -1894,16 +1950,16 @@ pub struct ApplePayPaymentRequest { pub merchant_capabilities: Vec<String>, /// The list of supported networks pub supported_networks: Vec<String>, - pub merchant_identifier: String, + pub merchant_identifier: Option<String>, } -#[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] - pub total_type: String, + pub total_type: Option<String>, /// The total amount for the payment pub amount: String, } diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 10906a59c93..7f893d9abda 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -657,6 +657,9 @@ pub enum StripeNextAction { DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData, }, + ThirdPartySdkSessionToken { + session_token: Option<payments::SessionToken>, + }, } pub(crate) fn into_stripe_next_action( @@ -677,5 +680,8 @@ pub(crate) fn into_stripe_next_action( } => StripeNextAction::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, }, + payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { + StripeNextAction::ThirdPartySdkSessionToken { session_token } + } }) } diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index b2eada91611..5d4514afcc0 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -317,6 +317,9 @@ pub enum StripeNextAction { DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData, }, + ThirdPartySdkSessionToken { + session_token: Option<payments::SessionToken>, + }, } pub(crate) fn into_stripe_next_action( @@ -337,6 +340,9 @@ pub(crate) fn into_stripe_next_action( } => StripeNextAction::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, }, + payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { + StripeNextAction::ThirdPartySdkSessionToken { session_token } + } }) } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index a14587cff1f..b2bc1a869e5 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -83,6 +83,7 @@ pub struct Settings { pub dummy_connector: DummyConnector, #[cfg(feature = "email")] pub email: EmailSettings, + pub delayed_session_response: DelayedSessionConfig, } #[derive(Debug, Deserialize, Clone, Default)] @@ -507,6 +508,27 @@ pub struct FileUploadConfig { pub bucket_name: String, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct DelayedSessionConfig { + #[serde(deserialize_with = "delayed_session_deser")] + pub connectors_with_delayed_session_response: HashSet<api_models::enums::Connector>, +} + +fn delayed_session_deser<'a, D>( + deserializer: D, +) -> Result<HashSet<api_models::enums::Connector>, D::Error> +where + D: Deserializer<'a>, +{ + let value = <String>::deserialize(deserializer)?; + value + .trim() + .split(',') + .map(api_models::enums::Connector::from_str) + .collect::<Result<_, _>>() + .map_err(D::Error::custom) +} + impl Settings { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 2eb438d05fe..e7dc7473e9f 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -1,4 +1,4 @@ -use api_models::enums as api_enums; +use api_models::{enums as api_enums, payments}; use base64::Engine; use common_utils::{ errors::CustomResult, @@ -321,11 +321,12 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons let wallet_token = consts::BASE64_ENGINE .decode(response.wallet_token.clone().expose()) .into_report() - .change_context(errors::ConnectorError::ParsingFailed)?; + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; - let session_response: api_models::payments::ApplePaySessionResponse = wallet_token[..] - .parse_struct("ApplePayResponse") - .change_context(errors::ConnectorError::ParsingFailed)?; + let session_response: api_models::payments::NoThirdPartySdkSessionResponse = + wallet_token[..] + .parse_struct("NoThirdPartySdkSessionResponse") + .change_context(errors::ConnectorError::ParsingFailed)?; let metadata = item.data.get_connector_meta()?.expose(); let applepay_metadata = metadata @@ -338,13 +339,16 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons response: Ok(types::PaymentsResponseData::SessionResponse { session_token: types::api::SessionToken::ApplePay(Box::new( api_models::payments::ApplepaySessionTokenResponse { - session_token_data: session_response, - payment_request_data: api_models::payments::ApplePayPaymentRequest { + session_token_data: + api_models::payments::ApplePaySessionResponse::NoThirdPartySdk( + session_response, + ), + payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { country_code: item.data.get_billing_country()?, currency_code: item.data.request.currency.to_string(), total: api_models::payments::AmountInfo { label: applepay_metadata.data.payment_request_data.label, - total_type: "final".to_string(), + total_type: Some("final".to_string()), amount: item.data.request.amount.to_string(), }, merchant_capabilities: applepay_metadata @@ -355,12 +359,20 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons .data .payment_request_data .supported_networks, - merchant_identifier: applepay_metadata - .data - .session_token_data - .merchant_identifier, - }, + merchant_identifier: Some( + applepay_metadata + .data + .session_token_data + .merchant_identifier, + ), + }), connector: "bluesnap".to_string(), + delayed_session_token: false, + sdk_next_action: { + payments::SdkNextAction { + next_action: payments::NextActionCall::Confirm, + } + }, }, )), }), diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index ca0e35d6607..8001c0afcec 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2167,8 +2167,11 @@ impl<F, T> }; Ok(Self { response: Ok(types::PaymentsResponseData::PreProcessingResponse { - pre_processing_id: item.response.id, + pre_processing_id: types::PreprocessingResponseId::PreProcessingId( + item.response.id, + ), connector_metadata: Some(connector_metadata), + session_token: None, }), status, ..item.data diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index 76371d76918..93fad702a17 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -343,6 +343,102 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme { } +impl api::PaymentsPreProcessing for Trustpay {} + +impl + ConnectorIntegration< + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > for Trustpay +{ + fn get_headers( + &self, + req: &types::PaymentsPreProcessingRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsPreProcessingType::get_content_type(self) + .to_string() + .into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}{}", self.base_url(connectors), "api/v1/intent")) + } + + fn get_request_body( + &self, + req: &types::PaymentsPreProcessingRouterData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let create_intent_req = trustpay::TrustpayCreateIntentRequest::try_from(req)?; + let trustpay_req = + utils::Encode::<trustpay::TrustpayCreateIntentRequest>::url_encode(&create_intent_req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(trustpay_req)) + } + + fn build_request( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let req = Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .body(types::PaymentsPreProcessingType::get_request_body( + self, req, + )?) + .build(), + ); + Ok(req) + } + + fn handle_response( + &self, + data: &types::PaymentsPreProcessingRouterData, + res: Response, + ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: trustpay::TrustpayCreateIntentResponse = res + .response + .parse_struct("TrustpayCreateIntentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl api::PaymentSession for Trustpay {} impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index ebb53d66830..a54f73175ca 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -16,6 +16,7 @@ use crate::{ core::errors, services, types::{self, api, storage::enums, BrowserInformation}, + utils::OptionExt, }; type Error = error_stack::Report<errors::ConnectorError>; @@ -474,7 +475,7 @@ pub struct PaymentsResponseCards { pub status: i64, pub description: Option<String>, pub instance_id: String, - pub payment_status: String, + pub payment_status: Option<String>, pub payment_description: Option<String>, pub redirect_url: Option<Url>, pub redirect_params: Option<HashMap<String, String>>, @@ -553,8 +554,13 @@ fn handle_cards_response( ), errors::ConnectorError, > { + // By default, payment status is pending(000.200.000 status code) let (status, msg) = get_transaction_status( - response.payment_status.as_str(), + response + .payment_status + .to_owned() + .unwrap_or("000.200.000".to_string()) + .as_str(), response.redirect_url.clone(), )?; let form_fields = response.redirect_params.unwrap_or_default(); @@ -567,7 +573,9 @@ fn handle_cards_response( }); let error = if msg.is_some() { Some(types::ErrorResponse { - code: response.payment_status, + code: response + .payment_status + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: msg.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: None, status_code, @@ -802,6 +810,164 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, TrustpayAuthUpdateResponse, T, t } } +#[derive(Default, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TrustpayCreateIntentRequest { + pub amount: String, + pub currency: String, + // If true, Apple Pay will be initialized + pub init_apple_pay: Option<bool>, +} + +impl TryFrom<&types::PaymentsSessionRouterData> for TrustpayCreateIntentRequest { + type Error = Error; + fn try_from(item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.request.amount.to_string(), + currency: item.request.currency.to_string(), + init_apple_pay: Some(true), + }) + } +} + +impl TryFrom<&types::PaymentsPreProcessingRouterData> for TrustpayCreateIntentRequest { + type Error = Error; + fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { + Ok(Self { + amount: item + .request + .amount + .get_required_value("amount") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })? + .to_string(), + currency: item + .request + .currency + .get_required_value("currency") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })? + .to_string(), + init_apple_pay: Some(true), + }) + } +} + +#[derive(Default, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TrustpayCreateIntentResponse { + // TrustPay's authorization secrets used by client + pub secrets: SdkSecretInfo, + // Data object to be used for Apple Pay + pub apple_init_result_data: TrustpayApplePayResponse, + // Unique operation/transaction identifier + pub instance_id: String, +} + +#[derive(Default, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SdkSecretInfo { + pub display: Secret<String>, + pub payment: Secret<String>, +} + +#[derive(Default, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TrustpayApplePayResponse { + pub country_code: api_models::enums::CountryAlpha2, + pub currency_code: String, + pub supported_networks: Vec<String>, + pub merchant_capabilities: Vec<String>, + pub total: ApplePayTotalInfo, +} + +#[derive(Default, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplePayTotalInfo { + pub label: String, + pub amount: String, +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, TrustpayCreateIntentResponse, T, types::PaymentsResponseData>, + > for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = Error; + fn try_from( + item: types::ResponseRouterData< + F, + TrustpayCreateIntentResponse, + T, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let response = item.response; + + Ok(Self { + response: Ok(types::PaymentsResponseData::PreProcessingResponse { + connector_metadata: None, + pre_processing_id: types::PreprocessingResponseId::ConnectorTransactionId( + response.instance_id, + ), + session_token: Some(types::api::SessionToken::ApplePay(Box::new( + api_models::payments::ApplepaySessionTokenResponse { + session_token_data: + api_models::payments::ApplePaySessionResponse::ThirdPartySdk( + api_models::payments::ThirdPartySdkSessionResponse { + secrets: response.secrets.into(), + }, + ), + payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { + country_code: response.apple_init_result_data.country_code, + currency_code: response.apple_init_result_data.currency_code.clone(), + supported_networks: response + .apple_init_result_data + .supported_networks + .clone(), + merchant_capabilities: response + .apple_init_result_data + .merchant_capabilities + .clone(), + total: response.apple_init_result_data.total.into(), + merchant_identifier: None, + }), + connector: "trustpay".to_string(), + delayed_session_token: true, + sdk_next_action: { + api_models::payments::SdkNextAction { + next_action: api_models::payments::NextActionCall::Sync, + } + }, + }, + ))), + }), + ..item.data + }) + } +} + +impl From<SdkSecretInfo> for api_models::payments::SecretInfoToInitiateSdk { + fn from(value: SdkSecretInfo) -> Self { + Self { + display: value.display, + payment: value.payment, + } + } +} + +impl From<ApplePayTotalInfo> for api_models::payments::AmountInfo { + fn from(value: ApplePayTotalInfo) -> Self { + Self { + label: value.label, + amount: value.amount, + total_type: None, + } + } +} + #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayRefundRequestCards { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b2ab1b74c11..8fe2d45f139 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -156,7 +156,7 @@ where &merchant_account, connector, &operation, - &payment_data, + &mut payment_data, &customer, call_connector_action, tokenization_action, @@ -399,6 +399,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { .and_then(|next_action_data| match next_action_data { api_models::payments::NextActionData::RedirectToUrl { redirect_to_url } => Some(redirect_to_url), api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None, + api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None }) .ok_or(errors::ApiErrorResponse::InternalServerError) .into_report() @@ -489,7 +490,7 @@ pub async fn call_connector_service<F, Op, Req>( merchant_account: &domain::MerchantAccount, connector: api::ConnectorData, _operation: &Op, - payment_data: &PaymentData<F>, + payment_data: &mut PaymentData<F>, customer: &Option<domain::Customer>, call_connector_action: CallConnectorAction, tokenization_action: TokenizationAction, @@ -542,6 +543,14 @@ where ) .await?; + if let Ok(types::PaymentsResponseData::PreProcessingResponse { + session_token: Some(session_token), + .. + }) = router_data.response.to_owned() + { + payment_data.sessions_token.push(session_token); + }; + let router_data_res = if should_continue_payment { router_data .decide_flows( @@ -590,7 +599,6 @@ where for session_connector_data in connectors.iter() { let connector_id = session_connector_data.connector.connector.id(); - let router_data = payment_data .construct_router_data(state, connector_id, merchant_account, customer) .await?; @@ -612,10 +620,17 @@ where let connector_name = session_connector.connector.connector_name.to_string(); match connector_res { Ok(connector_response) => { - if let Ok(types::PaymentsResponseData::SessionResponse { session_token }) = + if let Ok(types::PaymentsResponseData::SessionResponse { session_token, .. }) = connector_response.response { - payment_data.sessions_token.push(session_token); + // If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error + // In case of error, that error is already logged + if !matches!( + session_token, + api_models::payments::SessionToken::NoSessionTokenReceived, + ) { + payment_data.sessions_token.push(session_token); + } } } Err(connector_error) => { @@ -716,17 +731,17 @@ where } } -async fn complete_preprocessing_steps_if_required<F, Req, Res>( +async fn complete_preprocessing_steps_if_required<F, Req>( state: &AppState, connector: &api::ConnectorData, payment_data: &PaymentData<F>, - router_data: types::RouterData<F, Req, Res>, + router_data: types::RouterData<F, Req, types::PaymentsResponseData>, should_continue_payment: bool, -) -> RouterResult<(types::RouterData<F, Req, Res>, bool)> +) -> RouterResult<(types::RouterData<F, Req, types::PaymentsResponseData>, bool)> where F: Send + Clone + Sync, Req: Send + Sync, - types::RouterData<F, Req, Res>: Feature<F, Req> + Send, + types::RouterData<F, Req, types::PaymentsResponseData>: Feature<F, Req> + Send, dyn api::Connector: services::api::ConnectorIntegration<F, Req, types::PaymentsResponseData>, { //TODO: For ACH transfers, if preprocessing_step is not required for connectors encountered in future, add the check @@ -744,6 +759,16 @@ where } _ => (router_data, should_continue_payment), }, + Some(api_models::payments::PaymentMethodData::Wallet(_)) => { + if connector.connector_name.to_string() == *"trustpay" { + ( + router_data.preprocessing_steps(state, connector).await?, + false, + ) + } else { + (router_data, should_continue_payment) + } + } _ => (router_data, should_continue_payment), }; @@ -869,7 +894,6 @@ where .payment_method .get_required_value("payment_method")?; let payment_method_type = &payment_data.payment_attempt.payment_method_type; - let is_connector_tokenization_enabled = is_payment_method_tokenization_enabled_for_connector( state, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 2d052b210ea..4abbe9291f6 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -647,7 +647,6 @@ default_imp_for_pre_processing_steps!( connector::Payu, connector::Rapyd, connector::Shift4, - connector::Trustpay, connector::Worldline, connector::Worldpay, connector::Zen diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index f5043c69125..1efc09ffbc3 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -337,6 +337,7 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPreProcessingData Ok(Self { email: data.email, currency: Some(data.currency), + amount: Some(data.amount), }) } } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index ba1735b1d0f..f30ff80a48c 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -1,7 +1,7 @@ use api_models::payments as payment_types; use async_trait::async_trait; use common_utils::ext_traits::ByteSliceExt; -use error_stack::{report, ResultExt}; +use error_stack::{Report, ResultExt}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ @@ -10,7 +10,7 @@ use crate::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, transformers, PaymentData}, }, - headers, + headers, logger, routes::{self, metrics}, services, types::{self, api, domain}, @@ -78,18 +78,22 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio } } -fn mk_applepay_session_request( - state: &routes::AppState, - router_data: &types::PaymentsSessionRouterData, -) -> RouterResult<(services::Request, payment_types::ApplepaySessionTokenData)> { - let connector_metadata = router_data.connector_meta_data.clone(); - - let applepay_metadata = connector_metadata +fn get_applepay_metadata( + connector_metadata: Option<common_utils::pii::SecretSerdeValue>, +) -> RouterResult<payment_types::ApplepaySessionTokenData> { + connector_metadata .parse_value::<payment_types::ApplepaySessionTokenData>("ApplepaySessionTokenData") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_metadata".to_string(), expected_format: "applepay_metadata_format".to_string(), - })?; + }) +} + +fn mk_applepay_session_request( + state: &routes::AppState, + router_data: &types::PaymentsSessionRouterData, +) -> RouterResult<services::Request> { + let applepay_metadata = get_applepay_metadata(router_data.connector_meta_data.clone())?; let request = payment_types::ApplepaySessionRequest { merchant_identifier: applepay_metadata .data @@ -134,14 +138,10 @@ fn mk_applepay_session_request( .clone(), )) .add_certificate_key(Some( - applepay_metadata - .data - .session_token_data - .certificate_keys - .clone(), + applepay_metadata.data.session_token_data.certificate_keys, )) .build(); - Ok((session_request, applepay_metadata)) + Ok(session_request) } async fn create_applepay_session_token( @@ -149,83 +149,138 @@ async fn create_applepay_session_token( router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, ) -> RouterResult<types::PaymentsSessionRouterData> { - let (applepay_session_request, applepay_metadata) = - mk_applepay_session_request(state, router_data)?; - let response = services::call_connector_api(state, applepay_session_request) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failure in calling connector api")?; - let session_response: payment_types::ApplePaySessionResponse = match response { - Ok(resp) => resp - .response - .parse_struct("ApplePaySessionResponse") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to parse ApplePaySessionResponse struct"), - Err(err) => { - let error_response: payment_types::ApplepayErrorResponse = err - .response - .parse_struct("ApplepayErrorResponse") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to parse ApplepayErrorResponse struct")?; - Err( - report!(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( - "Failed with {} status code and the error response is {:?}", - err.status_code, error_response - )), - ) - } - }?; + let connectors_with_delayed_response = &state + .conf + .delayed_session_response + .connectors_with_delayed_session_response; - let amount_info = payment_types::AmountInfo { - label: applepay_metadata.data.payment_request_data.label, - total_type: "final".to_string(), - amount: connector::utils::to_currency_base_unit( - router_data.request.amount, - router_data.request.currency, + let connector_name = connector.connector_name; + let delayed_response = connectors_with_delayed_response.contains(&connector_name); + + if delayed_response { + let delayed_response_apple_pay_session = + Some(payment_types::ApplePaySessionResponse::NoSessionResponse); + create_apple_pay_session_response( + router_data, + delayed_response_apple_pay_session, + None, // Apple pay payment request will be none for delayed session response + connector_name.to_string(), + delayed_response, + payment_types::NextActionCall::Confirm, ) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to convert currency to base unit")?, - }; + } else { + let applepay_metadata = get_applepay_metadata(router_data.connector_meta_data.clone())?; - let applepay_payment_request = payment_types::ApplePayPaymentRequest { - country_code: router_data - .request - .country - .to_owned() - .get_required_value("country_code") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "country_code", + let amount_info = payment_types::AmountInfo { + label: applepay_metadata.data.payment_request_data.label, + total_type: Some("final".to_string()), + amount: connector::utils::to_currency_base_unit( + router_data.request.amount, + router_data.request.currency, + ) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert currency to base unit".to_string(), })?, - currency_code: router_data.request.currency.to_string(), - total: amount_info, - merchant_capabilities: applepay_metadata - .data - .payment_request_data - .merchant_capabilities, - supported_networks: applepay_metadata - .data - .payment_request_data - .supported_networks, - merchant_identifier: applepay_metadata - .data - .session_token_data - .merchant_identifier, - }; + }; - let response_router_data = types::PaymentsSessionRouterData { - response: Ok(types::PaymentsResponseData::SessionResponse { - session_token: payment_types::SessionToken::ApplePay(Box::new( - payment_types::ApplepaySessionTokenResponse { - session_token_data: session_response, - payment_request_data: applepay_payment_request, - connector: connector.connector_name.to_string(), - }, - )), - }), - ..router_data.clone() - }; + let applepay_payment_request = payment_types::ApplePayPaymentRequest { + country_code: router_data + .request + .country + .to_owned() + .get_required_value("country_code") + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "country_code", + })?, + currency_code: router_data.request.currency.to_string(), + total: amount_info, + merchant_capabilities: applepay_metadata + .data + .payment_request_data + .merchant_capabilities, + supported_networks: applepay_metadata + .data + .payment_request_data + .supported_networks, + merchant_identifier: Some( + applepay_metadata + .data + .session_token_data + .merchant_identifier, + ), + }; - Ok(response_router_data) + let applepay_session_request = mk_applepay_session_request(state, router_data)?; + let response = services::call_connector_api(state, applepay_session_request).await; + + // logging the error if present in session call response + log_session_response_if_error(&response); + + let apple_pay_session_response = response + .ok() + .and_then(|apple_pay_res| { + apple_pay_res + .map(|res| { + let response: Result< + payment_types::NoThirdPartySdkSessionResponse, + Report<common_utils::errors::ParsingError>, + > = res.response.parse_struct("NoThirdPartySdkSessionResponse"); + + // logging the parsing failed error + if let Err(error) = response.as_ref() { + logger::error!(?error); + }; + + response.ok() + }) + .ok() + }) + .flatten(); + + let session_response = + apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk); + + create_apple_pay_session_response( + router_data, + session_response, + Some(applepay_payment_request), + connector_name.to_string(), + delayed_response, + payment_types::NextActionCall::Confirm, + ) + } +} + +fn create_apple_pay_session_response( + router_data: &types::PaymentsSessionRouterData, + session_response: Option<payment_types::ApplePaySessionResponse>, + apple_pay_payment_request: Option<payment_types::ApplePayPaymentRequest>, + connector_name: String, + delayed_response: bool, + next_action: payment_types::NextActionCall, +) -> RouterResult<types::PaymentsSessionRouterData> { + match session_response { + Some(response) => Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::ApplePay(Box::new( + payment_types::ApplepaySessionTokenResponse { + session_token_data: response, + payment_request_data: apple_pay_payment_request, + connector: connector_name, + delayed_session_token: delayed_response, + sdk_next_action: { payment_types::SdkNextAction { next_action } }, + }, + )), + }), + ..router_data.clone() + }), + None => Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::NoSessionTokenReceived, + }), + ..router_data.clone() + }), + } } fn create_gpay_session_token( @@ -278,6 +333,18 @@ fn create_gpay_session_token( Ok(response_router_data) } +fn log_session_response_if_error( + response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>, +) { + if let Err(error) = response.as_ref() { + logger::error!(?error); + }; + response + .as_ref() + .ok() + .map(|res| res.as_ref().map_err(|error| logger::error!(?error))); +} + impl types::PaymentsSessionRouterData { pub async fn decide_flow<'a, 'b>( &'b self, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index feda3e1052a..4148ab61df2 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -315,13 +315,28 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( types::PaymentsResponseData::PreProcessingResponse { pre_processing_id, connector_metadata, + .. } => { + let connector_transaction_id = match pre_processing_id.to_owned() { + types::PreprocessingResponseId::PreProcessingId(_) => None, + types::PreprocessingResponseId::ConnectorTransactionId(connector_txn_id) => { + Some(connector_txn_id) + } + }; + let preprocessing_step_id = match pre_processing_id { + types::PreprocessingResponseId::PreProcessingId(pre_processing_id) => { + Some(pre_processing_id) + } + types::PreprocessingResponseId::ConnectorTransactionId(_) => None, + }; let payment_attempt_update = storage::PaymentAttemptUpdate::PreprocessingUpdate { status: router_data.status, payment_method_id: Some(router_data.payment_method_id), connector_metadata, - preprocessing_step_id: Some(pre_processing_id), + preprocessing_step_id, + connector_transaction_id, }; + (Some(payment_attempt_update), None) } types::PaymentsResponseData::TransactionResponse { diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 5fe496aa281..829951671bc 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -377,15 +377,15 @@ where for (connector, payment_method_type, business_sub_label) in connector_and_supporting_payment_method_type { - if let Ok(connector_data) = api::ConnectorData::get_connector_by_name( - connectors, - &connector, - api::GetToken::from(payment_method_type), - ) - .map_err(|err| { - logger::error!(session_token_error=?err); - err - }) { + let connector_type = + get_connector_type_for_session_token(payment_method_type, request, &connector); + if let Ok(connector_data) = + api::ConnectorData::get_connector_by_name(connectors, &connector, connector_type) + .map_err(|err| { + logger::error!(session_token_error=?err); + err + }) + { session_connector_data.push(api::SessionConnectorData { payment_method_type, connector: connector_data, @@ -412,11 +412,11 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken { pub fn get_connector_type_for_session_token( payment_method_type: api_models::enums::PaymentMethodType, - _request: &api::PaymentsSessionRequest, - connector: String, + request: &api::PaymentsSessionRequest, + connector: &str, ) -> api::GetToken { if payment_method_type == api_models::enums::PaymentMethodType::ApplePay { - if connector == *"bluesnap" { + if is_apple_pay_get_token_connector(connector, request) { api::GetToken::Connector } else { api::GetToken::ApplePayMetadata @@ -425,3 +425,11 @@ pub fn get_connector_type_for_session_token( api::GetToken::from(payment_method_type) } } + +pub fn is_apple_pay_get_token_connector( + connector: &str, + _request: &api::PaymentsSessionRequest, +) -> bool { + // Add connectors here, which all are required to hit connector for session call + matches!(connector, "bluesnap") +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index f65b5d8ba0f..320896b34d1 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -169,6 +169,7 @@ where payment_data.connector_response.authentication_data, &operation, payment_data.ephemeral_key, + payment_data.sessions_token, ) } } @@ -260,6 +261,7 @@ pub fn payments_to_payments_response<R, Op>( redirection_data: Option<serde_json::Value>, operation: &Op, ephemeral_key_option: Option<ephemeral_key::EphemeralKey>, + session_tokens: Vec<api::SessionToken>, ) -> RouterResponse<api::PaymentsResponse> where Op: Debug, @@ -337,6 +339,15 @@ where })); }; + // next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response) + if third_party_sdk_session_next_action(&payment_attempt, operation) { + next_action_response = Some( + api_models::payments::NextActionData::ThirdPartySdkSessionToken { + session_token: session_tokens.get(0).cloned(), + }, + ) + } + let mut response: api::PaymentsResponse = Default::default(); let routed_through = payment_attempt.connector.clone(); @@ -514,6 +525,34 @@ where output } +pub fn third_party_sdk_session_next_action<Op>( + payment_attempt: &storage::PaymentAttempt, + operation: &Op, +) -> bool +where + Op: Debug, +{ + // If the operation is confirm, we will send session token response in next action + if format!("{operation:?}").eq("PaymentConfirm") { + payment_attempt + .connector + .as_ref() + .map(|connector| matches!(connector.as_str(), "trustpay")) + .and_then(|is_connector_supports_third_party_sdk| { + if is_connector_supports_third_party_sdk { + payment_attempt + .payment_method + .map(|pm| matches!(pm, storage_models::enums::PaymentMethod::Wallet)) + } else { + Some(false) + } + }) + .unwrap_or(false) + } else { + false + } +} + impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse { fn foreign_from(item: (storage::PaymentIntent, storage::PaymentAttempt)) -> Self { let pi = item.0; @@ -900,6 +939,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce Ok(Self { email: payment_data.email, currency: Some(payment_data.currency), + amount: Some(payment_data.amount.into()), }) } } diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 9e870c5cd25..f43170cb8db 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -201,6 +201,9 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsSessionResponse, api_models::payments::SessionToken, api_models::payments::ApplePaySessionResponse, + api_models::payments::ThirdPartySdkSessionResponse, + api_models::payments::NoThirdPartySdkSessionResponse, + api_models::payments::SecretInfoToInitiateSdk, api_models::payments::ApplePayPaymentRequest, api_models::payments::AmountInfo, api_models::payments::GooglePayWalletData, @@ -216,6 +219,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::KlarnaSessionTokenResponse, api_models::payments::PaypalSessionTokenResponse, api_models::payments::ApplepaySessionTokenResponse, + api_models::payments::SdkNextAction, + api_models::payments::NextActionCall, api_models::payments::GpayTokenizationData, api_models::payments::GooglePayPaymentMethodInfo, api_models::payments::ApplePayWalletData, @@ -231,6 +236,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::ReceiverDetails, api_models::payments::AchTransfer, api_models::payments::ApplePayRedirectData, + api_models::payments::ApplePayThirdPartySdkData, api_models::payments::GooglePayRedirectData, api_models::payments::SepaBankTransferInstructions, api_models::payments::BacsBankTransferInstructions, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2020114f4ef..a694e878aa6 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -270,6 +270,7 @@ pub struct PaymentMethodTokenizationData { pub struct PaymentsPreProcessingData { pub email: Option<Email>, pub currency: Option<storage_enums::Currency>, + pub amount: Option<i64>, } #[derive(Debug, Clone)] @@ -425,11 +426,18 @@ pub enum PaymentsResponseData { related_transaction_id: Option<String>, }, PreProcessingResponse { - pre_processing_id: String, + pre_processing_id: PreprocessingResponseId, connector_metadata: Option<serde_json::Value>, + session_token: Option<api::SessionToken>, }, } +#[derive(Debug, Clone)] +pub enum PreprocessingResponseId { + PreProcessingId(String), + ConnectorTransactionId(String), +} + #[derive(Debug, Clone, Default)] pub enum ResponseId { ConnectorTransactionId(String), diff --git a/crates/storage_models/src/payment_attempt.rs b/crates/storage_models/src/payment_attempt.rs index f93124d3cce..96712d18c5b 100644 --- a/crates/storage_models/src/payment_attempt.rs +++ b/crates/storage_models/src/payment_attempt.rs @@ -178,6 +178,7 @@ pub enum PaymentAttemptUpdate { payment_method_id: Option<Option<String>>, connector_metadata: Option<serde_json::Value>, preprocessing_step_id: Option<String>, + connector_transaction_id: Option<String>, }, } @@ -394,12 +395,14 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { payment_method_id, connector_metadata, preprocessing_step_id, + connector_transaction_id, } => Self { status: Some(status), payment_method_id, modified_at: Some(common_utils::date_time::now()), connector_metadata, preprocessing_step_id, + connector_transaction_id, ..Default::default() }, }
feat
applepay through trustpay (#1422)
026d8fe3289115510fec26976716ed55787fc15e
2024-06-24 05:46:20
github-actions
chore(version): 2024.06.24.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 857f13fa9de..0b8cffb61dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.06.24.0 + +### Features + +- **payment_methods:** Implement Process tracker workflow for Payment method Status update ([#4668](https://github.com/juspay/hyperswitch/pull/4668)) ([`5cde7ee`](https://github.com/juspay/hyperswitch/commit/5cde7ee0344d4068a232c96f60b53629b8c17f7f)) +- **users:** Setup user authentication methods schema and apis ([#4999](https://github.com/juspay/hyperswitch/pull/4999)) ([`2005d3d`](https://github.com/juspay/hyperswitch/commit/2005d3df9fc2e559ea65c57892ab940e38b9af50)) + +### Bug Fixes + +- **router:** Avoid considering pre-routing results during `perform_session_token_routing` ([#5076](https://github.com/juspay/hyperswitch/pull/5076)) ([`a71fe03`](https://github.com/juspay/hyperswitch/commit/a71fe033e7de75171d140506ff4d51a362c185f4)) + +### Refactors + +- **redis:** Spawn one subscriber thread for handling all the published messages to different channel ([#5064](https://github.com/juspay/hyperswitch/pull/5064)) ([`6a07e10`](https://github.com/juspay/hyperswitch/commit/6a07e10af379006c4643bb8f0a9cb2f46813ff8a)) + +**Full Changelog:** [`2024.06.20.1...2024.06.24.0`](https://github.com/juspay/hyperswitch/compare/2024.06.20.1...2024.06.24.0) + +- - - + ## 2024.06.20.1 ### Features
chore
2024.06.24.0
13fa7d5c56d53ca1dc9ec9425892f561221e08ec
2024-06-07 15:23:00
DEEPANSHU BANSAL
feat(connector): [BOA] Handle refund status 201 (#4908)
false
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 55bc5290f71..dacacb5d27e 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -2649,9 +2649,12 @@ impl<F> TryFrom<&BankOfAmericaRouterData<&types::RefundsRouterData<F>>> } } -impl From<BankofamericaRefundStatus> for enums::RefundStatus { - fn from(item: BankofamericaRefundStatus) -> Self { - match item { +impl From<BankOfAmericaRefundResponse> for enums::RefundStatus { + fn from(item: BankOfAmericaRefundResponse) -> Self { + let error_reason = item + .error_information + .and_then(|error_info| error_info.reason); + match item.status { BankofamericaRefundStatus::Succeeded | BankofamericaRefundStatus::Transmitted => { Self::Success } @@ -2659,11 +2662,18 @@ impl From<BankofamericaRefundStatus> for enums::RefundStatus { | BankofamericaRefundStatus::Failed | BankofamericaRefundStatus::Voided => Self::Failure, BankofamericaRefundStatus::Pending => Self::Pending, + BankofamericaRefundStatus::TwoZeroOne => { + if error_reason == Some("PROCESSOR_DECLINED".to_string()) { + Self::Failure + } else { + Self::Pending + } + } } } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaRefundResponse { id: String, @@ -2678,19 +2688,19 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, BankOfAmericaRefundR fn try_from( item: types::RefundsResponseRouterData<api::Execute, BankOfAmericaRefundResponse>, ) -> Result<Self, Self::Error> { - let refund_status = enums::RefundStatus::from(item.response.status.clone()); + let refund_status = enums::RefundStatus::from(item.response.clone()); let response = if utils::is_refund_failure(refund_status) { Err(types::ErrorResponse::foreign_from(( &item.response.error_information, &None, None, item.http_code, - item.response.id.clone(), + item.response.id, ))) } else { Ok(types::RefundsResponseData { connector_refund_id: item.response.id, - refund_status: enums::RefundStatus::from(item.response.status), + refund_status, }) }; @@ -2710,6 +2720,8 @@ pub enum BankofamericaRefundStatus { Pending, Voided, Cancelled, + #[serde(rename = "201")] + TwoZeroOne, } #[derive(Debug, Deserialize, Serialize)] @@ -2739,8 +2751,26 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResp .and_then(|application_information| application_information.status) { Some(status) => { - let refund_status: common_enums::RefundStatus = - enums::RefundStatus::from(status.clone()); + let error_reason = item + .response + .error_information + .clone() + .and_then(|error_info| error_info.reason); + let refund_status = match status { + BankofamericaRefundStatus::Succeeded + | BankofamericaRefundStatus::Transmitted => enums::RefundStatus::Success, + BankofamericaRefundStatus::Cancelled + | BankofamericaRefundStatus::Failed + | BankofamericaRefundStatus::Voided => enums::RefundStatus::Failure, + BankofamericaRefundStatus::Pending => enums::RefundStatus::Pending, + BankofamericaRefundStatus::TwoZeroOne => { + if error_reason == Some("PROCESSOR_DECLINED".to_string()) { + enums::RefundStatus::Failure + } else { + enums::RefundStatus::Pending + } + } + }; if utils::is_refund_failure(refund_status) { if status == BankofamericaRefundStatus::Voided { Err(types::ErrorResponse::foreign_from((
feat
[BOA] Handle refund status 201 (#4908)
e3a9fb16c518d09313d00a23ece70a26d4728f63
2024-09-03 11:37:06
Hrithikesh
feat: add profile_id authentication for business profile update and list (#5673)
false
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 11ba1a0467e..a69a46000fb 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3717,6 +3717,7 @@ pub async fn create_business_profile( pub async fn list_business_profile( state: SessionState, merchant_id: id_type::MerchantId, + profile_id_list: Option<Vec<id_type::ProfileId>>, ) -> RouterResponse<Vec<api_models::admin::BusinessProfileResponse>> { let db = state.store.as_ref(); let key_store = db @@ -3732,6 +3733,7 @@ pub async fn list_business_profile( .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? .clone(); + let profiles = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, profiles); let mut business_profiles = Vec::new(); for profile in profiles { let business_profile = diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index be9c528e87f..2fcf8a24773 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1334,7 +1334,7 @@ pub fn get_incremental_authorization_allowed_value( } } -pub(super) trait GetProfileId { +pub(crate) trait GetProfileId { fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId>; } @@ -1381,6 +1381,12 @@ impl<T, F> GetProfileId for (storage::Payouts, T, F) { } } +impl GetProfileId for domain::BusinessProfile { + fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> { + Some(self.get_id()) + } +} + /// Filter Objects based on profile ids pub(super) fn filter_objects_based_on_profile_id_list<T: GetProfileId>( profile_id_list_auth_layer: Option<Vec<common_utils::id_type::ProfileId>>, @@ -1406,7 +1412,7 @@ pub(super) fn filter_objects_based_on_profile_id_list<T: GetProfileId>( } } -pub(super) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::Debug>( +pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::Debug>( profile_id_auth_layer: Option<common_utils::id_type::ProfileId>, object: &T, ) -> RouterResult<()> { diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 62e0b6fb31e..fc838645c8b 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -119,7 +119,9 @@ pub fn mk_app( { // This is a more specific route as compared to `MerchantConnectorAccount` // so it is registered before `MerchantConnectorAccount`. - server_app = server_app.service(routes::BusinessProfile::server(state.clone())) + server_app = server_app + .service(routes::BusinessProfileNew::server(state.clone())) + .service(routes::BusinessProfile::server(state.clone())) } server_app = server_app .service(routes::Payments::server(state.clone())) diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 561f96ab71a..cb8edb24052 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -59,10 +59,10 @@ pub use self::app::Forex; #[cfg(all(feature = "olap", feature = "recon"))] pub use self::app::Recon; pub use self::app::{ - ApiKeys, AppState, ApplePayCertificatesMigration, BusinessProfile, Cache, Cards, Configs, - ConnectorOnboarding, Customers, Disputes, EphemeralKey, Files, Gsm, Health, Mandates, - MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, - Refunds, SessionState, User, Webhooks, + ApiKeys, AppState, ApplePayCertificatesMigration, BusinessProfile, BusinessProfileNew, Cache, + Cards, Configs, ConnectorOnboarding, Customers, Disputes, EphemeralKey, Files, Gsm, Health, + Mandates, MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, + Poll, Refunds, SessionState, User, Webhooks, }; #[cfg(feature = "olap")] pub use self::app::{Blocklist, Organization, Routing, Verify, WebhookEvents}; diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 8e679040c91..6c7f30de1c5 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -892,8 +892,9 @@ pub async fn business_profile_update( }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), - &auth::JWTAuthMerchantFromRoute { + &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), + profile_id: profile_id.clone(), required_permission: Permission::MerchantAccountWrite, }, req.headers(), @@ -971,9 +972,43 @@ pub async fn business_profiles_list( state, &req, merchant_id.clone(), - |state, _, merchant_id, _| list_business_profile(state, merchant_id), + |state, _auth, merchant_id, _| list_business_profile(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromRoute { + merchant_id, + required_permission: Permission::MerchantAccountRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileList))] +pub async fn business_profiles_list_at_profile_level( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<common_utils::id_type::MerchantId>, +) -> HttpResponse { + let flow = Flow::BusinessProfileList; + let merchant_id = path.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + merchant_id.clone(), + |state, auth, merchant_id, _| { + list_business_profile( + state, + merchant_id, + auth.profile_id.map(|profile_id| vec![profile_id]), + ) + }, + auth::auth_type( + &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantAccountRead, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4b1f1bd8b14..c78caa9e781 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1639,6 +1639,19 @@ impl BusinessProfile { } } +pub struct BusinessProfileNew; + +#[cfg(feature = "olap")] +impl BusinessProfileNew { + pub fn server(state: AppState) -> Scope { + web::scope("/account/{account_id}/profile") + .app_data(web::Data::new(state)) + .service( + web::resource("").route(web::get().to(business_profiles_list_at_profile_level)), + ) + } +} + pub struct Gsm; #[cfg(feature = "olap")] diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 6c0a8d00b3a..a84f3a5a0e3 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -88,6 +88,11 @@ pub enum AuthenticationType { merchant_id: id_type::MerchantId, user_id: Option<String>, }, + MerchantJwtWithProfileId { + merchant_id: id_type::MerchantId, + profile_id: Option<id_type::ProfileId>, + user_id: String, + }, UserJwt { user_id: String, }, @@ -137,6 +142,7 @@ impl AuthenticationType { merchant_id, user_id: _, } + | Self::MerchantJwtWithProfileId { merchant_id, .. } | Self::WebhookAuth { merchant_id } => Some(merchant_id), Self::AdminApiKey | Self::UserJwt { .. } @@ -1324,6 +1330,80 @@ where } } +pub struct JWTAuthMerchantAndProfileFromRoute { + pub merchant_id: id_type::MerchantId, + pub profile_id: id_type::ProfileId, + pub required_permission: Permission, +} + +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantAndProfileFromRoute +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if payload.check_in_blacklist(state).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + if payload.merchant_id != self.merchant_id { + return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); + } + + if payload + .profile_id + .as_ref() + .is_some_and(|profile_id| *profile_id != self.profile_id) + { + return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); + } + + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.required_permission, &permissions)?; + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) + .attach_printable("Failed to fetch merchant account for the merchant id")?; + + let auth = AuthenticationData { + merchant_account: merchant, + key_store, + profile_id: payload.profile_id, + }; + Ok(( + auth.clone(), + AuthenticationType::MerchantJwtWithProfileId { + merchant_id: auth.merchant_account.get_id().clone(), + profile_id: auth.profile_id.clone(), + user_id: payload.user_id, + }, + )) + } +} + pub async fn parse_jwt_payload<A, T>(headers: &HeaderMap, state: &A) -> RouterResult<T> where T: serde::de::DeserializeOwned,
feat
add profile_id authentication for business profile update and list (#5673)
7b337ac39d72f90dd0ebe58133218896ff279313
2024-03-28 18:12:30
Chethan Rao
feat(mandates): allow off-session payments using `payment_method_id` (#4132)
false
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index bd5c5b5a1a0..4adda0d9af4 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -113,3 +113,10 @@ pub struct MandateListConstraints { #[serde(rename = "created_time.gte")] pub created_time_gte: Option<PrimitiveDateTime>, } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +#[serde(tag = "type", content = "data", rename_all = "snake_case")] +pub enum RecurringDetails { + MandateId(String), + PaymentMethodId(String), +} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index ce2b1c3d68a..72592ec3cad 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -19,10 +19,8 @@ use url::Url; use utoipa::ToSchema; use crate::{ - admin, disputes, - enums::{self as api_enums}, - ephemeral_key::EphemeralKeyCreateResponse, - refunds, + admin, disputes, enums as api_enums, ephemeral_key::EphemeralKeyCreateResponse, + mandates::RecurringDetails, refunds, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -459,6 +457,9 @@ pub struct PaymentsRequest { /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, + + /// Details required for recurring payment + pub recurring_details: Option<RecurringDetails>, } impl PaymentsRequest { @@ -3360,7 +3361,7 @@ pub struct PaymentsRedirectionResponse { } pub struct MandateValidationFields { - pub mandate_id: Option<String>, + pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<String>, pub mandate_data: Option<MandateData>, @@ -3370,8 +3371,14 @@ pub struct MandateValidationFields { impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { + let recurring_details = req + .mandate_id + .clone() + .map(RecurringDetails::MandateId) + .or(req.recurring_details.clone()); + Self { - mandate_id: req.mandate_id.clone(), + recurring_details, confirm: req.confirm, customer_id: req .customer @@ -3389,7 +3396,7 @@ impl From<&PaymentsRequest> for MandateValidationFields { impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { - mandate_id: None, + recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index c8e89f2ee70..4a61a20d08d 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -410,6 +410,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse, api_models::mandates::MandateCardDetails, + api_models::mandates::RecurringDetails, api_models::ephemeral_key::EphemeralKeyCreateResponse, api_models::payments::CustomerDetails, api_models::payments::GiftCardData, diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs index 150130ed9e5..704b7ae99f5 100644 --- a/crates/router/src/core/mandate/helpers.rs +++ b/crates/router/src/core/mandate/helpers.rs @@ -1,8 +1,14 @@ +use common_enums::enums; use common_utils::errors::CustomResult; +use data_models::mandates::MandateData; use diesel_models::Mandate; use error_stack::ResultExt; -use crate::{core::errors, routes::AppState, types::domain}; +use crate::{ + core::{errors, payments}, + routes::AppState, + types::domain, +}; pub async fn get_profile_id_for_mandate( state: &AppState, @@ -33,3 +39,14 @@ pub async fn get_profile_id_for_mandate( }?; Ok(profile_id) } + +#[derive(Clone)] +pub struct MandateGenericData { + pub token: Option<String>, + pub payment_method: Option<enums::PaymentMethod>, + pub payment_method_type: Option<enums::PaymentMethodType>, + pub mandate_data: Option<MandateData>, + pub recurring_mandate_payment_data: Option<payments::RecurringMandatePaymentData>, + pub mandate_connector: Option<payments::MandateConnectorDetails>, + pub payment_method_info: Option<diesel_models::PaymentMethod>, +} diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0a3a93923b7..e11a77496af 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -15,6 +15,7 @@ use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoI use api_models::{ self, enums, + mandates::RecurringDetails, payments::{self as payments_api, HeaderPayload}, }; use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge}; @@ -2263,6 +2264,7 @@ where pub authorizations: Vec<diesel_models::authorization::Authorization>, pub authentication: Option<storage::Authentication>, pub frm_metadata: Option<serde_json::Value>, + pub recurring_details: Option<RecurringDetails>, } #[derive(Debug, Default, Clone)] @@ -2907,7 +2909,7 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - return decide_connector_for_token_based_mit_flow( + return decide_multiplex_connector_for_normal_or_recurring_payment( payment_data, routing_data, connector_data, @@ -2961,7 +2963,7 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; - return decide_connector_for_token_based_mit_flow( + return decide_multiplex_connector_for_normal_or_recurring_payment( payment_data, routing_data, connector_data, @@ -2980,24 +2982,26 @@ where .await } -pub fn decide_connector_for_token_based_mit_flow<F: Clone>( +pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>( payment_data: &mut PaymentData<F>, routing_data: &mut storage::RoutingData, connectors: Vec<api::ConnectorData>, ) -> RouterResult<ConnectorCallType> { - if let Some((storage_enums::FutureUsage::OffSession, _)) = payment_data - .payment_intent - .setup_future_usage - .zip(payment_data.token_data.as_ref()) - { - logger::debug!("performing routing for token-based MIT flow"); + match ( + payment_data.payment_intent.setup_future_usage, + payment_data.token_data.as_ref(), + payment_data.recurring_details.as_ref(), + ) { + (Some(storage_enums::FutureUsage::OffSession), Some(_), None) + | (None, None, Some(RecurringDetails::PaymentMethodId(_))) => { + logger::debug!("performing routing for token-based MIT flow"); - let payment_method_info = payment_data - .payment_method_info - .as_ref() - .get_required_value("payment_method_info")?; + let payment_method_info = payment_data + .payment_method_info + .as_ref() + .get_required_value("payment_method_info")?; - let connector_mandate_details = payment_method_info + let connector_mandate_details = payment_method_info .connector_mandate_details .clone() .map(|details| { @@ -3010,67 +3014,69 @@ pub fn decide_connector_for_token_based_mit_flow<F: Clone>( .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?; - let mut connector_choice = None; - for connector_data in connectors { - if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { - if let Some(mandate_reference_record) = - connector_mandate_details.get(merchant_connector_id) - { - connector_choice = Some((connector_data, mandate_reference_record.clone())); - break; + let mut connector_choice = None; + for connector_data in connectors { + if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() { + if let Some(mandate_reference_record) = + connector_mandate_details.get(merchant_connector_id) + { + connector_choice = Some((connector_data, mandate_reference_record.clone())); + break; + } } } - } - let (chosen_connector_data, mandate_reference_record) = connector_choice - .get_required_value("connector_choice") - .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) - .attach_printable("no eligible connector found for token-based MIT payment")?; + let (chosen_connector_data, mandate_reference_record) = connector_choice + .get_required_value("connector_choice") + .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("no eligible connector found for token-based MIT payment")?; - routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); - #[cfg(feature = "connector_choice_mca_id")] - { - routing_data.merchant_connector_id = - chosen_connector_data.merchant_connector_id.clone(); - } + routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); + #[cfg(feature = "connector_choice_mca_id")] + { + routing_data.merchant_connector_id = + chosen_connector_data.merchant_connector_id.clone(); + } - payment_data.mandate_id = Some(payments_api::MandateIds { - mandate_id: None, - mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId( - payments_api::ConnectorMandateReferenceId { - connector_mandate_id: Some( - mandate_reference_record.connector_mandate_id.clone(), - ), - payment_method_id: Some(payment_method_info.payment_method_id.clone()), - update_history: None, - }, - )), - }); - - payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData { - payment_method_type: mandate_reference_record.payment_method_type, - original_payment_authorized_amount: mandate_reference_record - .original_payment_authorized_amount, - original_payment_authorized_currency: mandate_reference_record - .original_payment_authorized_currency, - }); - - Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data)) - } else { - let first_choice = connectors - .first() - .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) - .into_report() - .attach_printable("no eligible connector found for payment")? - .clone(); - - routing_data.routed_through = Some(first_choice.connector_name.to_string()); - #[cfg(feature = "connector_choice_mca_id")] - { - routing_data.merchant_connector_id = first_choice.merchant_connector_id; + payment_data.mandate_id = Some(payments_api::MandateIds { + mandate_id: None, + mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId( + payments_api::ConnectorMandateReferenceId { + connector_mandate_id: Some( + mandate_reference_record.connector_mandate_id.clone(), + ), + payment_method_id: Some(payment_method_info.payment_method_id.clone()), + update_history: None, + }, + )), + }); + + payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData { + payment_method_type: mandate_reference_record.payment_method_type, + original_payment_authorized_amount: mandate_reference_record + .original_payment_authorized_amount, + original_payment_authorized_currency: mandate_reference_record + .original_payment_authorized_currency, + }); + + Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data)) } + _ => { + let first_choice = connectors + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .into_report() + .attach_printable("no eligible connector found for payment")? + .clone(); + + routing_data.routed_through = Some(first_choice.connector_name.to_string()); + #[cfg(feature = "connector_choice_mca_id")] + { + routing_data.merchant_connector_id = first_choice.merchant_connector_id; + } - Ok(api::ConnectorCallType::Retryable(connectors)) + Ok(api::ConnectorCallType::Retryable(connectors)) + } } } @@ -3291,7 +3297,11 @@ where match transaction_data { TransactionData::Payment(payment_data) => { - decide_connector_for_token_based_mit_flow(payment_data, routing_data, connector_data) + decide_multiplex_connector_for_normal_or_recurring_payment( + payment_data, + routing_data, + connector_data, + ) } #[cfg(feature = "payouts")] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7eab4c0d26a..e9cefbf8aed 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,6 +1,9 @@ use std::borrow::Cow; -use api_models::payments::{CardToken, GetPaymentMethodType, RequestSurchargeDetails}; +use api_models::{ + mandates::RecurringDetails, + payments::{CardToken, GetPaymentMethodType, RequestSurchargeDetails}, +}; use base64::Engine; use common_utils::{ ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, @@ -34,6 +37,7 @@ use crate::{ consts::{self, BASE64_ENGINE}, core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + mandate::helpers::MandateGenericData, payment_methods::{cards, vault, PaymentMethodRetrieve}, payments, pm_auth::retrieve_payment_method_from_auth_service, @@ -414,59 +418,117 @@ pub async fn get_token_pm_type_mandate_details( mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, -) -> RouterResult<( - Option<String>, - Option<storage_enums::PaymentMethod>, - Option<storage_enums::PaymentMethodType>, - Option<MandateData>, - Option<payments::RecurringMandatePaymentData>, - Option<payments::MandateConnectorDetails>, -)> { +) -> RouterResult<MandateGenericData> { let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from); - match mandate_type { - Some(api::MandateTransactionType::NewMandateTransaction) => { - let setup_mandate = mandate_data.clone().get_required_value("mandate_data")?; - Ok(( - request.payment_token.to_owned(), - request.payment_method, - request.payment_method_type, - Some(setup_mandate), - None, - None, - )) - } + let ( + payment_token, + payment_method, + payment_method_type, + mandate_data, + recurring_payment_data, + mandate_connector_details, + payment_method_info, + ) = match mandate_type { + Some(api::MandateTransactionType::NewMandateTransaction) => ( + request.payment_token.to_owned(), + request.payment_method, + request.payment_method_type, + Some(mandate_data.clone().get_required_value("mandate_data")?), + None, + None, + None, + ), Some(api::MandateTransactionType::RecurringMandateTransaction) => { - let ( - token_, - payment_method_, - recurring_mandate_payment_data, - payment_method_type_, - mandate_connector, - ) = get_token_for_recurring_mandate( - state, - request, - merchant_account, - merchant_key_store, - ) - .await?; - Ok(( - token_, - payment_method_, - payment_method_type_.or(request.payment_method_type), - None, - recurring_mandate_payment_data, - mandate_connector, - )) + match &request.recurring_details { + Some(recurring_details) => match recurring_details { + RecurringDetails::MandateId(mandate_id) => { + let mandate_generic_data = get_token_for_recurring_mandate( + state, + request, + merchant_account, + merchant_key_store, + mandate_id.to_owned(), + ) + .await?; + + ( + mandate_generic_data.token, + mandate_generic_data.payment_method, + mandate_generic_data + .payment_method_type + .or(request.payment_method_type), + None, + mandate_generic_data.recurring_mandate_payment_data, + mandate_generic_data.mandate_connector, + None, + ) + } + RecurringDetails::PaymentMethodId(payment_method_id) => { + let payment_method_info = state + .store + .find_payment_method(payment_method_id) + .await + .to_not_found_response( + errors::ApiErrorResponse::PaymentMethodNotFound, + )?; + + ( + None, + Some(payment_method_info.payment_method), + payment_method_info.payment_method_type, + None, + None, + None, + Some(payment_method_info), + ) + } + }, + None => { + let mandate_id = request + .mandate_id + .clone() + .get_required_value("mandate_id")?; + let mandate_generic_data = get_token_for_recurring_mandate( + state, + request, + merchant_account, + merchant_key_store, + mandate_id, + ) + .await?; + ( + mandate_generic_data.token, + mandate_generic_data.payment_method, + mandate_generic_data + .payment_method_type + .or(request.payment_method_type), + None, + mandate_generic_data.recurring_mandate_payment_data, + mandate_generic_data.mandate_connector, + None, + ) + } + } } - None => Ok(( + None => ( request.payment_token.to_owned(), request.payment_method, request.payment_method_type, mandate_data, None, None, - )), - } + None, + ), + }; + Ok(MandateGenericData { + token: payment_token, + payment_method, + payment_method_type, + mandate_data, + recurring_mandate_payment_data: recurring_payment_data, + mandate_connector: mandate_connector_details, + payment_method_info, + }) } pub async fn get_token_for_recurring_mandate( @@ -474,15 +536,9 @@ pub async fn get_token_for_recurring_mandate( req: &api::PaymentsRequest, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, -) -> RouterResult<( - Option<String>, - Option<storage_enums::PaymentMethod>, - Option<payments::RecurringMandatePaymentData>, - Option<storage_enums::PaymentMethodType>, - Option<payments::MandateConnectorDetails>, -)> { + mandate_id: String, +) -> RouterResult<MandateGenericData> { let db = &*state.store; - let mandate_id = req.mandate_id.clone().get_required_value("mandate_id")?; let mandate = db .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, mandate_id.as_str()) @@ -566,29 +622,33 @@ pub async fn get_token_for_recurring_mandate( } }; - Ok(( - Some(token), - Some(payment_method.payment_method), - Some(payments::RecurringMandatePaymentData { + Ok(MandateGenericData { + token: Some(token), + payment_method: Some(payment_method.payment_method), + recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData { payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, }), - payment_method.payment_method_type, - Some(mandate_connector_details), - )) + payment_method_type: payment_method.payment_method_type, + mandate_connector: Some(mandate_connector_details), + mandate_data: None, + payment_method_info: None, + }) } else { - Ok(( - None, - Some(payment_method.payment_method), - Some(payments::RecurringMandatePaymentData { + Ok(MandateGenericData { + token: None, + payment_method: Some(payment_method.payment_method), + recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData { payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, }), - payment_method.payment_method_type, - Some(mandate_connector_details), - )) + payment_method_type: payment_method.payment_method_type, + mandate_connector: Some(mandate_connector_details), + mandate_data: None, + payment_method_info: None, + }) } } @@ -792,7 +852,7 @@ pub fn validate_mandate( let req: api::MandateValidationFields = req.into(); match req.validate_and_get_mandate_type().change_context( errors::ApiErrorResponse::MandateValidationFailed { - reason: "Expected one out of mandate_id and mandate_data but got both".into(), + reason: "Expected one out of recurring_details and mandate_data but got both".into(), }, )? { Some(api::MandateTransactionType::NewMandateTransaction) => { @@ -809,6 +869,23 @@ pub fn validate_mandate( } } +pub fn validate_recurring_details_and_token( + recurring_details: &Option<RecurringDetails>, + payment_token: &Option<String>, +) -> CustomResult<(), errors::ApiErrorResponse> { + utils::when( + recurring_details.is_some() && payment_token.is_some(), + || { + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: "Expected one out of recurring_details and payment_token but got both" + .into() + })) + }, + )?; + + Ok(()) +} + fn validate_new_mandate_request( req: api::MandateValidationFields, is_confirm_operation: bool, @@ -940,7 +1017,8 @@ pub fn create_complete_authorize_url( } fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> { - req.mandate_id.check_value_present("mandate_id")?; + req.recurring_details + .check_value_present("recurring_details")?; req.customer_id.check_value_present("customer_id")?; @@ -1950,7 +2028,8 @@ pub(crate) fn validate_payment_method_fields_present( utils::when( req.payment_method.is_some() && req.payment_method_data.is_none() - && req.payment_token.is_none(), + && req.payment_token.is_none() + && req.recurring_details.is_none(), || { Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "payment_method_data", diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 65b856364cc..a2132bed8c1 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -178,6 +178,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], frm_metadata: None, authentication: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index b25c0e2b909..ab5feb5d9b5 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -187,6 +187,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], frm_metadata: None, authentication: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 47d339f15be..4445589f42f 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -231,6 +231,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], frm_metadata: None, authentication: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 8a773904ea3..b788ebc95f7 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + mandate::helpers::MandateGenericData, payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, @@ -71,17 +72,18 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> "confirm", )?; - let ( + let MandateGenericData { token, payment_method, payment_method_type, - setup_mandate, + mandate_data, recurring_mandate_payment_data, mandate_connector, - ) = helpers::get_token_pm_type_mandate_details( + payment_method_info, + } = helpers::get_token_pm_type_mandate_details( state, request, - mandate_type.clone(), + mandate_type.to_owned(), merchant_account, key_store, ) @@ -225,7 +227,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); // The operation merges mandate data from both request and payment_attempt - let setup_mandate = setup_mandate.map(Into::into); + let setup_mandate = mandate_data.map(Into::into); let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); @@ -270,7 +272,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .as_ref() .map(|pmd| pmd.payment_method_data.clone()), - payment_method_info: None, + payment_method_info, force_sync: None, refunds: vec![], disputes: vec![], @@ -291,6 +293,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], authentication: None, frm_metadata: None, + recurring_details: request.recurring_details.clone(), }; let customer_details = Some(CustomerDetails { @@ -455,6 +458,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; + helpers::validate_recurring_details_and_token( + &request.recurring_details, + &request.payment_token, + )?; + Ok(( Box::new(self), operations::ValidateResult { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index cb4226bcfbe..a0caf5e1c94 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -15,6 +15,7 @@ use crate::{ authentication, blocklist::utils as blocklist_utils, errors::{self, CustomResult, RouterResult, StorageErrorExt}, + mandate::helpers::MandateGenericData, payment_methods::PaymentMethodRetrieve, payments::{ self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress, @@ -351,14 +352,15 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .setup_future_usage .or(payment_intent.setup_future_usage); - let ( + let MandateGenericData { token, payment_method, payment_method_type, - mut setup_mandate, + mandate_data, recurring_mandate_payment_data, mandate_connector, - ) = mandate_details; + payment_method_info, + } = mandate_details; let browser_info = request .browser_info @@ -406,7 +408,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> (Some(token_data), payment_method_info) } else { - (None, None) + (None, payment_method_info) }; payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); @@ -478,7 +480,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .or(payment_attempt.business_sub_label); // The operation merges mandate data from both request and payment_attempt - setup_mandate = setup_mandate.map(|mut sm| { + let setup_mandate = mandate_data.map(|mut sm| { sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type); sm.update_mandate_id = payment_attempt .mandate_data @@ -619,6 +621,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], frm_metadata: request.frm_metadata.clone(), authentication, + recurring_details: request.recurring_details.clone(), }; let get_trackers_response = operations::GetTrackerResponse { @@ -1199,6 +1202,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; + helpers::validate_recurring_details_and_token( + &request.recurring_details, + &request.payment_token, + )?; + let payment_id = request .payment_id .clone() diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 58675bf62cd..6dce6db9d9b 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1,6 +1,6 @@ use std::marker::PhantomData; -use api_models::enums::FrmSuggestion; +use api_models::{enums::FrmSuggestion, mandates::RecurringDetails}; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; use data_models::{ @@ -19,6 +19,7 @@ use crate::{ consts, core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + mandate::helpers::MandateGenericData, payment_link, payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, @@ -104,14 +105,15 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> })? }; - let ( + let MandateGenericData { token, payment_method, payment_method_type, - setup_mandate, + mandate_data, recurring_mandate_payment_data, mandate_connector, - ) = helpers::get_token_pm_type_mandate_details( + payment_method_info, + } = helpers::get_token_pm_type_mandate_details( state, request, mandate_type, @@ -291,6 +293,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> let mandate_id = request .mandate_id .as_ref() + .or_else(|| { + request.recurring_details + .as_ref() + .and_then(|recurring_details| match recurring_details { + RecurringDetails::MandateId(id) => Some(id), + _ => None, + }) + }) .async_and_then(|mandate_id| async { let mandate = db .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id) @@ -359,7 +369,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .transpose()?; // The operation merges mandate data from both request and payment_attempt - let setup_mandate = setup_mandate.map(MandateData::from); + let setup_mandate = mandate_data.map(MandateData::from); let customer_acceptance = request.customer_acceptance.clone().map(From::from); @@ -398,7 +408,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> token_data: None, confirm: request.confirm, payment_method_data: payment_method_data_after_card_bin_call, - payment_method_info: None, + payment_method_info, refunds: vec![], disputes: vec![], attempts: None, @@ -419,6 +429,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], authentication: None, frm_metadata: request.frm_metadata.clone(), + recurring_details: request.recurring_details.clone(), }; let get_trackers_response = operations::GetTrackerResponse { @@ -676,6 +687,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; + helpers::validate_recurring_details_and_token( + &request.recurring_details, + &request.payment_token, + )?; + if request.confirm.unwrap_or(false) { helpers::validate_pm_or_token_given( &request.payment_method, diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 591ecb0a118..e1d58b032aa 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -174,6 +174,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], authentication: None, frm_metadata: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 805b5fb3630..25b419e3222 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -199,6 +199,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], authentication: None, frm_metadata: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 520336be0e1..465a2e5818d 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -186,6 +186,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], authentication: None, frm_metadata: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 101d997db21..4d616146908 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -462,6 +462,7 @@ async fn get_tracker_for_sync< authorizations, authentication, frm_metadata: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 2a0b99bc54b..684f7c4b698 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -1,6 +1,8 @@ use std::marker::PhantomData; -use api_models::{enums::FrmSuggestion, payments::RequestSurchargeDetails}; +use api_models::{ + enums::FrmSuggestion, mandates::RecurringDetails, payments::RequestSurchargeDetails, +}; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; use error_stack::{report, IntoReport, ResultExt}; @@ -11,6 +13,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, + mandate::helpers::MandateGenericData, payment_methods::PaymentMethodRetrieve, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, @@ -94,17 +97,19 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> )?; helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; - let ( + + let MandateGenericData { token, payment_method, payment_method_type, - setup_mandate, + mandate_data, recurring_mandate_payment_data, mandate_connector, - ) = helpers::get_token_pm_type_mandate_details( + payment_method_info, + } = helpers::get_token_pm_type_mandate_details( state, request, - mandate_type.clone(), + mandate_type.to_owned(), merchant_account, key_store, ) @@ -263,6 +268,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> let mandate_id = request .mandate_id .as_ref() + .or_else(|| { + request.recurring_details + .as_ref() + .and_then(|recurring_details| match recurring_details { + RecurringDetails::MandateId(id) => Some(id), + _ => None, + }) + }) .async_and_then(|mandate_id| async { let mandate = db .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id) @@ -357,7 +370,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .transpose()?; // The operation merges mandate data from both request and payment_attempt - let setup_mandate = setup_mandate.map(Into::into); + let setup_mandate = mandate_data.map(Into::into); let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); helpers::validate_mandate_data_and_future_usage( @@ -405,7 +418,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .payment_method_data .as_ref() .map(|pmd| pmd.payment_method_data.clone()), - payment_method_info: None, + payment_method_info, force_sync: None, refunds: vec![], disputes: vec![], @@ -426,6 +439,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], authentication: None, frm_metadata: request.frm_metadata.clone(), + recurring_details: request.recurring_details.clone(), }; let get_trackers_response = operations::GetTrackerResponse { @@ -737,6 +751,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen let mandate_type = helpers::validate_mandate(request, false)?; + helpers::validate_recurring_details_and_token( + &request.recurring_details, + &request.payment_token, + )?; + Ok(( Box::new(self), operations::ValidateResult { diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index ab7ab56d94f..f28b1d55c32 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -152,6 +152,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> authorizations: vec![], authentication: None, frm_metadata: None, + recurring_details: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 8e13f6c9935..d465300dd61 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -115,10 +115,11 @@ impl MandateValidationFieldsExt for MandateValidationFields { fn validate_and_get_mandate_type( &self, ) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError> { - match (&self.mandate_data, &self.mandate_id) { + match (&self.mandate_data, &self.recurring_details) { (None, None) => Ok(None), (Some(_), Some(_)) => Err(errors::ValidationError::InvalidValue { - message: "Expected one out of mandate_id and mandate_data but got both".to_string(), + message: "Expected one out of recurring_details and mandate_data but got both" + .to_string(), }) .into_report(), (_, Some(_)) => Ok(Some(MandateTransactionType::RecurringMandateTransaction)), diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 2005f9c11e0..fa9c7435632 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -13334,6 +13334,14 @@ "description": "Whether to perform external authentication (if applicable)", "example": true, "nullable": true + }, + "recurring_details": { + "allOf": [ + { + "$ref": "#/components/schemas/RecurringDetails" + } + ], + "nullable": true } } }, @@ -13726,6 +13734,14 @@ "description": "Whether to perform external authentication (if applicable)", "example": true, "nullable": true + }, + "recurring_details": { + "allOf": [ + { + "$ref": "#/components/schemas/RecurringDetails" + } + ], + "nullable": true } } }, @@ -14220,6 +14236,14 @@ "description": "Whether to perform external authentication (if applicable)", "example": true, "nullable": true + }, + "recurring_details": { + "allOf": [ + { + "$ref": "#/components/schemas/RecurringDetails" + } + ], + "nullable": true } } }, @@ -15220,6 +15244,14 @@ "description": "Whether to perform external authentication (if applicable)", "example": true, "nullable": true + }, + "recurring_details": { + "allOf": [ + { + "$ref": "#/components/schemas/RecurringDetails" + } + ], + "nullable": true } } }, @@ -16129,6 +16161,49 @@ "disabled" ] }, + "RecurringDetails": { + "oneOf": [ + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "mandate_id" + ] + }, + "data": { + "type": "string" + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "payment_method_id" + ] + }, + "data": { + "type": "string" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, "RedirectResponse": { "type": "object", "properties": {
feat
allow off-session payments using `payment_method_id` (#4132)
a9e3d74cc160d35b75278e39faac5df3aebd16bb
2024-02-15 21:35:47
Rachit Naithani
feat(users): Email JWT blacklist (#3659)
false
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 002452a8a35..54fbecc64f3 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -311,6 +311,10 @@ pub async fn change_password( .await .change_context(UserErrors::InternalServerError)?; + let _ = auth::blacklist::insert_user_in_blacklist(&state, user.get_user_id()) + .await + .map_err(|e| logger::error!(?e)); + #[cfg(not(feature = "email"))] { state @@ -372,10 +376,12 @@ pub async fn reset_password( state: AppState, request: user_api::ResetPasswordRequest, ) -> UserResponse<()> { - let token = - auth::decode_jwt::<email_types::EmailToken>(request.token.expose().as_str(), &state) - .await - .change_context(UserErrors::LinkInvalid)?; + let token = request.token.expose(); + let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state) + .await + .change_context(UserErrors::LinkInvalid)?; + + auth::blacklist::check_email_token_in_blacklist(&state, &token).await?; let password = domain::UserPassword::new(request.password)?; @@ -384,7 +390,7 @@ pub async fn reset_password( let user = state .store .update_user_by_email( - token.get_email(), + email_token.get_email(), storage_user::UserUpdate::AccountUpdate { name: None, password: Some(hash_password), @@ -395,7 +401,7 @@ pub async fn reset_password( .await .change_context(UserErrors::InternalServerError)?; - if let Some(inviter_merchant_id) = token.get_merchant_id() { + if let Some(inviter_merchant_id) = email_token.get_merchant_id() { let update_status_result = state .store .update_user_role_by_user_id_merchant_id( @@ -403,13 +409,20 @@ pub async fn reset_password( inviter_merchant_id, UserRoleUpdate::UpdateStatus { status: UserStatus::Active, - modified_by: user.user_id, + modified_by: user.user_id.clone(), }, ) .await; logger::info!(?update_status_result); } + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); + let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id) + .await + .map_err(|e| logger::error!(?e)); + Ok(ApplicationResponse::StatusOk) } @@ -454,7 +467,13 @@ pub async fn invite_user( merchant_id: user_from_token.merchant_id, role_id: request.role_id, org_id: user_from_token.org_id, - status: UserStatus::Active, + status: { + if cfg!(feature = "email") { + UserStatus::InvitationSent + } else { + UserStatus::Active + } + }, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id, created_at: now, @@ -1050,12 +1069,14 @@ pub async fn verify_email_without_invite_checks( state: AppState, req: user_api::VerifyEmailRequest, ) -> UserResponse<user_api::DashboardEntryResponse> { - let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) + let token = req.token.clone().expose(); + let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state) .await .change_context(UserErrors::LinkInvalid)?; + auth::blacklist::check_email_token_in_blacklist(&state, &token).await?; let user = state .store - .find_user_by_email(token.get_email()) + .find_user_by_email(email_token.get_email()) .await .change_context(UserErrors::InternalServerError)?; let user = state @@ -1065,6 +1086,9 @@ pub async fn verify_email_without_invite_checks( .change_context(UserErrors::InternalServerError)?; let user_from_db: domain::UserFromStorage = user.into(); let user_role = user_from_db.get_role_from_db(state.clone()).await?; + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( @@ -1077,13 +1101,16 @@ pub async fn verify_email( state: AppState, req: user_api::VerifyEmailRequest, ) -> UserResponse<user_api::SignInResponse> { - let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) + let token = req.token.clone().expose(); + let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state) .await .change_context(UserErrors::LinkInvalid)?; + auth::blacklist::check_email_token_in_blacklist(&state, &token).await?; + let user = state .store - .find_user_by_email(token.get_email()) + .find_user_by_email(email_token.get_email()) .await .change_context(UserErrors::InternalServerError)?; @@ -1115,6 +1142,10 @@ pub async fn verify_email( .await? }; + let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token) + .await + .map_err(|e| logger::error!(?e)); + Ok(ApplicationResponse::Json( signin_strategy.get_signin_response(&state).await?, )) diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index 6fab28433b4..325ef29bad3 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -5,6 +5,8 @@ use common_utils::date_time; use error_stack::{IntoReport, ResultExt}; use redis_interface::RedisConnectionPool; +#[cfg(feature = "email")] +use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS}; use crate::{ consts::{JWT_TOKEN_TIME_IN_SECS, USER_BLACKLIST_PREFIX}, core::errors::{ApiErrorResponse, RouterResult}, @@ -47,6 +49,33 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>( .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) } +#[cfg(feature = "email")] +pub async fn insert_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> { + let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); + let expiry = + expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; + redis_conn + .set_key_with_expiry(blacklist_key.as_str(), true, expiry) + .await + .change_context(UserErrors::InternalServerError) +} + +#[cfg(feature = "email")] +pub async fn check_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> { + let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; + let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); + let key_exists = redis_conn + .exists::<()>(blacklist_key.as_str()) + .await + .change_context(UserErrors::InternalServerError)?; + + if key_exists { + return Err(UserErrors::LinkInvalid.into()); + } + Ok(()) +} + fn get_redis_connection<A: AppStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store()
feat
Email JWT blacklist (#3659)
608676c8e26d73b191914960dbcc8b84effb6c7d
2024-09-12 19:18:01
Hrithikesh
refactor: return optional request body from build_request_v2 in ConnectorIntegrationV2 trait (#5865)
false
diff --git a/crates/common_utils/src/request.rs b/crates/common_utils/src/request.rs index 264179fc603..38244e2a3de 100644 --- a/crates/common_utils/src/request.rs +++ b/crates/common_utils/src/request.rs @@ -152,6 +152,11 @@ impl RequestBuilder { self } + pub fn set_optional_body<T: Into<RequestContent>>(mut self, body: Option<T>) -> Self { + body.map(|body| self.body.replace(body.into())); + self + } + pub fn set_body<T: Into<RequestContent>>(mut self, body: T) -> Self { self.body.replace(body.into()); self diff --git a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs index 90c3f950a4e..9384ed0a0cd 100644 --- a/crates/hyperswitch_interfaces/src/connector_integration_v2.rs +++ b/crates/hyperswitch_interfaces/src/connector_integration_v2.rs @@ -1,7 +1,7 @@ //! definition of the new connector integration trait use common_utils::{ errors::CustomResult, - request::{Method, Request, RequestContent}, + request::{Method, Request, RequestBuilder, RequestContent}, }; use hyperswitch_domain_models::{router_data::ErrorResponse, router_data_v2::RouterDataV2}; use masking::Maskable; @@ -65,6 +65,11 @@ pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<String, errors::ConnectorError> { + metrics::UNIMPLEMENTED_FLOW.add( + &metrics::CONTEXT, + 1, + &add_attributes([("connector", self.id())]), + ); Ok(String::new()) } @@ -72,8 +77,8 @@ pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: fn get_request_body( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, - ) -> CustomResult<RequestContent, errors::ConnectorError> { - Ok(RequestContent::Json(Box::new(json!(r#"{}"#)))) + ) -> CustomResult<Option<RequestContent>, errors::ConnectorError> { + Ok(None) } /// returns form data @@ -87,14 +92,19 @@ pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: /// builds the request and returns it fn build_request_v2( &self, - _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, + req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<Request>, errors::ConnectorError> { - metrics::UNIMPLEMENTED_FLOW.add( - &metrics::CONTEXT, - 1, - &add_attributes([("connector", self.id())]), - ); - Ok(None) + Ok(Some( + RequestBuilder::new() + .method(self.get_http_method()) + .url(self.get_url(req)?.as_str()) + .attach_default_headers() + .headers(self.get_headers(req)?) + .set_optional_body(self.get_request_body(req)?) + .add_certificate(self.get_certificate(req)?) + .add_certificate_key(self.get_certificate_key(req)?) + .build(), + )) } /// accepts the raw api response and decodes it @@ -167,7 +177,7 @@ pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: fn get_certificate( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> { Ok(None) } @@ -175,7 +185,7 @@ pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: fn get_certificate_key( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> { Ok(None) } }
refactor
return optional request body from build_request_v2 in ConnectorIntegrationV2 trait (#5865)
7ddf5ccf30555ce1c28fd0c2341ec760286f0dd4
2022-12-07 19:08:18
Kartikeya Hegde
storage: Added Ephemeral Key types (#83)
false
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 12576e3eee1..af125e0390f 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -3,6 +3,7 @@ pub mod configs; pub mod connector_response; pub mod customers; pub mod enums; +pub mod ephemeral_key; pub mod events; pub mod locker_mock_up; pub mod mandate; diff --git a/crates/router/src/types/storage/ephemeral_key.rs b/crates/router/src/types/storage/ephemeral_key.rs new file mode 100644 index 00000000000..d3afbbdcfa8 --- /dev/null +++ b/crates/router/src/types/storage/ephemeral_key.rs @@ -0,0 +1,16 @@ +pub struct EphemeralKeyNew { + pub id: String, + pub merchant_id: String, + pub customer_id: String, + pub secret: String, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct EphemeralKey { + pub id: String, + pub merchant_id: String, + pub customer_id: String, + pub created_at: time::PrimitiveDateTime, + pub expires: time::PrimitiveDateTime, + pub secret: String, +}
storage
Added Ephemeral Key types (#83)
39f255b4b209588dec35d780078c2ab7ceb37b10
2023-11-30 13:06:35
Mani Chandra
feat(core): Add ability to verify connector credentials before integrating the connector (#2986)
false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index efde4a04832..6bb4fd4afa0 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use common_utils::{ crypto::{Encryptable, OptionalEncryptableName}, pii, @@ -614,6 +616,36 @@ pub struct MerchantConnectorCreate { pub status: Option<api_enums::ConnectorStatus>, } +// Different patterns of authentication. +#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(tag = "auth_type")] +pub enum ConnectorAuthType { + TemporaryAuth, + HeaderKey { + api_key: Secret<String>, + }, + BodyKey { + api_key: Secret<String>, + key1: Secret<String>, + }, + SignatureKey { + api_key: Secret<String>, + key1: Secret<String>, + api_secret: Secret<String>, + }, + MultiAuthKey { + api_key: Secret<String>, + key1: Secret<String>, + api_secret: Secret<String>, + key2: Secret<String>, + }, + CurrencyAuthKey { + auth_key_map: HashMap<common_enums::Currency, pii::SecretSerdeValue>, + }, + #[default] + NoKey, +} + #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorWebhookDetails { diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index ab40a96582b..8ef40d31914 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -27,4 +27,5 @@ pub mod routing; pub mod surcharge_decision_configs; pub mod user; pub mod verifications; +pub mod verify_connector; pub mod webhooks; diff --git a/crates/api_models/src/verify_connector.rs b/crates/api_models/src/verify_connector.rs new file mode 100644 index 00000000000..1db5a19a030 --- /dev/null +++ b/crates/api_models/src/verify_connector.rs @@ -0,0 +1,11 @@ +use common_utils::events::{ApiEventMetric, ApiEventsType}; + +use crate::{admin, enums}; + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct VerifyConnectorRequest { + pub connector_name: enums::Connector, + pub connector_account_details: admin::ConnectorAuthType, +} + +common_utils::impl_misc_api_event_type!(VerifyConnectorRequest); diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 61072d06221..49c5cfacad1 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -65,3 +65,8 @@ pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days #[cfg(feature = "email")] pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin"; + +#[cfg(feature = "olap")] +pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; +#[cfg(feature = "olap")] +pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index cff2dc8e58f..30fe1a1ce8c 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -28,4 +28,6 @@ pub mod user; pub mod utils; #[cfg(all(feature = "olap", feature = "kms"))] pub mod verification; +#[cfg(feature = "olap")] +pub mod verify_connector; pub mod webhooks; diff --git a/crates/router/src/core/verify_connector.rs b/crates/router/src/core/verify_connector.rs new file mode 100644 index 00000000000..e837e8b8b25 --- /dev/null +++ b/crates/router/src/core/verify_connector.rs @@ -0,0 +1,63 @@ +use api_models::{enums::Connector, verify_connector::VerifyConnectorRequest}; +use error_stack::{IntoReport, ResultExt}; + +use crate::{ + connector, + core::errors, + services, + types::{ + api, + api::verify_connector::{self as types, VerifyConnector}, + }, + utils::verify_connector as utils, + AppState, +}; + +pub async fn verify_connector_credentials( + state: AppState, + req: VerifyConnectorRequest, +) -> errors::RouterResponse<()> { + let boxed_connector = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &req.connector_name.to_string(), + api::GetToken::Connector, + None, + ) + .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?; + + let card_details = utils::get_test_card_details(req.connector_name)? + .ok_or(errors::ApiErrorResponse::FlowNotSupported { + flow: "Verify credentials".to_string(), + connector: req.connector_name.to_string(), + }) + .into_report()?; + + match req.connector_name { + Connector::Stripe => { + connector::Stripe::verify( + &state, + types::VerifyConnectorData { + connector: *boxed_connector.connector, + connector_auth: req.connector_account_details.into(), + card_details, + }, + ) + .await + } + Connector::Paypal => connector::Paypal::get_access_token( + &state, + types::VerifyConnectorData { + connector: *boxed_connector.connector, + connector_auth: req.connector_account_details.into(), + card_details, + }, + ) + .await + .map(|_| services::ApplicationResponse::StatusOk), + _ => Err(errors::ApiErrorResponse::FlowNotSupported { + flow: "Verify credentials".to_string(), + connector: req.connector_name.to_string(), + }) + .into_report(), + } +} diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 37cc1339e1a..22c2610d325 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -29,6 +29,8 @@ pub mod routing; pub mod user; #[cfg(all(feature = "olap", feature = "kms"))] pub mod verification; +#[cfg(feature = "olap")] +pub mod verify_connector; pub mod webhooks; pub mod locker_migration; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 80993429c4e..2a7e1ab6190 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -30,6 +30,8 @@ use super::{cache::*, health::*}; use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*}; #[cfg(feature = "oltp")] use super::{ephemeral_key::*, payment_methods::*, webhooks::*}; +#[cfg(feature = "olap")] +use crate::routes::verify_connector::payment_connector_verify; pub use crate::{ configs::settings, db::{StorageImpl, StorageInterface}, @@ -548,6 +550,10 @@ impl MerchantConnectorAccount { use super::admin::*; route = route + .service( + web::resource("/connectors/verify") + .route(web::post().to(payment_connector_verify)), + ) .service( web::resource("/{merchant_id}/connectors") .route(web::post().to(payment_connector_create)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 5c2ad123749..c7369b9e4d5 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -147,7 +147,9 @@ impl From<Flow> for ApiIdentifier { | Flow::GsmRuleUpdate | Flow::GsmRuleDelete => Self::Gsm, - Flow::UserConnectAccount | Flow::ChangePassword => Self::User, + Flow::UserConnectAccount | Flow::ChangePassword | Flow::VerifyPaymentConnector => { + Self::User + } } } } diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs new file mode 100644 index 00000000000..bfb1b781ada --- /dev/null +++ b/crates/router/src/routes/verify_connector.rs @@ -0,0 +1,28 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use api_models::verify_connector::VerifyConnectorRequest; +use router_env::{instrument, tracing, Flow}; + +use super::AppState; +use crate::{ + core::{api_locking, verify_connector}, + services::{self, authentication as auth, authorization::permissions::Permission}, +}; + +#[instrument(skip_all, fields(flow = ?Flow::VerifyPaymentConnector))] +pub async fn payment_connector_verify( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<VerifyConnectorRequest>, +) -> HttpResponse { + let flow = Flow::VerifyPaymentConnector; + Box::pin(services::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _: (), req| verify_connector::verify_connector_credentials(state, req), + &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index cd37fbb549d..c3118f0c05b 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -33,7 +33,7 @@ use crate::{ payments::{PaymentData, RecurringMandatePaymentData}, }, services, - types::storage::payment_attempt::PaymentAttemptExt, + types::{storage::payment_attempt::PaymentAttemptExt, transformers::ForeignFrom}, utils::OptionExt, }; @@ -942,6 +942,78 @@ pub enum ConnectorAuthType { NoKey, } +impl From<api_models::admin::ConnectorAuthType> for ConnectorAuthType { + fn from(value: api_models::admin::ConnectorAuthType) -> Self { + match value { + api_models::admin::ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, + api_models::admin::ConnectorAuthType::HeaderKey { api_key } => { + Self::HeaderKey { api_key } + } + api_models::admin::ConnectorAuthType::BodyKey { api_key, key1 } => { + Self::BodyKey { api_key, key1 } + } + api_models::admin::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Self::SignatureKey { + api_key, + key1, + api_secret, + }, + api_models::admin::ConnectorAuthType::MultiAuthKey { + api_key, + key1, + api_secret, + key2, + } => Self::MultiAuthKey { + api_key, + key1, + api_secret, + key2, + }, + api_models::admin::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { + Self::CurrencyAuthKey { auth_key_map } + } + api_models::admin::ConnectorAuthType::NoKey => Self::NoKey, + } + } +} + +impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType { + fn foreign_from(from: ConnectorAuthType) -> Self { + match from { + ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, + ConnectorAuthType::HeaderKey { api_key } => Self::HeaderKey { api_key }, + ConnectorAuthType::BodyKey { api_key, key1 } => Self::BodyKey { api_key, key1 }, + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Self::SignatureKey { + api_key, + key1, + api_secret, + }, + ConnectorAuthType::MultiAuthKey { + api_key, + key1, + api_secret, + key2, + } => Self::MultiAuthKey { + api_key, + key1, + api_secret, + key2, + }, + ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { + Self::CurrencyAuthKey { auth_key_map } + } + ConnectorAuthType::NoKey => Self::NoKey, + } + } +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorsList { pub connectors: Vec<String>, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index bcb3a9add55..96bcaca3ed5 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -13,6 +13,8 @@ pub mod payments; pub mod payouts; pub mod refunds; pub mod routing; +#[cfg(feature = "olap")] +pub mod verify_connector; pub mod webhooks; use std::{fmt::Debug, str::FromStr}; diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs new file mode 100644 index 00000000000..3e3511ccb98 --- /dev/null +++ b/crates/router/src/types/api/verify_connector.rs @@ -0,0 +1,181 @@ +pub mod paypal; +pub mod stripe; + +use error_stack::{IntoReport, ResultExt}; + +use crate::{ + consts, + core::errors, + services, + services::ConnectorIntegration, + types::{self, api, storage::enums as storage_enums}, + AppState, +}; + +#[derive(Clone, Debug)] +pub struct VerifyConnectorData { + pub connector: &'static (dyn types::api::Connector + Sync), + pub connector_auth: types::ConnectorAuthType, + pub card_details: api::Card, +} + +impl VerifyConnectorData { + fn get_payment_authorize_data(&self) -> types::PaymentsAuthorizeData { + types::PaymentsAuthorizeData { + payment_method_data: api::PaymentMethodData::Card(self.card_details.clone()), + email: None, + amount: 1000, + confirm: true, + currency: storage_enums::Currency::USD, + mandate_id: None, + webhook_url: None, + customer_id: None, + off_session: None, + browser_info: None, + session_token: None, + order_details: None, + order_category: None, + capture_method: None, + enrolled_for_3ds: false, + router_return_url: None, + surcharge_details: None, + setup_future_usage: None, + payment_experience: None, + payment_method_type: None, + statement_descriptor: None, + setup_mandate_details: None, + complete_authorize_url: None, + related_transaction_id: None, + statement_descriptor_suffix: None, + } + } + + fn get_router_data<F, R1, R2>( + &self, + request_data: R1, + access_token: Option<types::AccessToken>, + ) -> types::RouterData<F, R1, R2> { + let attempt_id = + common_utils::generate_id_with_default_len(consts::VERIFY_CONNECTOR_ID_PREFIX); + types::RouterData { + flow: std::marker::PhantomData, + status: storage_enums::AttemptStatus::Started, + request: request_data, + response: Err(errors::ApiErrorResponse::InternalServerError.into()), + connector: self.connector.id().to_string(), + auth_type: storage_enums::AuthenticationType::NoThreeDs, + test_mode: None, + return_url: None, + attempt_id: attempt_id.clone(), + description: None, + customer_id: None, + merchant_id: consts::VERIFY_CONNECTOR_MERCHANT_ID.to_string(), + reference_id: None, + access_token, + session_token: None, + payment_method: storage_enums::PaymentMethod::Card, + amount_captured: None, + preprocessing_id: None, + payment_method_id: None, + connector_customer: None, + connector_auth_type: self.connector_auth.clone(), + connector_meta_data: None, + payment_method_token: None, + connector_api_version: None, + recurring_mandate_payment_data: None, + connector_request_reference_id: attempt_id, + address: types::PaymentAddress { + shipping: None, + billing: None, + }, + payment_id: common_utils::generate_id_with_default_len( + consts::VERIFY_CONNECTOR_ID_PREFIX, + ), + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + payment_method_balance: None, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + } + } +} + +#[async_trait::async_trait] +pub trait VerifyConnector { + async fn verify( + state: &AppState, + connector_data: VerifyConnectorData, + ) -> errors::RouterResponse<()> { + let authorize_data = connector_data.get_payment_authorize_data(); + let access_token = Self::get_access_token(state, connector_data.clone()).await?; + let router_data = connector_data.get_router_data(authorize_data, access_token); + + let request = connector_data + .connector + .build_request(&router_data, &state.conf.connectors) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Payment request cannot be built".to_string(), + })? + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + + let response = services::call_connector_api(&state.to_owned(), request) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + match response { + Ok(_) => Ok(services::ApplicationResponse::StatusOk), + Err(error_response) => { + Self::handle_payment_error_response::< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >(connector_data.connector, error_response) + .await + } + } + } + + async fn get_access_token( + _state: &AppState, + _connector_data: VerifyConnectorData, + ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { + // AccessToken is None for the connectors without the AccessToken Flow. + // If a connector has that, then it should override this implementation. + Ok(None) + } + + async fn handle_payment_error_response<F, R1, R2>( + connector: &(dyn types::api::Connector + Sync), + error_response: types::Response, + ) -> errors::RouterResponse<()> + where + dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, + { + let error = connector + .get_error_response(error_response) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + Err(errors::ApiErrorResponse::InvalidRequestData { + message: error.reason.unwrap_or(error.message), + }) + .into_report() + } + + async fn handle_access_token_error_response<F, R1, R2>( + connector: &(dyn types::api::Connector + Sync), + error_response: types::Response, + ) -> errors::RouterResult<Option<types::AccessToken>> + where + dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, + { + let error = connector + .get_error_response(error_response) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + Err(errors::ApiErrorResponse::InvalidRequestData { + message: error.reason.unwrap_or(error.message), + }) + .into_report() + } +} diff --git a/crates/router/src/types/api/verify_connector/paypal.rs b/crates/router/src/types/api/verify_connector/paypal.rs new file mode 100644 index 00000000000..33e848f909d --- /dev/null +++ b/crates/router/src/types/api/verify_connector/paypal.rs @@ -0,0 +1,54 @@ +use error_stack::ResultExt; + +use super::{VerifyConnector, VerifyConnectorData}; +use crate::{ + connector, + core::errors, + routes::AppState, + services, + types::{self, api}, +}; + +#[async_trait::async_trait] +impl VerifyConnector for connector::Paypal { + async fn get_access_token( + state: &AppState, + connector_data: VerifyConnectorData, + ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { + let token_data: types::AccessTokenRequestData = + connector_data.connector_auth.clone().try_into()?; + let router_data = connector_data.get_router_data(token_data, None); + + let request = connector_data + .connector + .build_request(&router_data, &state.conf.connectors) + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Payment request cannot be built".to_string(), + })? + .ok_or(errors::ApiErrorResponse::InternalServerError)?; + + let response = services::call_connector_api(&state.to_owned(), request) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + match response { + Ok(res) => Some( + connector_data + .connector + .handle_response(&router_data, res) + .change_context(errors::ApiErrorResponse::InternalServerError)? + .response + .map_err(|_| errors::ApiErrorResponse::InternalServerError.into()), + ) + .transpose(), + Err(response_data) => { + Self::handle_access_token_error_response::< + api::AccessTokenAuth, + types::AccessTokenRequestData, + types::AccessToken, + >(connector_data.connector, response_data) + .await + } + } + } +} diff --git a/crates/router/src/types/api/verify_connector/stripe.rs b/crates/router/src/types/api/verify_connector/stripe.rs new file mode 100644 index 00000000000..ece9fa15a1d --- /dev/null +++ b/crates/router/src/types/api/verify_connector/stripe.rs @@ -0,0 +1,36 @@ +use error_stack::{IntoReport, ResultExt}; +use router_env::env; + +use super::VerifyConnector; +use crate::{ + connector, + core::errors, + services::{self, ConnectorIntegration}, + types, +}; + +#[async_trait::async_trait] +impl VerifyConnector for connector::Stripe { + async fn handle_payment_error_response<F, R1, R2>( + connector: &(dyn types::api::Connector + Sync), + error_response: types::Response, + ) -> errors::RouterResponse<()> + where + dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, + { + let error = connector + .get_error_response(error_response) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + match (env::which(), error.code.as_str()) { + // In situations where an attempt is made to process a payment using a + // Stripe production key along with a test card (which verify_connector is using), + // Stripe will respond with a "card_declined" error. In production, + // when this scenario occurs we will send back an "Ok" response. + (env::Env::Production, "card_declined") => Ok(services::ApplicationResponse::StatusOk), + _ => Err(errors::ApiErrorResponse::InvalidRequestData { + message: error.reason.unwrap_or(error.message), + }) + .into_report(), + } + } +} diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index c936ee858c1..81968cd9b62 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -6,6 +6,8 @@ pub mod ext_traits; pub mod storage_partitioning; #[cfg(feature = "olap")] pub mod user; +#[cfg(feature = "olap")] +pub mod verify_connector; use std::fmt::Debug; diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rs new file mode 100644 index 00000000000..6ad683d63ba --- /dev/null +++ b/crates/router/src/utils/verify_connector.rs @@ -0,0 +1,49 @@ +use api_models::enums::Connector; +use error_stack::{IntoReport, ResultExt}; + +use crate::{core::errors, types::api}; + +pub fn generate_card_from_details( + card_number: String, + card_exp_year: String, + card_exp_month: String, + card_cvv: String, +) -> errors::RouterResult<api::Card> { + Ok(api::Card { + card_number: card_number + .parse() + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while parsing card number")?, + card_issuer: None, + card_cvc: masking::Secret::new(card_cvv), + card_network: None, + card_exp_year: masking::Secret::new(card_exp_year), + card_exp_month: masking::Secret::new(card_exp_month), + card_holder_name: masking::Secret::new("HyperSwitch".to_string()), + nick_name: None, + card_type: None, + card_issuing_country: None, + bank_code: None, + }) +} + +pub fn get_test_card_details(connector_name: Connector) -> errors::RouterResult<Option<api::Card>> { + match connector_name { + Connector::Stripe => Some(generate_card_from_details( + "4242424242424242".to_string(), + "2025".to_string(), + "12".to_string(), + "100".to_string(), + )) + .transpose(), + Connector::Paypal => Some(generate_card_from_details( + "4111111111111111".to_string(), + "2025".to_string(), + "02".to_string(), + "123".to_string(), + )) + .transpose(), + _ => Ok(None), + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 2a174f42eb6..c254f89b4ee 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -259,6 +259,8 @@ pub enum Flow { DecisionManagerRetrieveConfig, /// Change password flow ChangePassword, + /// Payment Connector Verify + VerifyPaymentConnector, } ///
feat
Add ability to verify connector credentials before integrating the connector (#2986)
35c9b8afe1a09b858c79c0ce13cf5c24d200d3fd
2024-07-17 15:56:41
Sandeep Kumar
feat(globalsearch): Added search_tags based filter for global search in dashboard (#5341)
false
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 79605b77fa4..12b3d2a05fd 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -9515,11 +9515,11 @@ "nullable": true }, "search_tags": { - "allOf": [ - { - "$ref": "#/components/schemas/RedirectResponse" - } - ], + "type": "array", + "items": { + "type": "string" + }, + "description": "Additional tags to be used for global search", "nullable": true } } diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs index 269864bf44a..a5bd117bd63 100644 --- a/crates/analytics/src/search.rs +++ b/crates/analytics/src/search.rs @@ -66,6 +66,24 @@ pub async fn msearch_results( .switch()?; } }; + if let Some(search_tags) = filters.search_tags { + if !search_tags.is_empty() { + query_builder + .add_filter_clause( + "feature_metadata.search_tags.keyword".to_string(), + search_tags + .iter() + .filter_map(|search_tag| { + // TODO: Add trait based inputs instead of converting this to strings + serde_json::to_value(search_tag) + .ok() + .and_then(|a| a.as_str().map(|a| a.to_string())) + }) + .collect(), + ) + .switch()?; + } + }; }; let response_text: OpenMsearchOutput = client @@ -173,6 +191,24 @@ pub async fn search_results( .switch()?; } }; + if let Some(search_tags) = filters.search_tags { + if !search_tags.is_empty() { + query_builder + .add_filter_clause( + "feature_metadata.search_tags.keyword".to_string(), + search_tags + .iter() + .filter_map(|search_tag| { + // TODO: Add trait based inputs instead of converting this to strings + serde_json::to_value(search_tag) + .ok() + .and_then(|a| a.as_str().map(|a| a.to_string())) + }) + .collect(), + ) + .switch()?; + } + }; }; query_builder .set_offset_n_count(search_req.offset, search_req.count) diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index 034a2a94356..d1af00de569 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -1,4 +1,5 @@ use common_utils::hashing::HashedString; +use masking::WithType; use serde_json::Value; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] @@ -7,6 +8,7 @@ pub struct SearchFilters { pub currency: Option<Vec<String>>, pub status: Option<Vec<String>>, pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>, + pub search_tags: Option<Vec<HashedString<WithType>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index f53507fc13a..c04af204493 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -9,11 +9,12 @@ use common_utils::{ consts::default_payments_list_limit, crypto, ext_traits::{ConfigExt, Encode}, + hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; -use masking::{PeekInterface, Secret}; +use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{ de::{self, Unexpected, Visitor}, @@ -4987,11 +4988,12 @@ pub struct PaymentsStartRequest { #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios + #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, // TODO: Convert this to hashedstrings to avoid PII sensitive data /// Additional tags to be used for global search - #[schema(value_type = Option<RedirectResponse>)] - pub search_tags: Option<Vec<Secret<String>>>, + #[schema(value_type = Option<Vec<String>>)] + pub search_tags: Option<Vec<HashedString<WithType>>>, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None diff --git a/crates/masking/src/strategy.rs b/crates/masking/src/strategy.rs index 8b4d9b0ec34..eb705ca490a 100644 --- a/crates/masking/src/strategy.rs +++ b/crates/masking/src/strategy.rs @@ -7,6 +7,8 @@ pub trait Strategy<T> { } /// Debug with type +#[cfg_attr(feature = "serde", derive(serde::Deserialize))] +#[derive(Debug, Copy, Clone)] pub enum WithType {} impl<T> Strategy<T> for WithType {
feat
Added search_tags based filter for global search in dashboard (#5341)
2216a88d25c42ede9862f6d036e7b0586a2e7c28
2024-05-07 16:05:32
Chethan Rao
chore: address Rust 1.78 clippy lints (#4545)
false
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 4d01c20972c..8f0d00cd799 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -453,7 +453,7 @@ where |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), - order.to_string() + order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) @@ -476,7 +476,7 @@ where |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), - order.to_string() + order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 2a7075a0f29..ae10fc9889e 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -78,14 +78,16 @@ impl Default for AnalyticsProvider { } } -impl ToString for AnalyticsProvider { - fn to_string(&self) -> String { - String::from(match self { +impl std::fmt::Display for AnalyticsProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let analytics_provider = match self { Self::Clickhouse(_) => "Clickhouse", Self::Sqlx(_) => "Sqlx", Self::CombinedCkh(_, _) => "CombinedCkh", Self::CombinedSqlx(_, _) => "CombinedSqlx", - }) + }; + + write!(f, "{}", analytics_provider) } } diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs index c340f2888f8..efc8aaf6983 100644 --- a/crates/analytics/src/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -153,10 +153,7 @@ impl PaymentMetricAccumulator for SumAccumulator { fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { self.total = match ( self.total, - metrics - .total - .as_ref() - .and_then(bigdecimal::ToPrimitive::to_i64), + metrics.total.as_ref().and_then(ToPrimitive::to_i64), ) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, @@ -173,10 +170,7 @@ impl PaymentMetricAccumulator for AverageAccumulator { type MetricOutput = Option<f64>; fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { - let total = metrics - .total - .as_ref() - .and_then(bigdecimal::ToPrimitive::to_u32); + let total = metrics.total.as_ref().and_then(ToPrimitive::to_u32); let count = metrics.count.and_then(|total| u32::try_from(total).ok()); match (total, count) { diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index d5296152076..525bc0f8467 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -286,12 +286,12 @@ pub enum Order { Descending, } -impl ToString for Order { - fn to_string(&self) -> String { - String::from(match self { - Self::Ascending => "asc", - Self::Descending => "desc", - }) +impl std::fmt::Display for Order { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Ascending => write!(f, "asc"), + Self::Descending => write!(f, "desc"), + } } } @@ -709,12 +709,12 @@ where Ok(query) } - pub async fn execute_query<R, P: AnalyticsDataSource>( + pub async fn execute_query<R, P>( &mut self, store: &P, ) -> CustomResult<CustomResult<Vec<R>, QueryExecutionError>, QueryBuildingError> where - P: LoadRow<R>, + P: LoadRow<R> + AnalyticsDataSource, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { diff --git a/crates/analytics/src/refunds.rs b/crates/analytics/src/refunds.rs index 53481e23281..590dc148ebf 100644 --- a/crates/analytics/src/refunds.rs +++ b/crates/analytics/src/refunds.rs @@ -6,5 +6,4 @@ pub mod metrics; pub mod types; pub use accumulator::{RefundMetricAccumulator, RefundMetricsAccumulator}; -pub trait RefundAnalytics: metrics::RefundMetricAnalytics {} pub use self::core::{get_filters, get_metrics}; diff --git a/crates/analytics/src/sdk_events.rs b/crates/analytics/src/sdk_events.rs index fe8af7cfe2d..a02de4cbbee 100644 --- a/crates/analytics/src/sdk_events.rs +++ b/crates/analytics/src/sdk_events.rs @@ -5,10 +5,5 @@ pub mod filters; pub mod metrics; pub mod types; pub use accumulator::{SdkEventMetricAccumulator, SdkEventMetricsAccumulator}; -pub trait SDKEventAnalytics: events::SdkEventsFilterAnalytics {} -pub trait SdkEventAnalytics: - metrics::SdkEventMetricAnalytics + filters::SdkEventFilterAnalytics -{ -} pub use self::core::{get_filters, get_metrics, sdk_events_core}; diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 86782c5f750..133e959d63b 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -593,7 +593,7 @@ where |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), - order.to_string() + order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) @@ -616,7 +616,7 @@ where |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), - order.to_string() + order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {}", alias)) diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 356d11bb77d..d0c1d74bc10 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -63,11 +63,6 @@ where } } -// Analytics Framework - -pub trait RefundAnalytics {} -pub trait SdkEventAnalytics {} - #[async_trait::async_trait] pub trait AnalyticsDataSource where diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 75bd2a31d8e..e845317b693 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -456,7 +456,7 @@ pub struct MerchantConnectorCreate { pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector - #[schema(example = json!(common_utils::consts::FRM_CONFIGS_EG))] + #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead @@ -609,7 +609,7 @@ pub struct MerchantConnectorResponse { pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector - #[schema(example = json!(common_utils::consts::FRM_CONFIGS_EG))] + #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead @@ -702,7 +702,7 @@ pub struct MerchantConnectorUpdate { pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector - #[schema(example = json!(common_utils::consts::FRM_CONFIGS_EG))] + #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, pub pm_auth_config: Option<serde_json::Value>, diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs index 805c5616c2a..801bbc63f5f 100644 --- a/crates/api_models/src/api_keys.rs +++ b/crates/api_models/src/api_keys.rs @@ -270,7 +270,7 @@ mod api_key_expiration_tests { let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( - serde_json::to_string(&ApiKeyExpiration::DateTime(time::PrimitiveDateTime::new( + serde_json::to_string(&ApiKeyExpiration::DateTime(PrimitiveDateTime::new( date, time ))) .unwrap(), @@ -289,7 +289,7 @@ mod api_key_expiration_tests { let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(), - ApiKeyExpiration::DateTime(time::PrimitiveDateTime::new(date, time)) + ApiKeyExpiration::DateTime(PrimitiveDateTime::new(date, time)) ); } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 8270ddaf3fe..0e46eb19931 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -682,7 +682,7 @@ impl PaymentsRequest { .as_ref() .map(|od| { od.iter() - .map(|order| order.encode_to_value().map(masking::Secret::new)) + .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() @@ -1304,9 +1304,7 @@ mod payment_method_data_serde { match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) - .map_err(|serde_json_error| { - serde::de::Error::custom(serde_json_error.to_string()) - })?; + .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data @@ -1321,14 +1319,12 @@ mod payment_method_data_serde { payment_method_data_value, ) .map_err(|serde_json_error| { - serde::de::Error::custom(serde_json_error.to_string()) + de::Error::custom(serde_json_error.to_string()) })?, ) } } else { - Err(serde::de::Error::custom( - "Expected a map for payment_method_data", - ))? + Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None @@ -1342,7 +1338,7 @@ mod payment_method_data_serde { __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, - _ => Err(serde::de::Error::custom("Invalid Variant"))?, + _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { @@ -2686,8 +2682,8 @@ pub enum PaymentIdType { PreprocessingId(String), } -impl std::fmt::Display for PaymentIdType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Display for PaymentIdType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!(f, "payment_intent_id = \"{payment_id}\"") diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index f3d966f3d9d..a7c4ed24475 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -203,8 +203,8 @@ pub struct RoutableConnectorChoice { pub sub_label: Option<String>, } -impl ToString for RoutableConnectorChoice { - fn to_string(&self) -> String { +impl std::fmt::Display for RoutableConnectorChoice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { #[cfg(feature = "connector_choice_mca_id")] let base = self.connector.to_string(); @@ -219,7 +219,7 @@ impl ToString for RoutableConnectorChoice { sub_base }; - base + write!(f, "{}", base) } } @@ -329,7 +329,7 @@ pub enum RoutingAlgorithm { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), #[schema(value_type=ProgramConnectorSelection)] - Advanced(euclid::frontend::ast::Program<ConnectorSelection>), + Advanced(ast::Program<ConnectorSelection>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -338,7 +338,7 @@ pub enum RoutingAlgorithmSerde { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), - Advanced(euclid::frontend::ast::Program<ConnectorSelection>), + Advanced(ast::Program<ConnectorSelection>), } impl TryFrom<RoutingAlgorithmSerde> for RoutingAlgorithm { diff --git a/crates/api_models/src/user/dashboard_metadata.rs b/crates/api_models/src/user/dashboard_metadata.rs index b547a61d450..d8a437e31a6 100644 --- a/crates/api_models/src/user/dashboard_metadata.rs +++ b/crates/api_models/src/user/dashboard_metadata.rs @@ -33,7 +33,7 @@ pub enum SetMetaDataRequest { pub struct ProductionAgreementRequest { pub version: String, #[serde(skip_deserializing)] - pub ip_address: Option<Secret<String, common_utils::pii::IpAddress>>, + pub ip_address: Option<Secret<String, pii::IpAddress>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs index 46904535f01..7901dec6db2 100644 --- a/crates/common_utils/src/crypto.rs +++ b/crates/common_utils/src/crypto.rs @@ -38,14 +38,14 @@ impl NonceSequence { } /// Returns the current nonce value as bytes. - fn current(&self) -> [u8; ring::aead::NONCE_LEN] { - let mut nonce = [0_u8; ring::aead::NONCE_LEN]; + fn current(&self) -> [u8; aead::NONCE_LEN] { + let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); nonce } /// Constructs a nonce sequence from bytes - fn from_bytes(bytes: [u8; ring::aead::NONCE_LEN]) -> Self { + fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self { let mut sequence_number = [0_u8; 128 / 8]; sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes); let sequence_number = u128::from_be_bytes(sequence_number); @@ -53,16 +53,16 @@ impl NonceSequence { } } -impl ring::aead::NonceSequence for NonceSequence { - fn advance(&mut self) -> Result<ring::aead::Nonce, ring::error::Unspecified> { - let mut nonce = [0_u8; ring::aead::NONCE_LEN]; +impl aead::NonceSequence for NonceSequence { + fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> { + let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); // Increment sequence number self.0 = self.0.wrapping_add(1); // Return previous sequence number as bytes - Ok(ring::aead::Nonce::assume_unique_for_key(nonce)) + Ok(aead::Nonce::assume_unique_for_key(nonce)) } } @@ -275,8 +275,8 @@ impl DecodeMessage for GcmAes256 { .change_context(errors::CryptoError::DecodingFailed)?; let nonce_sequence = NonceSequence::from_bytes( - <[u8; ring::aead::NONCE_LEN]>::try_from( - msg.get(..ring::aead::NONCE_LEN) + <[u8; aead::NONCE_LEN]>::try_from( + msg.get(..aead::NONCE_LEN) .ok_or(errors::CryptoError::DecodingFailed) .attach_printable("Failed to read the nonce form the encrypted ciphertext")?, ) @@ -288,7 +288,7 @@ impl DecodeMessage for GcmAes256 { let output = binding.as_mut_slice(); let result = key - .open_within(aead::Aad::empty(), output, ring::aead::NONCE_LEN..) + .open_within(aead::Aad::empty(), output, aead::NONCE_LEN..) .change_context(errors::CryptoError::DecodingFailed)?; Ok(result.to_vec()) diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index f71e098a99c..5ad53ec8533 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -472,13 +472,13 @@ pub trait XmlExt { /// /// Deserialize an XML string into the specified type `<T>`. /// - fn parse_xml<T>(self) -> Result<T, quick_xml::de::DeError> + fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned; } impl XmlExt for &str { - fn parse_xml<T>(self) -> Result<T, quick_xml::de::DeError> + fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned, { diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index c1f9d716e4b..9c70c572fed 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -38,7 +38,7 @@ pub struct PhoneNumber(Secret<String, PhoneNumberStrategy>); impl<T> Strategy<T> for PhoneNumberStrategy where - T: AsRef<str> + std::fmt::Debug, + T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); @@ -85,7 +85,7 @@ impl ops::DerefMut for PhoneNumber { } } -impl<DB> Queryable<diesel::sql_types::Text, DB> for PhoneNumber +impl<DB> Queryable<sql_types::Text, DB> for PhoneNumber where DB: Backend, Self: FromSql<sql_types::Text, DB>, @@ -210,7 +210,7 @@ pub enum EmailStrategy {} impl<T> Strategy<T> for EmailStrategy where - T: AsRef<str> + std::fmt::Debug, + T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let val_str: &str = val.as_ref(); @@ -224,7 +224,7 @@ where #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default, AsExpression, )] -#[diesel(sql_type = diesel::sql_types::Text)] +#[diesel(sql_type = sql_types::Text)] #[serde(try_from = "String")] pub struct Email(Secret<String, EmailStrategy>); @@ -262,7 +262,7 @@ impl ops::DerefMut for Email { } } -impl<DB> Queryable<diesel::sql_types::Text, DB> for Email +impl<DB> Queryable<sql_types::Text, DB> for Email where DB: Backend, Self: FromSql<sql_types::Text, DB>, @@ -353,7 +353,7 @@ pub enum UpiVpaMaskingStrategy {} impl<T> Strategy<T> for UpiVpaMaskingStrategy where - T: AsRef<str> + std::fmt::Debug, + T: AsRef<str> + fmt::Debug, { fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result { let vpa_str: &str = val.as_ref(); diff --git a/crates/common_utils/src/static_cache.rs b/crates/common_utils/src/static_cache.rs index ca608fa9a3b..37705c892c5 100644 --- a/crates/common_utils/src/static_cache.rs +++ b/crates/common_utils/src/static_cache.rs @@ -26,6 +26,8 @@ impl<T> StaticCache<T> where T: Send, { + // Cannot have default impl as it cannot be called during instantiation of static item + #[allow(clippy::new_without_default)] pub const fn new() -> Self { Self { data: Lazy::new(|| RwLock::new(FxHashMap::default())), diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 203e48ac507..f89c2e5921b 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -98,12 +98,11 @@ impl DashboardRequestPayload { if let Some(payment_methods_enabled) = request.payment_methods_enabled.clone() { for payload in payment_methods_enabled { match payload.payment_method { - api_models::enums::PaymentMethod::Card => { + PaymentMethod::Card => { if let Some(card_provider) = payload.card_provider { - let payment_type = api_models::enums::PaymentMethodType::from_str( - &payload.payment_method_type, - ) - .map_err(|_| "Invalid key received".to_string()); + let payment_type = + PaymentMethodType::from_str(&payload.payment_method_type) + .map_err(|_| "Invalid key received".to_string()); if let Ok(payment_type) = payment_type { for method in card_provider { @@ -124,17 +123,17 @@ impl DashboardRequestPayload { } } - api_models::enums::PaymentMethod::Wallet - | api_models::enums::PaymentMethod::BankRedirect - | api_models::enums::PaymentMethod::PayLater - | api_models::enums::PaymentMethod::BankTransfer - | api_models::enums::PaymentMethod::Crypto - | api_models::enums::PaymentMethod::BankDebit - | api_models::enums::PaymentMethod::Reward - | api_models::enums::PaymentMethod::Upi - | api_models::enums::PaymentMethod::Voucher - | api_models::enums::PaymentMethod::GiftCard - | api_models::enums::PaymentMethod::CardRedirect => { + PaymentMethod::Wallet + | PaymentMethod::BankRedirect + | PaymentMethod::PayLater + | PaymentMethod::BankTransfer + | PaymentMethod::Crypto + | PaymentMethod::BankDebit + | PaymentMethod::Reward + | PaymentMethod::Upi + | PaymentMethod::Voucher + | PaymentMethod::GiftCard + | PaymentMethod::CardRedirect => { if let Some(provider) = payload.provider { let val = Self::transform_payment_method( request.connector, @@ -154,7 +153,7 @@ impl DashboardRequestPayload { } if !card_payment_method_types.is_empty() { let card = PaymentMethodsEnabled { - payment_method: api_models::enums::PaymentMethod::Card, + payment_method: PaymentMethod::Card, payment_method_types: Some(card_payment_method_types), }; payment_method_enabled.push(card); diff --git a/crates/diesel_models/src/encryption.rs b/crates/diesel_models/src/encryption.rs index 375259491c9..6c6063c1604 100644 --- a/crates/diesel_models/src/encryption.rs +++ b/crates/diesel_models/src/encryption.rs @@ -8,7 +8,7 @@ use diesel::{ use masking::Secret; #[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)] -#[diesel(sql_type = diesel::sql_types::Binary)] +#[diesel(sql_type = sql_types::Binary)] #[repr(transparent)] pub struct Encryption { inner: Secret<Vec<u8>, EncryptionStrategy>, @@ -41,7 +41,7 @@ where DB: Backend, Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>, { - fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { <Secret<Vec<u8>, EncryptionStrategy>>::from_sql(bytes).map(Self::new) } } diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index f23c2318899..4e5773800aa 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -10,7 +10,7 @@ use error_stack::{report, ResultExt}; use super::generics; use crate::{ enums::{self, IntentStatus}, - errors::{self, DatabaseError}, + errors::DatabaseError, payment_attempt::{ PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate, PaymentAttemptUpdateInternal, }, @@ -246,7 +246,7 @@ impl PaymentAttempt { .distinct() .get_results_async::<Option<String>>(conn) .await - .change_context(errors::DatabaseError::Others) + .change_context(DatabaseError::Others) .attach_printable("Error filtering records by connector")? .into_iter() .flatten() @@ -350,7 +350,7 @@ impl PaymentAttempt { db_metrics::DatabaseOperation::Filter, ) .await - .change_context(errors::DatabaseError::Others) + .change_context(DatabaseError::Others) .attach_printable("Error filtering count of payments") } } diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs index ac34ee695ac..4f95877bd7c 100644 --- a/crates/diesel_models/src/query/payout_attempt.rs +++ b/crates/diesel_models/src/query/payout_attempt.rs @@ -11,7 +11,7 @@ use error_stack::{report, ResultExt}; use super::generics; use crate::{ enums, - errors::{self, DatabaseError}, + errors::DatabaseError, payout_attempt::{ PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal, }, @@ -46,7 +46,7 @@ impl PayoutAttempt { .await { Err(error) => match error.current_context() { - errors::DatabaseError::NoFieldsToUpdate => Ok(self), + DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, @@ -98,7 +98,7 @@ impl PayoutAttempt { .first() .cloned() .ok_or_else(|| { - report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout") + report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } @@ -119,7 +119,7 @@ impl PayoutAttempt { .first() .cloned() .ok_or_else(|| { - report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout") + report!(DatabaseError::NotFound).attach_printable("Error while updating payout") }) } @@ -161,7 +161,7 @@ impl PayoutAttempt { .distinct() .get_results_async::<Option<String>>(conn) .await - .change_context(errors::DatabaseError::Others) + .change_context(DatabaseError::Others) .attach_printable("Error filtering records by connector")? .into_iter() .flatten() diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs index 47b60db80d5..35ad467d5fe 100644 --- a/crates/drainer/src/handler.rs +++ b/crates/drainer/src/handler.rs @@ -95,7 +95,7 @@ impl Handler { while let Some(_c) = rx.recv().await { logger::info!("Awaiting shutdown!"); metrics::SHUTDOWN_SIGNAL_RECEIVED.add(&metrics::CONTEXT, 1, &[]); - let shutdown_started = tokio::time::Instant::now(); + let shutdown_started = time::Instant::now(); rx.close(); //Check until the active tasks are zero. This does not include the tasks in the stream. diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index 56f2db0907e..cb2b55d202f 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -24,7 +24,7 @@ use router_env::{ }; use tokio::sync::mpsc; -pub(crate) type Settings = crate::settings::Settings<RawSecret>; +pub(crate) type Settings = settings::Settings<RawSecret>; use crate::{ connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData, diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 526248a3817..0ffafe4d48b 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -838,7 +838,7 @@ mod test { None::<()>, ); let mut memo = cgraph::Memoization::new(); - let mut cycle_map = cgraph::CycleCheck::new(); + let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( _node_1, @@ -894,7 +894,7 @@ mod test { None::<()>, ); let mut memo = cgraph::Memoization::new(); - let mut cycle_map = cgraph::CycleCheck::new(); + let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( @@ -986,7 +986,7 @@ mod test { ); let mut memo = cgraph::Memoization::new(); - let mut cycle_map = cgraph::CycleCheck::new(); + let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( diff --git a/crates/euclid/src/frontend/ast/parser.rs b/crates/euclid/src/frontend/ast/parser.rs index 8b2f717a868..cbfc21c96a7 100644 --- a/crates/euclid/src/frontend/ast/parser.rs +++ b/crates/euclid/src/frontend/ast/parser.rs @@ -3,7 +3,7 @@ use nom::{ }; use crate::{frontend::ast, types::DummyOutput}; -pub type ParseResult<T, U> = nom::IResult<T, U, nom::error::VerboseError<T>>; +pub type ParseResult<T, U> = nom::IResult<T, U, error::VerboseError<T>>; pub enum EuclidError { InvalidPercentage(String), @@ -50,9 +50,9 @@ impl EuclidParsable for DummyOutput { )(input) } } -pub fn skip_ws<'a, F: 'a, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&str, O> +pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&str, O> where - F: FnMut(&'a str) -> ParseResult<&str, O>, + F: FnMut(&'a str) -> ParseResult<&str, O> + 'a, { sequence::preceded(pchar::multispace0, inner) } diff --git a/crates/euclid_macros/src/inner/knowledge.rs b/crates/euclid_macros/src/inner/knowledge.rs index a9c453b42c6..baef55338f0 100644 --- a/crates/euclid_macros/src/inner/knowledge.rs +++ b/crates/euclid_macros/src/inner/knowledge.rs @@ -1,4 +1,8 @@ -use std::{hash::Hash, rc::Rc}; +use std::{ + fmt::{Display, Formatter}, + hash::Hash, + rc::Rc, +}; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; @@ -24,15 +28,16 @@ enum Comparison { LessThanEqual, } -impl ToString for Comparison { - fn to_string(&self) -> String { - match self { - Self::LessThan => "< ".to_string(), - Self::Equal => String::new(), - Self::GreaterThanEqual => ">= ".to_string(), - Self::LessThanEqual => "<= ".to_string(), - Self::GreaterThan => "> ".to_string(), - } +impl Display for Comparison { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let symbol = match self { + Self::LessThan => "< ", + Self::Equal => return Ok(()), + Self::GreaterThanEqual => ">= ", + Self::LessThanEqual => "<= ", + Self::GreaterThan => "> ", + }; + write!(f, "{}", symbol) } } @@ -69,7 +74,7 @@ impl ValueType { Self::Any => format!("{key}(any)"), Self::EnumVariant(s) => format!("{key}({s})"), Self::Number { number, comparison } => { - format!("{}({}{})", key, comparison.to_string(), number) + format!("{}({}{})", key, comparison, number) } } } @@ -104,9 +109,9 @@ struct Atom { value: ValueType, } -impl ToString for Atom { - fn to_string(&self) -> String { - self.value.to_string(&self.key) +impl Display for Atom { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.value.to_string(&self.key)) } } @@ -317,15 +322,14 @@ impl Parse for Scope { } } -impl ToString for Scope { - fn to_string(&self) -> String { +impl Display for Scope { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - Self::Crate => "crate".to_string(), - Self::Extern => "euclid".to_string(), + Self::Crate => write!(f, "crate"), + Self::Extern => write!(f, "euclid"), } } } - #[derive(Clone)] struct Program { rules: Vec<Rc<Rule>>, diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 4920243bcc0..3668130608e 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -193,9 +193,7 @@ pub fn run_program(program: JsValue, input: JsValue) -> JsResult { #[wasm_bindgen(js_name = getAllConnectors)] pub fn get_all_connectors() -> JsResult { - Ok(serde_wasm_bindgen::to_value( - common_enums::RoutableConnectors::VARIANTS, - )?) + Ok(serde_wasm_bindgen::to_value(RoutableConnectors::VARIANTS)?) } #[wasm_bindgen(js_name = getAllKeys)] diff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs index 912ddc67058..180f733cfeb 100644 --- a/crates/hyperswitch_domain_models/src/mandates.rs +++ b/crates/hyperswitch_domain_models/src/mandates.rs @@ -169,8 +169,7 @@ impl CustomerAcceptance { } pub fn get_accepted_at(&self) -> PrimitiveDateTime { - self.accepted_at - .unwrap_or_else(common_utils::date_time::now) + self.accepted_at.unwrap_or_else(date_time::now) } } diff --git a/crates/masking/src/diesel.rs b/crates/masking/src/diesel.rs index f3576298bdb..ea60a861c9d 100644 --- a/crates/masking/src/diesel.rs +++ b/crates/masking/src/diesel.rs @@ -52,7 +52,7 @@ where S: FromSql<T, DB>, I: Strategy<S>, { - fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { S::from_sql(bytes).map(|raw| raw.into()) } } @@ -122,7 +122,7 @@ where S: FromSql<T, DB> + ZeroizableSecret, I: Strategy<S>, { - fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { S::from_sql(bytes).map(|raw| raw.into()) } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 1e384408397..7abbc3b77e4 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -514,6 +514,8 @@ Never share your secret api keys. Keep them guarded and secure. )), modifiers(&SecurityAddon) )] +// Bypass clippy lint for not being constructed +#[allow(dead_code)] pub struct ApiDoc; struct SecurityAddon; diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs index 51fd796072b..d5c66b9c64a 100644 --- a/crates/pm_auth/src/types.rs +++ b/crates/pm_auth/src/types.rs @@ -110,12 +110,12 @@ pub type BankDetailsRouterData = PaymentAuthRouterData< >; pub type PaymentAuthLinkTokenType = - dyn self::api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; + dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; pub type PaymentAuthExchangeTokenType = - dyn self::api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; + dyn api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; -pub type PaymentAuthBankAccountDetailsType = dyn self::api::ConnectorIntegration< +pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration< BankAccountCredentials, BankAccountCredentialsRequest, BankAccountCredentialsResponse, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index d509cf03d3c..8eb94a29124 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -114,7 +114,7 @@ pub mod routes { pub async fn get_info( state: web::Data<AppState>, req: actix_web::HttpRequest, - domain: actix_web::web::Path<analytics::AnalyticsDomain>, + domain: web::Path<analytics::AnalyticsDomain>, ) -> impl Responder { let flow = AnalyticsFlow::GetInfo; Box::pin(api::server_wrap( @@ -631,7 +631,7 @@ pub mod routes { state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Json<GetSearchRequest>, - index: actix_web::web::Path<SearchIndex>, + index: web::Path<SearchIndex>, ) -> impl Responder { let flow = AnalyticsFlow::GetSearchResults; let indexed_req = GetSearchRequestWithIndex { diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 47f41d8700f..5341a1b09c1 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -40,7 +40,7 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { conf.proxy.clone(), services::proxy_bypass_urls(&conf.locker), ) - .change_context(errors::ProcessTrackerError::ConfigurationError)?, + .change_context(ProcessTrackerError::ConfigurationError)?, ); // channel for listening to redis disconnect events let (redis_shutdown_signal_tx, redis_shutdown_signal_rx) = oneshot::channel(); @@ -320,7 +320,7 @@ async fn start_scheduler( .conf .scheduler .clone() - .ok_or(errors::ProcessTrackerError::ConfigurationError)?; + .ok_or(ProcessTrackerError::ConfigurationError)?; scheduler::start_process_tracker( state, scheduler_flow, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index eed80a1128e..3d5264ddbed 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -649,7 +649,7 @@ fn from_timestamp_to_datetime( } })?; - Ok(Some(time::PrimitiveDateTime::new(time.date(), time.time()))) + Ok(Some(PrimitiveDateTime::new(time.date(), time.time()))) } else { Ok(None) } @@ -744,7 +744,7 @@ impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments:: }, ))), }, - None => Some(api_models::payments::MandateType::MultiUse(Some( + None => Some(payments::MandateType::MultiUse(Some( payments::MandateAmountData { amount: mandate.amount.unwrap_or_default(), currency, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index adc09fb55af..5b55ca8b0e3 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -200,7 +200,7 @@ pub struct ApplepayMerchantConfigs { #[derive(Debug, Deserialize, Clone, Default)] pub struct MultipleApiVersionSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] - pub supported_connectors: HashSet<api_models::enums::Connector>, + pub supported_connectors: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -214,10 +214,10 @@ pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMet #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorCustomer { #[serde(deserialize_with = "deserialize_hashset")] - pub connector_list: HashSet<api_models::enums::Connector>, + pub connector_list: HashSet<enums::Connector>, #[cfg(feature = "payouts")] #[serde(deserialize_with = "deserialize_hashset")] - pub payout_connector_list: HashSet<api_models::enums::PayoutConnectors>, + pub payout_connector_list: HashSet<enums::PayoutConnectors>, } #[cfg(feature = "dummy_connector")] @@ -263,7 +263,7 @@ pub struct Mandates { #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTransactionIdSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] - pub connector_list: HashSet<api_models::enums::Connector>, + pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone)] @@ -279,7 +279,7 @@ pub struct SupportedPaymentMethodTypesForMandate( #[derive(Debug, Deserialize, Clone)] pub struct SupportedConnectorsForMandate { #[serde(deserialize_with = "deserialize_hashset")] - pub connector_list: HashSet<api_models::enums::Connector>, + pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -322,9 +322,7 @@ pub enum PaymentMethodTypeTokenFilter { } #[derive(Debug, Deserialize, Clone, Default)] -pub struct BankRedirectConfig( - pub HashMap<api_models::enums::PaymentMethodType, ConnectorBankNames>, -); +pub struct BankRedirectConfig(pub HashMap<enums::PaymentMethodType, ConnectorBankNames>); #[derive(Debug, Deserialize, Clone)] pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); @@ -345,17 +343,17 @@ pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCoun #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(untagged)] pub enum PaymentMethodFilterKey { - PaymentMethodType(api_models::enums::PaymentMethodType), - CardNetwork(api_models::enums::CardNetwork), + PaymentMethodType(enums::PaymentMethodType), + CardNetwork(enums::CardNetwork), } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { #[serde(deserialize_with = "deserialize_optional_hashset")] - pub currency: Option<HashSet<api_models::enums::Currency>>, + pub currency: Option<HashSet<enums::Currency>>, #[serde(deserialize_with = "deserialize_optional_hashset")] - pub country: Option<HashSet<api_models::enums::CountryAlpha2>>, + pub country: Option<HashSet<enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } @@ -628,13 +626,13 @@ pub struct ApiKeys { #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deserialize_hashset")] - pub connectors_with_delayed_session_response: HashSet<api_models::enums::Connector>, + pub connectors_with_delayed_session_response: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct WebhookSourceVerificationCall { #[serde(deserialize_with = "deserialize_hashset")] - pub connectors_with_webhook_source_verification_call: HashSet<api_models::enums::Connector>, + pub connectors_with_webhook_source_verification_call: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 23288e3819d..9353b848bdb 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -22,20 +22,13 @@ pub struct AciRouterData<T> { router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for AciRouterData<T> -{ +impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for AciRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, item): ( &types::api::CurrencyUnit, - types::storage::enums::Currency, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 6dfe899f2d1..77abaacf40b 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1720,7 +1720,7 @@ fn get_amount_data(item: &AdyenRouterData<&types::PaymentsAuthorizeRouterData>) } fn get_address_info( - address: Option<&api_models::payments::Address>, + address: Option<&payments::Address>, ) -> Option<Result<Address, error_stack::Report<errors::ConnectorError>>> { address.and_then(|add| { add.address.as_ref().map( @@ -1783,7 +1783,7 @@ fn get_telephone_number(item: &types::PaymentsAuthorizeRouterData) -> Option<Sec }) } -fn get_shopper_name(address: Option<&api_models::payments::Address>) -> Option<ShopperName> { +fn get_shopper_name(address: Option<&payments::Address>) -> Option<ShopperName> { let billing = address.and_then(|billing| billing.address.as_ref()); Some(ShopperName { first_name: billing.and_then(|a| a.first_name.clone()), @@ -1791,9 +1791,7 @@ fn get_shopper_name(address: Option<&api_models::payments::Address>) -> Option<S }) } -fn get_country_code( - address: Option<&api_models::payments::Address>, -) -> Option<api_enums::CountryAlpha2> { +fn get_country_code(address: Option<&payments::Address>) -> Option<api_enums::CountryAlpha2> { address.and_then(|billing| billing.address.as_ref().and_then(|address| address.country)) } diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index 91a27fc3df0..bdd842bf958 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -223,7 +223,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -312,7 +312,7 @@ impl event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -442,7 +442,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -523,7 +523,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -614,7 +614,7 @@ impl .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -703,7 +703,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -779,7 +779,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -892,7 +892,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon .change_context(errors::ConnectorError::RequestEncodingFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -965,7 +965,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::try_from(types::ResponseRouterData { + RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index e80909d7e01..fe0cd021ebc 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -59,20 +59,13 @@ pub struct AirwallexRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for AirwallexRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for AirwallexRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, router_data): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, + &api::CurrencyUnit, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 7f9cdc376e1..2ca78e630fa 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -39,8 +39,7 @@ where &self, _req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError> - { + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index a072fcf3214..ca8b13298b0 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -46,22 +46,10 @@ pub struct AuthorizedotnetRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for AuthorizedotnetRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for AuthorizedotnetRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index dbb655c6ca0..77c91af709d 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -20,22 +20,10 @@ pub struct BamboraRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for BamboraRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BamboraRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = crate::connector::utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index 0c01facf386..e5ddd3743b9 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -120,8 +120,7 @@ where &self, req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError> - { + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let date = OffsetDateTime::now_utc(); let boa_req = self.get_request_body(req, connectors)?; let http_method = self.get_http_method(); diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index efece7f61fb..2d7b2307039 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -58,22 +58,10 @@ pub struct BankOfAmericaRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for BankOfAmericaRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BankOfAmericaRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; Ok(Self { @@ -602,7 +590,7 @@ impl merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: None, original_authorized_amount: Some(utils::get_amount_as_string( - &types::api::CurrencyUnit::Base, + &api::CurrencyUnit::Base, original_amount, original_currency, )?), diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs index 4e91a2c9ffb..3e5e53286e3 100644 --- a/crates/router/src/connector/billwerk/transformers.rs +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -14,22 +14,10 @@ pub struct BillwerkRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for BillwerkRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BillwerkRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index 74fa0b5c595..a70c4ba3ac2 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -15,20 +15,13 @@ pub struct BitpayRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for BitpayRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BitpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, router_data): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, + &api::CurrencyUnit, + enums::Currency, i64, T, ), @@ -81,7 +74,7 @@ impl TryFrom<&ConnectorAuthType> for BitpayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 2a572a2231a..0630fef2748 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -36,22 +36,10 @@ pub struct BluesnapRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for BluesnapRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BluesnapRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; Ok(Self { @@ -150,7 +138,7 @@ pub struct BluesnapGooglePayObject { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapApplePayObject { - token: api_models::payments::ApplePayWalletData, + token: payments::ApplePayWalletData, } #[derive(Debug, Serialize)] @@ -447,23 +435,19 @@ impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken { let apple_pay_metadata = item.get_connector_meta()?.expose(); let applepay_metadata = apple_pay_metadata .clone() - .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( + .parse_value::<payments::ApplepayCombinedSessionTokenData>( "ApplepayCombinedSessionTokenData", ) .map(|combined_metadata| { - api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( + payments::ApplepaySessionTokenMetadata::ApplePayCombined( combined_metadata.apple_pay_combined, ) }) .or_else(|_| { apple_pay_metadata - .parse_value::<api_models::payments::ApplepaySessionTokenData>( - "ApplepaySessionTokenData", - ) + .parse_value::<payments::ApplepaySessionTokenData>("ApplepaySessionTokenData") .map(|old_metadata| { - api_models::payments::ApplepaySessionTokenMetadata::ApplePay( - old_metadata.apple_pay, - ) + payments::ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay) }) }) .change_context(errors::ConnectorError::ParsingFailed)?; @@ -500,31 +484,26 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons .decode(response.wallet_token.clone().expose()) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; - let session_response: api_models::payments::NoThirdPartySdkSessionResponse = - wallet_token[..] - .parse_struct("NoThirdPartySdkSessionResponse") - .change_context(errors::ConnectorError::ParsingFailed)?; + let session_response: payments::NoThirdPartySdkSessionResponse = wallet_token + .parse_struct("NoThirdPartySdkSessionResponse") + .change_context(errors::ConnectorError::ParsingFailed)?; let metadata = item.data.get_connector_meta()?.expose(); let applepay_metadata = metadata .clone() - .parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>( + .parse_value::<payments::ApplepayCombinedSessionTokenData>( "ApplepayCombinedSessionTokenData", ) .map(|combined_metadata| { - api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( + payments::ApplepaySessionTokenMetadata::ApplePayCombined( combined_metadata.apple_pay_combined, ) }) .or_else(|_| { metadata - .parse_value::<api_models::payments::ApplepaySessionTokenData>( - "ApplepaySessionTokenData", - ) + .parse_value::<payments::ApplepaySessionTokenData>("ApplepaySessionTokenData") .map(|old_metadata| { - api_models::payments::ApplepaySessionTokenMetadata::ApplePay( - old_metadata.apple_pay, - ) + payments::ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay) }) }) .change_context(errors::ConnectorError::ParsingFailed)?; @@ -543,16 +522,15 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons Ok(Self { response: Ok(types::PaymentsResponseData::SessionResponse { - session_token: types::api::SessionToken::ApplePay(Box::new( - api_models::payments::ApplepaySessionTokenResponse { - session_token_data: - api_models::payments::ApplePaySessionResponse::NoThirdPartySdk( - session_response, - ), - payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { + session_token: api::SessionToken::ApplePay(Box::new( + payments::ApplepaySessionTokenResponse { + session_token_data: payments::ApplePaySessionResponse::NoThirdPartySdk( + session_response, + ), + payment_request_data: Some(payments::ApplePayPaymentRequest { country_code: item.data.get_billing_country()?, currency_code: item.data.request.currency, - total: api_models::payments::AmountInfo { + total: payments::AmountInfo { label: payment_request_data.label, total_type: Some("final".to_string()), amount: item.data.request.amount.to_string(), diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index 07b48a5353c..c22b6567732 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -295,7 +295,7 @@ fn get_authorize_response( let redirection_data = match response.hosted { Some(hosted_value) => Ok(hosted_value .redirect_url - .map(|url| services::RedirectForm::from((url, services::Method::Get)))), + .map(|url| RedirectForm::from((url, services::Method::Get)))), None => Err(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "redirect_url", }), diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 1b55f12cab1..f7e142a9af9 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -1467,10 +1467,8 @@ impl api::IncomingWebhook for Braintree { match response.dispute { Some(dispute_data) => { - let currency = diesel_models::enums::Currency::from_str( - dispute_data.currency_iso_code.as_str(), - ) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let currency = enums::Currency::from_str(dispute_data.currency_iso_code.as_str()) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(api::disputes::DisputePayload { amount: connector_utils::to_currency_lower_unit( dispute_data.amount_disputed.to_string(), diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index 480867c6cbd..bd860e72900 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -27,22 +27,10 @@ pub struct BraintreeRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for BraintreeRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BraintreeRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; Ok(Self { @@ -80,7 +68,7 @@ pub enum BraintreePaymentsRequest { #[derive(Debug, Deserialize)] pub struct BraintreeMeta { merchant_account_id: Secret<String>, - merchant_config_currency: types::storage::enums::Currency, + merchant_config_currency: enums::Currency, } impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta { diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index ef111a2588a..e278ff40b43 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -21,7 +21,7 @@ pub struct PaymentOptions { #[derive(Debug, Deserialize)] pub struct BraintreeMeta { merchant_account_id: Option<Secret<String>>, - merchant_config_currency: Option<types::storage::enums::Currency>, + merchant_config_currency: Option<enums::Currency>, } #[derive(Debug, Serialize, Eq, PartialEq)] @@ -304,7 +304,7 @@ impl<F, T> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PaymentsResponseData::SessionResponse { - session_token: types::api::SessionToken::Paypal(Box::new( + session_token: api::SessionToken::Paypal(Box::new( payments::PaypalSessionTokenResponse { session_token: item.response.client_token.value.expose(), }, diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs index 525b19df001..f8c275df33b 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/router/src/connector/cashtocode/transformers.rs @@ -203,13 +203,13 @@ fn get_redirect_form_data( enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form { //redirect form is manually constructed because the connector for this pm type expects query params in the url endpoint: response_data.pay_url.to_string(), - method: services::Method::Post, + method: Method::Post, form_fields: Default::default(), }), enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from(( //here the pay url gets parsed, and query params are sent as formfields as the connector expects response_data.pay_url, - services::Method::Get, + Method::Get, ))), _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("CashToCode"), diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 3fff6d940d6..cc937c0ef60 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -23,22 +23,10 @@ pub struct CheckoutRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for CheckoutRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for CheckoutRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs index 8bfbe8b695a..497cf81918e 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/router/src/connector/coinbase.rs @@ -52,8 +52,7 @@ where &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError> - { + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index b8f398a0d96..baea07faa60 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -19,19 +19,12 @@ pub struct CryptopayRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for CryptopayRouterData<T> -{ +impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for CryptopayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, item): ( &types::api::CurrencyUnit, - types::storage::enums::Currency, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index d93a9405ae3..1a85498ad06 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -233,8 +233,7 @@ where &self, req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError> - { + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let date = OffsetDateTime::now_utc(); let cybersource_req = self.get_request_body(req, connectors)?; let auth = cybersource::CybersourceAuthType::try_from(&req.connector_auth_type)?; @@ -740,8 +739,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError> - { + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -837,12 +835,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P { Ok(format!( "{}risk/v1/authentication-setups", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } else { Ok(format!( "{}pts/v2/payments/", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } } @@ -1111,7 +1109,7 @@ impl ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}pts/v2/payments/", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8251de8ca31..545ee672ed9 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -38,22 +38,10 @@ pub struct CybersourceRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for CybersourceRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for CybersourceRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { // This conversion function is used at different places in the file, if updating this, keep a check for those let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; @@ -570,7 +558,7 @@ impl .clone() .and_then(|mandate_id| mandate_id.mandate_reference_id) { - Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) => { + Some(payments::MandateReferenceId::ConnectorMandateId(_)) => { let original_amount = item .router_data .get_recurring_mandate_payment_data()? @@ -587,7 +575,7 @@ impl merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { reason: None, original_authorized_amount: Some(utils::get_amount_as_string( - &types::api::CurrencyUnit::Base, + &api::CurrencyUnit::Base, original_amount, original_currency, )?), @@ -596,9 +584,7 @@ impl }), ) } - Some(api_models::payments::MandateReferenceId::NetworkMandateId( - network_transaction_id, - )) => { + Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { let (original_amount, original_currency) = match network .clone() .map(|network| network.to_lowercase()) diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs index c92c6b8b854..dc99619e9da 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/router/src/connector/dlocal.rs @@ -56,8 +56,7 @@ where &self, req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, services::request::Maskable<String>)>, errors::ConnectorError> - { + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let dlocal_req = self.get_request_body(req, connectors)?; let date = date_time::date_as_yyyymmddthhmmssmmmz() diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 14337ca0765..c073dc03cc9 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -57,20 +57,13 @@ pub struct DlocalRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for DlocalRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, router_data): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, + &api::CurrencyUnit, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index fcb808c6700..3d40876c353 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -18,20 +18,13 @@ pub struct FiservRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for FiservRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for FiservRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, router_data): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, + &api::CurrencyUnit, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index cfb822715bf..478da2cf902 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -269,7 +269,7 @@ impl<F, T> }) .transpose()?; let redirection_data = - redirect_url.map(|url| services::RedirectForm::from((url, services::Method::Get))); + redirect_url.map(|url| RedirectForm::from((url, services::Method::Get))); Ok(Self { status, response: get_payment_response(status, item.response, redirection_data), @@ -434,8 +434,8 @@ fn get_mandate_details(item: &types::PaymentsAuthorizeRouterData) -> Result<Mand Some(StoredCredential { model: Some(requests::Model::Recurring), sequence: Some(match connector_mandate_id.is_some() { - true => requests::Sequence::Subsequent, - false => requests::Sequence::First, + true => Sequence::Subsequent, + false => Sequence::First, }), }), connector_mandate_id, diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index 59177307f22..e05f1b469ac 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -24,22 +24,10 @@ pub struct GocardlessRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for GocardlessRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for GocardlessRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, @@ -736,7 +724,7 @@ impl<F> Ok(Self { status: enums::AttemptStatus::from(item.response.payments.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.payments.id), + resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id), redirection_data: None, mandate_reference: Some(mandate_reference), connector_metadata: None, @@ -771,7 +759,7 @@ impl<F> Ok(Self { status: enums::AttemptStatus::from(item.response.payments.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.payments.id), + resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id), redirection_data: None, mandate_reference: None, connector_metadata: None, diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index 2dc44c8a19b..655d8a8663b 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -19,22 +19,10 @@ pub struct HelcimRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for HelcimRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for HelcimRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { @@ -45,9 +33,9 @@ impl<T> } pub fn check_currency( - currency: types::storage::enums::Currency, -) -> Result<types::storage::enums::Currency, errors::ConnectorError> { - if currency == types::storage::enums::Currency::USD { + currency: enums::Currency, +) -> Result<enums::Currency, errors::ConnectorError> { + if currency == enums::Currency::USD { Ok(currency) } else { Err(errors::ConnectorError::NotSupported { diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 8e45b96e69c..bce25a76429 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -37,22 +37,10 @@ pub struct IatapayRouterData<T> { amount: f64, router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for IatapayRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for IatapayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount: connector_util::get_amount_as_f64(currency_unit, amount, currency)?, @@ -114,7 +102,7 @@ impl TryFrom< &IatapayRouterData< &types::RouterData< - types::api::payments::Authorize, + api::payments::Authorize, PaymentsAuthorizeData, types::PaymentsResponseData, >, @@ -126,7 +114,7 @@ impl fn try_from( item: &IatapayRouterData< &types::RouterData< - types::api::payments::Authorize, + api::payments::Authorize, PaymentsAuthorizeData, types::PaymentsResponseData, >, diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 29dccfbf32b..db77b9c30cd 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -14,20 +14,13 @@ pub struct KlarnaRouterData<T> { router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for KlarnaRouterData<T> -{ +impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for KlarnaRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, router_data): ( &types::api::CurrencyUnit, - types::storage::enums::Currency, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 850bd058e41..f993928d94f 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -20,23 +20,11 @@ pub struct MultisafepayRouterData<T> { router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for MultisafepayRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for MultisafepayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, @@ -677,9 +665,8 @@ impl<F, T> MultisafepayPaymentStatus::Declined }; - let status = enums::AttemptStatus::from( - payment_response.data.status.unwrap_or(default_status), - ); + let status = + AttemptStatus::from(payment_response.data.status.unwrap_or(default_status)); Ok(Self { status, diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index 7c95578bfd6..4bf61ce1ca4 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -16,18 +16,13 @@ pub struct NetceteraRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for NetceteraRouterData<T> +impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> + for NetceteraRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, + &api::CurrencyUnit, types::storage::enums::Currency, i64, T, diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs index 1370fcf11cd..88aa149a267 100644 --- a/crates/router/src/connector/nexinets.rs +++ b/crates/router/src/connector/nexinets.rs @@ -120,7 +120,7 @@ impl ConnectorCommon for Nexinets { if !field.is_empty() { msg.push_str(format!("{} : {}", field, error.message).as_str()); } else { - msg = error.message.to_owned(); + error.message.clone_into(&mut msg) } if message.is_empty() { message.push_str(&msg); diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index ea61782d498..fdc65963fe8 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -42,11 +42,11 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), public_key: None, }), - types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), public_key: Some(key1.to_owned()), }), @@ -61,20 +61,13 @@ pub struct NmiRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for NmiRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for NmiRouterData<T> { type Error = Report<errors::ConnectorError>; fn try_from( (_currency_unit, currency, amount, router_data): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, + &api::CurrencyUnit, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index aa4157a68d8..d08820266c3 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -161,7 +161,7 @@ impl ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/payment.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( @@ -248,7 +248,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/voidTransaction.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } @@ -334,7 +334,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/getPaymentStatus.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } @@ -417,7 +417,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/settleTransaction.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } @@ -509,7 +509,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/payment.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } @@ -671,7 +671,7 @@ impl ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/getSessionToken.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } @@ -756,7 +756,7 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/initPayment.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } @@ -839,7 +839,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/refundTransaction.do", - api::ConnectorCommon::base_url(self, connectors) + ConnectorCommon::base_url(self, connectors) )) } @@ -954,7 +954,7 @@ impl api::IncomingWebhook for Nuvei { serde_urlencoded::from_str::<nuvei::NuveiWebhookTransactionId>(&request.query_params) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - types::api::PaymentIdType::ConnectorTransactionId(body.ppp_transaction_id), + api::PaymentIdType::ConnectorTransactionId(body.ppp_transaction_id), )) } diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs index 3267caf60d6..09da5fc8f94 100644 --- a/crates/router/src/connector/opennode/transformers.rs +++ b/crates/router/src/connector/opennode/transformers.rs @@ -16,20 +16,13 @@ pub struct OpennodeRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for OpennodeRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for OpennodeRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, router_data): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, + &api::CurrencyUnit, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 0ceed1390be..a8442f7ea8a 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -15,20 +15,13 @@ pub struct PayeezyRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for PayeezyRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for PayeezyRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, router_data): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, + &api::CurrencyUnit, + enums::Currency, i64, T, ), diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 7f5e30402d6..0b3f4fb48ce 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -29,22 +29,10 @@ pub struct PaymeRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for PaymeRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for PaymeRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, @@ -630,7 +618,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(req_card) => { + PaymentMethodData::Card(req_card) => { let card = PaymeCard { credit_card_cvv: req_card.card_cvc.clone(), credit_card_exp: req_card @@ -652,23 +640,21 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { language: LANGUAGE.to_string(), }) } - domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("payme"), - ))? - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("payme"), + ))?, } } } @@ -681,7 +667,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { - Some(domain::PaymentMethodData::Card(_)) => { + Some(PaymentMethodData::Card(_)) => { let buyer_email = item.request.get_email()?; let buyer_name = item.get_billing_address()?.get_full_name()?; @@ -712,19 +698,19 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { meta_data_jwt: Secret::new(jwt_data.meta_data), }) } - Some(domain::PaymentMethodData::CardRedirect(_)) - | Some(domain::PaymentMethodData::Wallet(_)) - | Some(domain::PaymentMethodData::PayLater(_)) - | Some(domain::PaymentMethodData::BankRedirect(_)) - | Some(domain::PaymentMethodData::BankDebit(_)) - | Some(domain::PaymentMethodData::BankTransfer(_)) - | Some(domain::PaymentMethodData::Crypto(_)) - | Some(domain::PaymentMethodData::MandatePayment) - | Some(domain::PaymentMethodData::Reward) - | Some(domain::PaymentMethodData::Upi(_)) - | Some(domain::PaymentMethodData::Voucher(_)) - | Some(domain::PaymentMethodData::GiftCard(_)) - | Some(domain::PaymentMethodData::CardToken(_)) + Some(PaymentMethodData::CardRedirect(_)) + | Some(PaymentMethodData::Wallet(_)) + | Some(PaymentMethodData::PayLater(_)) + | Some(PaymentMethodData::BankRedirect(_)) + | Some(PaymentMethodData::BankDebit(_)) + | Some(PaymentMethodData::BankTransfer(_)) + | Some(PaymentMethodData::Crypto(_)) + | Some(PaymentMethodData::MandatePayment) + | Some(PaymentMethodData::Reward) + | Some(PaymentMethodData::Upi(_)) + | Some(PaymentMethodData::Voucher(_)) + | Some(PaymentMethodData::GiftCard(_)) + | Some(PaymentMethodData::CardToken(_)) | None => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } @@ -736,7 +722,7 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> { match item.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(req_card) => { + PaymentMethodData::Card(req_card) => { let seller_payme_id = PaymeAuthType::try_from(&item.connector_auth_type)?.seller_payme_id; let card = PaymeCard { @@ -750,19 +736,19 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest { seller_payme_id, }) } - domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::CardToken(_) => { + PaymentMethodData::Wallet(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } } @@ -1151,14 +1137,14 @@ impl<F, T> fn get_services(item: &types::PaymentsPreProcessingRouterData) -> Option<ThreeDs> { match item.auth_type { - api_models::enums::AuthenticationType::ThreeDs => { + AuthenticationType::ThreeDs => { let settings = ThreeDsSettings { active: true }; Some(ThreeDs { name: ThreeDsType::ThreeDs, settings, }) } - api_models::enums::AuthenticationType::NoThreeDs => None, + AuthenticationType::NoThreeDs => None, } } diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 63912391787..cf81fec6341 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -960,8 +960,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe ) -> CustomResult<String, errors::ConnectorError> { let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; match req.payment_method { - diesel_models::enums::PaymentMethod::Wallet - | diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!( + enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => Ok(format!( "{}v2/checkout/orders/{}", self.base_url(connectors), req.request @@ -1633,9 +1632,9 @@ impl services::ConnectorRedirectResponse for Paypal { action: PaymentAction, ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { match action { - services::PaymentAction::PSync - | services::PaymentAction::CompleteAuthorize - | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { + PaymentAction::PSync + | PaymentAction::CompleteAuthorize + | PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(payments::CallConnectorAction::Trigger) } } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 21b0f04af86..338b8c5ba4e 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -29,18 +29,13 @@ pub struct PaypalRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for PaypalRouterData<T> +impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> + for PaypalRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, + &api::CurrencyUnit, types::storage::enums::Currency, i64, T, @@ -153,7 +148,7 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ItemDetail pub struct Address { address_line_1: Option<Secret<String>>, postal_code: Option<Secret<String>>, - country_code: api_models::enums::CountryAlpha2, + country_code: enums::CountryAlpha2, admin_area_2: Option<String>, } @@ -216,7 +211,7 @@ pub enum ThreeDsType { #[derive(Debug, Serialize)] pub struct RedirectRequest { name: Secret<String>, - country_code: api_models::enums::CountryAlpha2, + country_code: enums::CountryAlpha2, experience_context: ContextStruct, } @@ -454,12 +449,12 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP let expiry = Some(card.get_expiry_date_as_yyyymm("-")); let attributes = match item.router_data.auth_type { - api_models::enums::AuthenticationType::ThreeDs => Some(ThreeDsSetting { + enums::AuthenticationType::ThreeDs => Some(ThreeDsSetting { verification: ThreeDsMethod { method: ThreeDsType::ScaAlways, }, }), - api_models::enums::AuthenticationType::NoThreeDs => None, + enums::AuthenticationType::NoThreeDs => None, }; let payment_source = Some(PaymentSourceItem::Card(CardRequest { @@ -858,13 +853,13 @@ impl TryFrom<&ConnectorAuthType> for PaypalAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails( + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::AuthWithDetails( PaypalConnectorCredentials::StandardIntegration(StandardFlowCredentials { client_id: key1.to_owned(), client_secret: api_key.to_owned(), }), )), - types::ConnectorAuthType::SignatureKey { + ConnectorAuthType::SignatureKey { api_key, key1, api_secret, @@ -875,7 +870,7 @@ impl TryFrom<&ConnectorAuthType> for PaypalAuthType { payer_id: api_secret.to_owned(), }), )), - types::ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth), + ConnectorAuthType::TemporaryAuth => Ok(Self::TemporaryAuth), _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, } } @@ -1216,7 +1211,7 @@ fn get_redirect_url( let mut link: Option<Url> = None; for item2 in link_vec.iter() { if item2.rel == "payer-action" { - link = item2.href.clone(); + link.clone_from(&item2.href) } } Ok(link) diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index 6ad3d3c2039..e400dc9b399 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -20,18 +20,13 @@ pub struct PlacetopayRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for PlacetopayRouterData<T> +impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> + for PlacetopayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, + &api::CurrencyUnit, types::storage::enums::Currency, i64, T, diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs index 570bf8d2b3a..7a8cd6e14d0 100644 --- a/crates/router/src/connector/prophetpay/transformers.rs +++ b/crates/router/src/connector/prophetpay/transformers.rs @@ -19,22 +19,10 @@ pub struct ProphetpayRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for ProphetpayRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ProphetpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { @@ -229,7 +217,7 @@ fn get_redirect_url_form( mut redirect_url: Url, complete_auth_url: Option<String>, ) -> CustomResult<services::RedirectForm, errors::ConnectorError> { - let mut form_fields = std::collections::HashMap::<String, String>::new(); + let mut form_fields = HashMap::<String, String>::new(); form_fields.insert( String::from("redirectUrl"), diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index c5f92c20f5c..5d4579fffa7 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -652,7 +652,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref } fn get_content_type(&self) -> &'static str { - api::ConnectorCommon::common_get_content_type(self) + ConnectorCommon::common_get_content_type(self) } fn get_url( diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 04dc4496b62..22e1074802d 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -19,22 +19,10 @@ pub struct RapydRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for RapydRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for RapydRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index e11a79cb027..e7487e795b6 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -217,8 +217,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P router_data: &mut types::PaymentsAuthorizeRouterData, app_state: &routes::AppState, ) -> CustomResult<(), errors::ConnectorError> { - if router_data.auth_type == diesel_models::enums::AuthenticationType::ThreeDs - && router_data.payment_method == diesel_models::enums::PaymentMethod::Card + if router_data.auth_type == enums::AuthenticationType::ThreeDs + && router_data.payment_method == enums::PaymentMethod::Card { let integ: Box< &(dyn ConnectorIntegration< diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 92a72f42d1e..30f327c700e 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -747,9 +747,9 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for Shift4RefundRequest { impl From<Shift4RefundStatus> for enums::RefundStatus { fn from(item: Shift4RefundStatus) -> Self { match item { - self::Shift4RefundStatus::Successful => Self::Success, - self::Shift4RefundStatus::Failed => Self::Failure, - self::Shift4RefundStatus::Processing => Self::Pending, + Shift4RefundStatus::Successful => Self::Success, + Shift4RefundStatus::Failed => Self::Failure, + Shift4RefundStatus::Processing => Self::Pending, } } } diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs index 550e1ae30a8..1c045b8da01 100644 --- a/crates/router/src/connector/signifyd.rs +++ b/crates/router/src/connector/signifyd.rs @@ -94,7 +94,7 @@ impl ConnectorCommon for Signifyd { Ok(ErrorResponse { status_code: res.status_code, - code: crate::consts::NO_ERROR_CODE.to_string(), + code: consts::NO_ERROR_CODE.to_string(), message: response.messages.join(" &"), reason: Some(response.errors.to_string()), attempt_status: None, diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 318e33978cc..c980a4e7494 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -5,10 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData}, core::errors, - types::{ - self, api, domain, - storage::{self, enums}, - }, + types::{self, api, domain, storage::enums}, unimplemented_payment_method, }; @@ -199,7 +196,7 @@ impl<F, T> item: types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - status: storage::enums::AttemptStatus::Pending, + status: enums::AttemptStatus::Pending, session_token: Some(item.response.session_id.clone().expose()), response: Ok(types::PaymentsResponseData::SessionTokenResponse { session_token: item.response.session_id.expose(), diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs index c923ca0577d..4604e9da872 100644 --- a/crates/router/src/connector/stax.rs +++ b/crates/router/src/connector/stax.rs @@ -869,29 +869,25 @@ impl api::IncomingWebhook for Stax { .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match webhook_body.transaction_type { - stax::StaxWebhookEventType::Refund => { - Ok(api_models::webhooks::ObjectReferenceId::RefundId( - api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.id), - )) - } - stax::StaxWebhookEventType::Unknown => { + StaxWebhookEventType::Refund => Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.id), + )), + StaxWebhookEventType::Unknown => { Err(errors::ConnectorError::WebhookEventTypeNotFound.into()) } - stax::StaxWebhookEventType::PreAuth - | stax::StaxWebhookEventType::Capture - | stax::StaxWebhookEventType::Charge - | stax::StaxWebhookEventType::Void => { - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId(match webhook_body - .transaction_type - { - stax::StaxWebhookEventType::Capture => webhook_body + StaxWebhookEventType::PreAuth + | StaxWebhookEventType::Capture + | StaxWebhookEventType::Charge + | StaxWebhookEventType::Void => Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + match webhook_body.transaction_type { + StaxWebhookEventType::Capture => webhook_body .auth_id .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, _ => webhook_body.id, - }), - )) - } + }, + ), + )), } } diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 1d097c40e7f..d48a2b1e82b 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -18,22 +18,10 @@ pub struct StaxRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for StaxRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for StaxRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?; Ok(Self { diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 64789e176fc..724a0ea6f78 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -2274,7 +2274,7 @@ impl services::ConnectorRedirectResponse for Stripe { _query_params: &str, _json_payload: Option<serde_json::Value>, action: services::PaymentAction, - ) -> CustomResult<crate::core::payments::CallConnectorAction, errors::ConnectorError> { + ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { match action { services::PaymentAction::PSync | services::PaymentAction::CompleteAuthorize diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 6932f6b7495..6b82c87b5d1 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1107,9 +1107,7 @@ impl TryFrom<(&domain::BankRedirectData, Option<bool>)> for StripeBillingAddress }, )?; Self { - name: Some(connector_util::BankRedirectBillingData::get_billing_name( - &billing_data, - )?), + name: Some(BankRedirectBillingData::get_billing_name(&billing_data)?), ..Self::default() } }), @@ -2859,16 +2857,14 @@ impl Serialize for StripeNextActionResponse { { match *self { Self::CashappHandleRedirectOrDisplayQrCode(ref i) => { - serde::Serialize::serialize(i, serializer) - } - Self::RedirectToUrl(ref i) => serde::Serialize::serialize(i, serializer), - Self::AlipayHandleRedirect(ref i) => serde::Serialize::serialize(i, serializer), - Self::VerifyWithMicrodeposits(ref i) => serde::Serialize::serialize(i, serializer), - Self::WechatPayDisplayQrCode(ref i) => serde::Serialize::serialize(i, serializer), - Self::DisplayBankTransferInstructions(ref i) => { - serde::Serialize::serialize(i, serializer) + Serialize::serialize(i, serializer) } - Self::NoNextActionBody => serde::Serialize::serialize("NoNextActionBody", serializer), + Self::RedirectToUrl(ref i) => Serialize::serialize(i, serializer), + Self::AlipayHandleRedirect(ref i) => Serialize::serialize(i, serializer), + Self::VerifyWithMicrodeposits(ref i) => Serialize::serialize(i, serializer), + Self::WechatPayDisplayQrCode(ref i) => Serialize::serialize(i, serializer), + Self::DisplayBankTransferInstructions(ref i) => Serialize::serialize(i, serializer), + Self::NoNextActionBody => Serialize::serialize("NoNextActionBody", serializer), } } } @@ -2984,10 +2980,10 @@ pub enum RefundStatus { impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { - self::RefundStatus::Succeeded => Self::Success, - self::RefundStatus::Failed => Self::Failure, - self::RefundStatus::Pending => Self::Pending, - self::RefundStatus::RequiresAction => Self::ManualReview, + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Pending => Self::Pending, + RefundStatus::RequiresAction => Self::ManualReview, } } } @@ -3382,12 +3378,12 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme code: item .response .failure_code - .unwrap_or_else(|| crate::consts::NO_ERROR_CODE.to_string()), + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: item .response .failure_message .clone() - .unwrap_or_else(|| crate::consts::NO_ERROR_MESSAGE.to_string()), + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: item.response.failure_message, status_code: item.http_code, attempt_status: Some(status), diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/router/src/connector/threedsecureio/transformers.rs index f0a2f116a40..d6a77fef31e 100644 --- a/crates/router/src/connector/threedsecureio/transformers.rs +++ b/crates/router/src/connector/threedsecureio/transformers.rs @@ -27,18 +27,13 @@ pub struct ThreedsecureioRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for ThreedsecureioRouterData<T> +impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> + for ThreedsecureioRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, + &api::CurrencyUnit, types::storage::enums::Currency, i64, T, @@ -168,7 +163,7 @@ impl let creq_str = to_string(&creq) .change_context(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("error while constructing creq_str")?; - let creq_base64 = base64::Engine::encode(&BASE64_ENGINE, creq_str) + let creq_base64 = Engine::encode(&BASE64_ENGINE, creq_str) .trim_end_matches('=') .to_owned(); Ok( @@ -270,7 +265,7 @@ impl TryFrom<&ThreedsecureioRouterData<&types::authentication::ConnectorAuthenti .map(|currency| currency.to_string()) .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("missing field currency")?; - let purchase_currency: Currency = iso_currency::Currency::from_code(&currency) + let purchase_currency: Currency = Currency::from_code(&currency) .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("error while parsing Currency")?; let billing_address = request.billing_address.address.clone().ok_or( diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index c40435c01bb..5a318e5e440 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -28,19 +28,12 @@ pub struct TrustpayRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for TrustpayRouterData<T> -{ +impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for TrustpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, amount, item): ( &types::api::CurrencyUnit, - types::storage::enums::Currency, + enums::Currency, i64, T, ), @@ -1179,7 +1172,7 @@ impl<F> let create_intent_response = item.response.init_result_data.to_owned(); let secrets = item.response.secrets.to_owned(); let instance_id = item.response.instance_id.to_owned(); - let pmt = utils::PaymentsPreProcessingData::get_payment_method_type(&item.data.request)?; + let pmt = PaymentsPreProcessingData::get_payment_method_type(&item.data.request)?; match (pmt, create_intent_response) { ( diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index 6ffe1f1ed7f..dfc7e61c000 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -5,10 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RefundsRequestData}, core::errors, - types::{ - self, api, domain, - storage::{self, enums}, - }, + types::{self, api, domain, storage::enums}, }; #[derive(Debug, Serialize)] @@ -25,7 +22,7 @@ pub struct TsysPaymentAuthSaleRequest { transaction_key: Secret<String>, card_data_source: String, transaction_amount: String, - currency_code: storage::enums::Currency, + currency_code: enums::Currency, card_number: cards::CardNumber, expiration_date: Secret<String>, cvv2: Secret<String>, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index bb52d4885fb..5a5b1242611 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -363,10 +363,7 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re } fn is_three_ds(&self) -> bool { - matches!( - self.auth_type, - diesel_models::enums::AuthenticationType::ThreeDs - ) + matches!(self.auth_type, enums::AuthenticationType::ThreeDs) } fn get_shipping_address(&self) -> Result<&api::AddressDetails, Error> { @@ -430,8 +427,8 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re pub trait PaymentsPreProcessingData { fn get_email(&self) -> Result<Email, Error>; - fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error>; - fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error>; + fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; + fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_amount(&self) -> Result<i64, Error>; fn is_auto_capture(&self) -> Result<bool, Error>; fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; @@ -445,12 +442,12 @@ impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } - fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error> { + fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } - fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error> { + fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_amount(&self) -> Result<i64, Error> { @@ -458,8 +455,8 @@ impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { } fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { - Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true), - Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false), + Some(enums::CaptureMethod::Automatic) | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } @@ -551,7 +548,7 @@ pub trait PaymentsAuthorizeRequestData { fn get_router_return_url(&self) -> Result<String, Error>; fn is_wallet(&self) -> bool; fn is_card(&self) -> bool; - fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error>; + fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; fn get_connector_mandate_id(&self) -> Result<String, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>; @@ -578,8 +575,8 @@ impl PaymentMethodTokenizationRequestData for types::PaymentMethodTokenizationDa impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { - Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true), - Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false), + Some(enums::CaptureMethod::Automatic) | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } @@ -619,9 +616,9 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { - Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - connector_mandate_ids, - )) => connector_mandate_ids.connector_mandate_id.clone(), + Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { + connector_mandate_ids.connector_mandate_id.clone() + } _ => None, }) } @@ -653,7 +650,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { matches!(self.payment_method_data, domain::PaymentMethodData::Card(_)) } - fn get_payment_method_type(&self) -> Result<diesel_models::enums::PaymentMethodType, Error> { + fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) @@ -797,8 +794,8 @@ pub trait PaymentsCompleteAuthorizeRequestData { impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { - Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true), - Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false), + Some(enums::CaptureMethod::Automatic) | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } @@ -831,8 +828,8 @@ pub trait PaymentsSyncRequestData { impl PaymentsSyncRequestData for types::PaymentsSyncData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { - Some(diesel_models::enums::CaptureMethod::Automatic) | None => Ok(true), - Some(diesel_models::enums::CaptureMethod::Manual) => Ok(false), + Some(enums::CaptureMethod::Automatic) | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } @@ -910,7 +907,7 @@ impl CustomerDetails for types::CustomerDetails { pub trait PaymentsCancelRequestData { fn get_amount(&self) -> Result<i64, Error>; - fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error>; + fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_cancellation_reason(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; } @@ -919,7 +916,7 @@ impl PaymentsCancelRequestData for PaymentsCancelData { fn get_amount(&self) -> Result<i64, Error> { self.amount.ok_or_else(missing_field_err("amount")) } - fn get_currency(&self) -> Result<diesel_models::enums::Currency, Error> { + fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_cancellation_reason(&self) -> Result<String, Error> { @@ -1540,7 +1537,7 @@ impl MandateData for payments::MandateAmountData { pub trait RecurringMandateData { fn get_original_payment_amount(&self) -> Result<i64, Error>; - fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error>; + fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>; } impl RecurringMandateData for RecurringMandatePaymentData { @@ -1548,7 +1545,7 @@ impl RecurringMandateData for RecurringMandatePaymentData { self.original_payment_authorized_amount .ok_or_else(missing_field_err("original_payment_authorized_amount")) } - fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error> { + fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> { self.original_payment_authorized_currency .ok_or_else(missing_field_err("original_payment_authorized_currency")) } @@ -1558,7 +1555,7 @@ pub trait MandateReferenceData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } -impl MandateReferenceData for api_models::payments::ConnectorMandateReferenceId { +impl MandateReferenceData for payments::ConnectorMandateReferenceId { fn get_connector_mandate_id(&self) -> Result<String, Error> { self.connector_mandate_id .clone() @@ -1645,7 +1642,7 @@ pub fn base64_decode(data: String) -> Result<Vec<u8>, Error> { pub fn to_currency_base_unit_from_optional_amount( amount: Option<i64>, - currency: diesel_models::enums::Currency, + currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { match amount { Some(a) => to_currency_base_unit(a, currency), @@ -1657,25 +1654,25 @@ pub fn to_currency_base_unit_from_optional_amount( } pub fn get_amount_as_string( - currency_unit: &types::api::CurrencyUnit, + currency_unit: &api::CurrencyUnit, amount: i64, - currency: diesel_models::enums::Currency, + currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let amount = match currency_unit { - types::api::CurrencyUnit::Minor => amount.to_string(), - types::api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?, + api::CurrencyUnit::Minor => amount.to_string(), + api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?, }; Ok(amount) } pub fn get_amount_as_f64( - currency_unit: &types::api::CurrencyUnit, + currency_unit: &api::CurrencyUnit, amount: i64, - currency: diesel_models::enums::Currency, + currency: enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { let amount = match currency_unit { - types::api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?, - types::api::CurrencyUnit::Minor => u32::try_from(amount) + api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?, + api::CurrencyUnit::Minor => u32::try_from(amount) .change_context(errors::ConnectorError::ParsingFailed)? .into(), }; @@ -1684,7 +1681,7 @@ pub fn get_amount_as_f64( pub fn to_currency_base_unit( amount: i64, - currency: diesel_models::enums::Currency, + currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit(amount) @@ -1693,7 +1690,7 @@ pub fn to_currency_base_unit( pub fn to_currency_lower_unit( amount: String, - currency: diesel_models::enums::Currency, + currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_lower_unit(amount) @@ -1721,7 +1718,7 @@ pub fn construct_not_supported_error_report( pub fn to_currency_base_unit_with_zero_decimal_check( amount: i64, - currency: diesel_models::enums::Currency, + currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit_with_zero_decimal_check(amount) @@ -1730,7 +1727,7 @@ pub fn to_currency_base_unit_with_zero_decimal_check( pub fn to_currency_base_unit_asf64( amount: i64, - currency: diesel_models::enums::Currency, + currency: enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit_asf64(amount) diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index d3913296c09..814eefaf5ff 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -18,18 +18,13 @@ pub struct VoltRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for VoltRouterData<T> +impl<T> TryFrom<(&api::CurrencyUnit, types::storage::enums::Currency, i64, T)> + for VoltRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, + &api::CurrencyUnit, types::storage::enums::Currency, i64, T, diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 3dba5ea24e7..795133f602f 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -190,22 +190,10 @@ pub struct WorldlineRouterData<T> { amount: i64, router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for WorldlineRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for WorldlineRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, @@ -218,7 +206,7 @@ impl TryFrom< &WorldlineRouterData< &types::RouterData< - types::api::payments::Authorize, + api::payments::Authorize, PaymentsAuthorizeData, PaymentsResponseData, >, @@ -230,7 +218,7 @@ impl fn try_from( item: &WorldlineRouterData< &types::RouterData< - types::api::payments::Authorize, + api::payments::Authorize, PaymentsAuthorizeData, PaymentsResponseData, >, @@ -593,7 +581,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData item.response.status, item.response.capture_method, )), - response: Ok(types::PaymentsResponseData::TransactionResponse { + response: Ok(PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, @@ -645,7 +633,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResp item.response.payment.status, item.response.payment.capture_method, )), - response: Ok(types::PaymentsResponseData::TransactionResponse { + response: Ok(PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.payment.id.clone(), ), diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 1f2dac807d1..894cfc16331 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -750,9 +750,7 @@ impl api::IncomingWebhook for Worldpay { .parse_struct("WorldpayWebhookTransactionId") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - types::api::PaymentIdType::ConnectorTransactionId( - body.event_details.transaction_reference, - ), + api::PaymentIdType::ConnectorTransactionId(body.event_details.transaction_reference), )) } diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 35a2f8cee8a..9c908cf749d 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -244,7 +244,7 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>> })?, }, description: item.response.description, - response: Ok(types::PaymentsResponseData::TransactionResponse { + response: Ok(PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::try_from(item.response.links)?, redirection_data: None, mandate_reference: None, diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index ead716af721..67538b819d5 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -23,22 +23,10 @@ pub struct ZenRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for ZenRouterData<T> -{ +impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for ZenRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (currency_unit, currency, amount, item): ( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - ), + (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; Ok(Self { diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs index 3ffd5b2ccef..58ff6ab2fab 100644 --- a/crates/router/src/connector/zsl/transformers.rs +++ b/crates/router/src/connector/zsl/transformers.rs @@ -27,19 +27,12 @@ pub struct ZslRouterData<T> { pub router_data: T, } -impl<T> - TryFrom<( - &types::api::CurrencyUnit, - types::storage::enums::Currency, - i64, - T, - )> for ZslRouterData<T> -{ +impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for ZslRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( (currency_unit, currency, txn_amount, item): ( &types::api::CurrencyUnit, - types::storage::enums::Currency, + enums::Currency, i64, T, ), diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 0b8d52332d9..ee06097a599 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -268,7 +268,7 @@ pub async fn create_merchant_account( .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?; - db.insert_config(diesel_models::configs::ConfigNew { + db.insert_config(configs::ConfigNew { key: format!("{}_requires_cvv", merchant_account.merchant_id), config: "true".to_string(), }) @@ -545,7 +545,7 @@ pub async fn merchant_account_update( let updated_merchant_account = storage::MerchantAccountUpdate::Update { merchant_name: req .merchant_name - .map(masking::Secret::new) + .map(Secret::new) .async_lift(|inner| domain_types::encrypt_optional(inner, key)) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -554,11 +554,11 @@ pub async fn merchant_account_update( merchant_details: req .merchant_details .as_ref() - .map(utils::Encode::encode_to_value) + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to convert merchant_details to a value")? - .map(masking::Secret::new) + .map(Secret::new) .async_lift(|inner| domain_types::encrypt_optional(inner, key)) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -569,7 +569,7 @@ pub async fn merchant_account_update( webhook_details: req .webhook_details .as_ref() - .map(utils::Encode::encode_to_value) + .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?, @@ -941,8 +941,8 @@ pub async fn create_payment_connector( business_country: req.business_country, business_label: req.business_label.clone(), business_sub_label: req.business_sub_label.clone(), - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), + created_at: date_time::now(), + modified_at: date_time::now(), id: None, connector_webhook_details: match req.connector_webhook_details { Some(connector_webhook_details) => { @@ -951,7 +951,7 @@ pub async fn create_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {}", merchant_id)) .map(Some)? - .map(masking::Secret::new) + .map(Secret::new) } None => None, }, @@ -1278,7 +1278,7 @@ pub async fn update_payment_connector( .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .map(Some)? - .map(masking::Secret::new), + .map(Secret::new), None => None, }, applepay_verified_domains: None, @@ -1458,7 +1458,7 @@ pub fn get_frm_config_as_secret( config .encode_to_value() .change_context(errors::ApiErrorResponse::ConfigNotFound) - .map(masking::Secret::new) + .map(Secret::new) }) .collect::<Result<Vec<_>, _>>() .ok()?; diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index f75ed011688..7f2b343b968 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -184,7 +184,7 @@ pub async fn add_api_key_expiry_task( api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { - let current_time = common_utils::date_time::now(); + let current_time = date_time::now(); let schedule_time = expiry_reminder_days .first() @@ -341,7 +341,7 @@ pub async fn update_api_key_expiry_task( api_key: &ApiKey, expiry_reminder_days: Vec<u8>, ) -> Result<(), errors::ProcessTrackerError> { - let current_time = common_utils::date_time::now(); + let current_time = date_time::now(); let schedule_time = expiry_reminder_days .first() diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs index 36ee3c20416..e2f605304a7 100644 --- a/crates/router/src/core/authentication.rs +++ b/crates/router/src/core/authentication.rs @@ -9,7 +9,7 @@ use common_utils::errors::CustomResult; use error_stack::ResultExt; use masking::ExposeInterface; -use super::errors::{self, StorageErrorExt}; +use super::errors::StorageErrorExt; use crate::{ core::{errors::ApiErrorResponse, payments as payments_core}, routes::AppState, @@ -23,10 +23,10 @@ pub async fn perform_authentication( authentication_connector: String, payment_method_data: payments::PaymentMethodData, payment_method: common_enums::PaymentMethod, - billing_address: api_models::payments::Address, - shipping_address: Option<api_models::payments::Address>, + billing_address: payments::Address, + shipping_address: Option<payments::Address>, browser_details: Option<core_types::BrowserInformation>, - business_profile: core_types::storage::BusinessProfile, + business_profile: storage::BusinessProfile, merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType, amount: Option<i64>, currency: Option<Currency>, @@ -35,10 +35,10 @@ pub async fn perform_authentication( authentication_data: storage::Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, - threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator, + threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, -) -> CustomResult<core_types::api::authentication::AuthenticationResponse, ApiErrorResponse> { +) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> { let router_data = transformers::construct_authentication_router_data( authentication_connector.clone(), payment_method_data, @@ -72,13 +72,13 @@ pub async fn perform_authentication( status_code: err.status_code, reason: err.reason, })?; - core_types::api::authentication::AuthenticationResponse::try_from(authentication) + api::authentication::AuthenticationResponse::try_from(authentication) } pub async fn perform_post_authentication( state: &AppState, key_store: &domain::MerchantKeyStore, - business_profile: core_types::storage::BusinessProfile, + business_profile: storage::BusinessProfile, authentication_id: String, ) -> CustomResult<storage::Authentication, ApiErrorResponse> { let (authentication_connector, three_ds_connector_account) = @@ -96,7 +96,7 @@ pub async fn perform_post_authentication( authentication_id.clone(), ) .await - .to_not_found_response(errors::ApiErrorResponse::InternalServerError) + .to_not_found_response(ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}"))?; if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled { let router_data = transformers::construct_post_authentication_router_data( @@ -119,7 +119,7 @@ pub async fn perform_pre_authentication( key_store: &domain::MerchantKeyStore, card_number: cards::CardNumber, token: String, - business_profile: &core_types::storage::BusinessProfile, + business_profile: &storage::BusinessProfile, acquirer_details: Option<types::AcquirerDetails>, payment_id: Option<String>, ) -> CustomResult<storage::Authentication, ApiErrorResponse> { @@ -135,7 +135,7 @@ pub async fn perform_pre_authentication( payment_id, three_ds_connector_account .get_mca_id() - .ok_or(errors::ApiErrorResponse::InternalServerError) + .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Error while finding mca_id from merchant_connector_account")?, ) .await?; diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs index d4cad2fbedb..9e00dfe70c9 100644 --- a/crates/router/src/core/authentication/transformers.rs +++ b/crates/router/src/core/authentication/transformers.rs @@ -29,8 +29,8 @@ pub fn construct_authentication_router_data( authentication_connector: String, payment_method_data: payments::PaymentMethodData, payment_method: PaymentMethod, - billing_address: api_models::payments::Address, - shipping_address: Option<api_models::payments::Address>, + billing_address: payments::Address, + shipping_address: Option<payments::Address>, browser_details: Option<types::BrowserInformation>, amount: Option<i64>, currency: Option<common_enums::Currency>, @@ -40,8 +40,8 @@ pub fn construct_authentication_router_data( merchant_connector_account: payments_helpers::MerchantConnectorAccountType, authentication_data: storage::Authentication, return_url: Option<String>, - sdk_information: Option<api_models::payments::SdkInformation>, - threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator, + sdk_information: Option<payments::SdkInformation>, + threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, ) -> RouterResult<types::authentication::ConnectorAuthenticationRouterData> { diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index af97c500f3e..3b10b408f9e 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -37,7 +37,7 @@ pub async fn create_customer( let db = state.store.as_ref(); let customer_id = &customer_data.customer_id; let merchant_id = &merchant_account.merchant_id; - customer_data.merchant_id = merchant_id.to_owned(); + merchant_id.clone_into(&mut customer_data.merchant_id); // We first need to validate whether the customer with the given customer id already exists // this may seem like a redundant db call, as the insert_customer will anyway return this error diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index d80d86460b2..a70a97e7bf0 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -105,7 +105,7 @@ impl From<ring::error::Unspecified> for EncryptionError { pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> { ApiErrorResponse::NotImplemented { - message: api_error_response::NotImplementedMessage::Default, + message: NotImplementedMessage::Default, } .error_response() } diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index e2ce5b42c3f..5dedcb14863 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -7,7 +7,7 @@ use super::errors::{self, RouterResponse}; use crate::{ consts, routes::AppState, - services::{self, ApplicationResponse}, + services::ApplicationResponse, types::{api, domain}, }; @@ -72,9 +72,9 @@ pub async fn files_create_core( .attach_printable_lazy(|| { format!("Unable to update file_metadata with file_id: {}", file_id) })?; - Ok(services::api::ApplicationResponse::Json( - files::CreateFileResponse { file_id }, - )) + Ok(ApplicationResponse::Json(files::CreateFileResponse { + file_id, + })) } pub async fn files_delete_core( diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 5e03033977e..e26d5d0b461 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -81,10 +81,10 @@ where ) .await?; - frm_data.payment_attempt.connector_transaction_id = payment_data + frm_data .payment_attempt .connector_transaction_id - .clone(); + .clone_from(&payment_data.payment_attempt.connector_transaction_id); let mut router_data = frm_data .construct_router_data( @@ -676,7 +676,7 @@ where if matches!(fraud_capture_method, Some(Some(CaptureMethod::Manual))) && matches!( payment_data.payment_attempt.status, - api_models::enums::AttemptStatus::Unresolved + AttemptStatus::Unresolved ) { if let Some(info) = frm_info { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 939367bd4db..7a1e294f9dc 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -512,11 +512,11 @@ impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>> pub trait MandateBehaviour { fn get_amount(&self) -> i64; fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage>; - fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds>; - fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>); + fn get_mandate_id(&self) -> Option<&payments::MandateIds>; + fn set_mandate_id(&mut self, new_mandate_id: Option<payments::MandateIds>); fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData; fn get_setup_mandate_details( &self, ) -> Option<&hyperswitch_domain_models::mandates::MandateData>; - fn get_customer_acceptance(&self) -> Option<api_models::payments::CustomerAcceptance>; + fn get_customer_acceptance(&self) -> Option<payments::CustomerAcceptance>; } diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs index 3f9f5f017a7..11c53a77b1e 100644 --- a/crates/router/src/core/payment_link.rs +++ b/crates/router/src/core/payment_link.rs @@ -350,7 +350,9 @@ fn validate_order_details( order_details_amount_string.product_img_link = Some(DEFAULT_PRODUCT_IMG.to_string()) } else { - order_details_amount_string.product_img_link = order.product_img_link.clone() + order_details_amount_string + .product_img_link + .clone_from(&order.product_img_link) }; order_details_amount_string.amount = currency diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index d3f6aeea24b..9ae327269cf 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -115,10 +115,10 @@ pub async fn create_payment_method( payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone(), - metadata: pm_metadata.map(masking::Secret::new), + metadata: pm_metadata.map(Secret::new), payment_method_data, connector_mandate_details, - customer_acceptance: customer_acceptance.map(masking::Secret::new), + customer_acceptance: customer_acceptance.map(Secret::new), client_secret: Some(client_secret), status: status.unwrap_or(enums::PaymentMethodStatus::Active), network_transaction_id: network_transaction_id.to_owned(), @@ -201,7 +201,7 @@ pub async fn get_or_insert_payment_method( .await; match &existing_pm_by_locker_id { - Ok(pm) => payment_method_id = pm.payment_method_id.clone(), + Ok(pm) => payment_method_id.clone_from(&pm.payment_method_id), Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"), }; existing_pm_by_locker_id @@ -212,7 +212,7 @@ pub async fn get_or_insert_payment_method( existing_pm_by_pmid } }; - resp.payment_method_id = payment_method_id.to_owned(); + payment_method_id.clone_into(&mut resp.payment_method_id); match payment_method { Ok(pm) => Ok(pm), @@ -405,7 +405,7 @@ pub async fn add_payment_method_data( return Ok(services::ApplicationResponse::Json(pm_resp)); } else { let locker_id = pm_resp.payment_method_id.clone(); - pm_resp.payment_method_id = pm_id.clone(); + pm_resp.payment_method_id.clone_from(&pm_id); pm_resp.client_secret = Some(client_secret.clone()); let card_isin = card.card_number.clone().get_card_isin(); @@ -898,7 +898,9 @@ pub async fn update_customer_payment_method( payment_method_data: pm_data_encrypted, }; - add_card_resp.payment_method_id = pm.payment_method_id.clone(); + add_card_resp + .payment_method_id + .clone_from(&pm.payment_method_id); db.update_payment_method(pm, pm_update, merchant_account.storage_scheme) .await @@ -1191,7 +1193,7 @@ pub async fn add_card_hs( card_exp_year: card.card_exp_year.to_owned(), card_brand: card.card_network.as_ref().map(ToString::to_string), card_isin: None, - nick_name: card.nick_name.as_ref().map(masking::Secret::peek).cloned(), + nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(), }, }); @@ -2912,7 +2914,7 @@ fn filter_pm_based_on_supported_payments_for_mandate( } fn filter_pm_based_on_config<'a>( - config: &'a crate::configs::settings::ConnectorFilters, + config: &'a settings::ConnectorFilters, connector: &'a str, payment_method_type: &'a api_enums::PaymentMethodType, payment_attempt: Option<&storage::PaymentAttempt>, @@ -3615,7 +3617,7 @@ pub async fn get_card_details_with_locker_fallback( Ok(if let Some(mut crd) = card_decrypted { if crd.saved_to_locker { - crd.scheme = pm.scheme.clone(); + crd.scheme.clone_from(&pm.scheme); Some(crd) } else { None @@ -3645,7 +3647,7 @@ pub async fn get_card_details_without_locker_fallback( }); Ok(if let Some(mut crd) = card_decrypted { - crd.scheme = pm.scheme.clone(); + crd.scheme.clone_from(&pm.scheme); crd } else { get_card_details_from_locker(state, pm).await? @@ -4005,10 +4007,7 @@ impl TempLockerCardSupport { metrics::TASKS_ADDED_COUNT.add( &metrics::CONTEXT, 1, - &[metrics::request::add_attributes( - "flow", - "DeleteTokenizeData", - )], + &[request::add_attributes("flow", "DeleteTokenizeData")], ); Ok(card) } @@ -4171,7 +4170,7 @@ pub async fn create_encrypted_payment_method_data( let pm_data_encrypted: Option<Encryption> = pm_data .as_ref() - .map(utils::Encode::encode_to_value) + .map(Encode::encode_to_value) .transpose() .change_context(errors::StorageError::SerializationFailed) .attach_printable("Unable to convert payment method data to a value") @@ -4179,7 +4178,7 @@ pub async fn create_encrypted_payment_method_data( logger::error!(err=?err); None }) - .map(masking::Secret::<_, masking::WithType>::new) + .map(Secret::<_, masking::WithType>::new) .async_lift(|inner| encrypt_optional(inner, key)) .await .change_context(errors::StorageError::EncryptionError) diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 9c53642f4d7..009e9e54467 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -563,7 +563,7 @@ pub fn get_card_detail( card_token: None, card_fingerprint: None, card_holder_name: response.name_on_card, - nick_name: response.nick_name.map(masking::Secret::new), + nick_name: response.nick_name.map(Secret::new), card_isin: None, card_issuer: None, card_network: None, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 07bceefb0f9..0e10c2a5417 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -12,8 +12,10 @@ pub mod transformers; pub mod types; #[cfg(feature = "olap")] -use std::collections::{HashMap, HashSet}; -use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter}; +use std::collections::HashMap; +use std::{ + collections::HashSet, fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter, +}; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; @@ -119,7 +121,7 @@ where router_types::RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, // To construct connector flow specific api - dyn router_types::api::Connector: + dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse @@ -265,7 +267,7 @@ where _ => (), }; payment_data = match connector_details { - api::ConnectorCallType::PreDetermined(connector) => { + ConnectorCallType::PreDetermined(connector) => { let schedule_time = if should_add_task_to_process_tracker { payment_sync::get_sync_process_schedule_time( &*state.store, @@ -330,7 +332,7 @@ where .await? } - api::ConnectorCallType::Retryable(connectors) => { + ConnectorCallType::Retryable(connectors) => { let mut connectors = connectors.into_iter(); let connector_data = get_connector_data(&mut connectors)?; @@ -432,7 +434,7 @@ where .await? } - api::ConnectorCallType::SessionMultiple(connectors) => { + ConnectorCallType::SessionMultiple(connectors) => { let session_surcharge_details = call_surcharge_decision_management_for_session_flow( state, @@ -741,7 +743,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, Ctx>( req: Req, auth_flow: services::AuthFlow, call_connector_action: CallConnectorAction, - eligible_connectors: Option<Vec<api_models::enums::Connector>>, + eligible_connectors: Option<Vec<enums::Connector>>, header_payload: HeaderPayload, ) -> RouterResponse<Res> where @@ -756,7 +758,7 @@ where Ctx: PaymentMethodRetrieve, // To construct connector flow specific api - dyn router_types::api::Connector: + dyn api::Connector: services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, // To perform router related operation for PaymentResponse @@ -994,7 +996,7 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCom // If the status is requires customer action, then send the startpay url again // The redirection data must have been provided and updated by the connector let redirection_response = match payments_response.status { - api_models::enums::IntentStatus::RequiresCustomerAction => { + enums::IntentStatus::RequiresCustomerAction => { let startpay_url = payments_response .next_action .clone() @@ -1021,9 +1023,9 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentRedirectCom }) } // If the status is terminal status, then redirect to merchant return url to provide status - api_models::enums::IntentStatus::Succeeded - | api_models::enums::IntentStatus::Failed - | api_models::enums::IntentStatus::Cancelled | api_models::enums::IntentStatus::RequiresCapture| api_models::enums::IntentStatus::Processing=> helpers::get_handle_response_url( + enums::IntentStatus::Succeeded + | enums::IntentStatus::Failed + | enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture| enums::IntentStatus::Processing=> helpers::get_handle_response_url( payment_id, &payment_flow_response.business_profile, payments_response, @@ -1293,9 +1295,8 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentAuthenticat }?; // When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction { - let req_poll_id = - super::utils::get_external_authentication_request_poll_id(&payment_id); - let poll_id = super::utils::get_poll_id(merchant_id.clone(), req_poll_id.clone()); + let req_poll_id = utils::get_external_authentication_request_poll_id(&payment_id); + let poll_id = utils::get_poll_id(merchant_id.clone(), req_poll_id.clone()); let redis_conn = state .store .get_redis_conn() @@ -1797,7 +1798,7 @@ where merchant_connector_account.get_mca_id(), )?; - let connector_label = super::utils::get_connector_label( + let connector_label = utils::get_connector_label( payment_data.payment_intent.business_country, payment_data.payment_intent.business_label.as_ref(), payment_data.payment_attempt.business_sub_label.as_ref(), @@ -2087,13 +2088,11 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization( } fn decide_apple_pay_flow( - payment_method_type: &Option<api_models::enums::PaymentMethodType>, + payment_method_type: &Option<enums::PaymentMethodType>, merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>, ) -> Option<enums::ApplePayFlow> { payment_method_type.and_then(|pmt| match pmt { - api_models::enums::PaymentMethodType::ApplePay => { - check_apple_pay_metadata(merchant_connector_account) - } + enums::PaymentMethodType::ApplePay => check_apple_pay_metadata(merchant_connector_account), _ => None, }) } @@ -3032,7 +3031,7 @@ pub async fn get_connector_choice<F, Req, Ctx>( business_profile: &storage::business_profile::BusinessProfile, key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, - eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, + eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<Option<ConnectorCallType>> where @@ -3061,7 +3060,7 @@ where connectors, ) .await?; - api::ConnectorCallType::SessionMultiple(routing_output) + ConnectorCallType::SessionMultiple(routing_output) } api::ConnectorChoice::StraightThrough(straight_through) => { @@ -3112,7 +3111,7 @@ pub async fn connector_selection<F>( key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, request_straight_through: Option<serde_json::Value>, - eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, + eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where @@ -3188,7 +3187,7 @@ pub async fn decide_connector<F>( payment_data: &mut PaymentData<F>, request_straight_through: Option<api::routing::StraightThroughAlgorithm>, routing_data: &mut storage::RoutingData, - eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, + eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where @@ -3209,7 +3208,7 @@ where .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); - return Ok(api::ConnectorCallType::PreDetermined(connector_data)); + return Ok(ConnectorCallType::PreDetermined(connector_data)); } if let Some(mandate_connector_details) = payment_data.mandate_connector.as_ref() { @@ -3228,10 +3227,11 @@ where routing_data.routed_through = Some(mandate_connector_details.connector.clone()); #[cfg(feature = "connector_choice_mca_id")] { - routing_data.merchant_connector_id = - mandate_connector_details.merchant_connector_id.clone(); + routing_data + .merchant_connector_id + .clone_from(&mandate_connector_details.merchant_connector_id); } - return Ok(api::ConnectorCallType::PreDetermined(connector_data)); + return Ok(ConnectorCallType::PreDetermined(connector_data)); } if let Some((pre_routing_results, storage_pm_type)) = routing_data @@ -3259,13 +3259,15 @@ where routing_data.routed_through = Some(choice.connector.to_string()); #[cfg(feature = "connector_choice_mca_id")] { - routing_data.merchant_connector_id = choice.merchant_connector_id.clone(); + routing_data + .merchant_connector_id + .clone_from(&choice.merchant_connector_id); } #[cfg(not(feature = "connector_choice_mca_id"))] { routing_data.business_sub_label = choice.sub_label.clone(); } - return Ok(api::ConnectorCallType::PreDetermined(connector_data)); + return Ok(ConnectorCallType::PreDetermined(connector_data)); } } @@ -3540,14 +3542,16 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); #[cfg(feature = "connector_choice_mca_id")] { - routing_data.merchant_connector_id = - chosen_connector_data.merchant_connector_id.clone(); + routing_data + .merchant_connector_id + .clone_from(&chosen_connector_data.merchant_connector_id); } routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string()); #[cfg(feature = "connector_choice_mca_id")] { - routing_data.merchant_connector_id = - chosen_connector_data.merchant_connector_id.clone(); + routing_data + .merchant_connector_id + .clone_from(&chosen_connector_data.merchant_connector_id); } payment_data.mandate_id = Some(payments_api::MandateIds { @@ -3555,7 +3559,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone mandate_reference_id, }); - Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data)) + Ok(ConnectorCallType::PreDetermined(chosen_connector_data)) } _ => { let first_choice = connectors @@ -3570,7 +3574,7 @@ pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone routing_data.merchant_connector_id = first_choice.merchant_connector_id; } - Ok(api::ConnectorCallType::Retryable(connectors)) + Ok(ConnectorCallType::Retryable(connectors)) } } } @@ -3655,7 +3659,7 @@ where } } - let routing_enabled_pms = std::collections::HashSet::from([ + let routing_enabled_pms = HashSet::from([ enums::PaymentMethodType::GooglePay, enums::PaymentMethodType::ApplePay, enums::PaymentMethodType::Klarna, @@ -3723,7 +3727,7 @@ pub async fn route_connector_v1<F>( key_store: &domain::MerchantKeyStore, transaction_data: TransactionData<'_, F>, routing_data: &mut storage::RoutingData, - eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, + eligible_connectors: Option<Vec<enums::RoutableConnectors>>, mandate_type: Option<api::MandateTransactionType>, ) -> RouterResult<ConnectorCallType> where @@ -4015,7 +4019,7 @@ pub async fn payment_external_authentication( return_url, req.sdk_information, req.threeds_method_comp_ind, - optional_customer.and_then(|customer| customer.email.map(common_utils::pii::Email::from)), + optional_customer.and_then(|customer| customer.email.map(pii::Email::from)), webhook_url, )) .await?; diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs index 1de9cb60ca0..f7fe5b7844f 100644 --- a/crates/router/src/core/payments/access_token.rs +++ b/crates/router/src/core/payments/access_token.rs @@ -35,7 +35,7 @@ pub fn update_router_data_with_access_token_result<F, Req, Res>( if should_update_router_data { match add_access_token_result.access_token_result.as_ref() { Ok(access_token) => { - router_data.access_token = access_token.clone(); + router_data.access_token.clone_from(access_token); true } Err(connector_error) => { diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 6b64dc04044..09b96284544 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -266,7 +266,7 @@ pub async fn authorize_preprocessing_steps<F: Clone>( Err(types::ErrorResponse::default()); let preprocessing_router_data = - payments::helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>( + helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>( router_data.clone(), preprocessing_request_data, preprocessing_response_data, @@ -303,12 +303,11 @@ pub async fn authorize_preprocessing_steps<F: Clone>( ], ); - let authorize_router_data = - payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>( - resp.clone(), - router_data.request.to_owned(), - resp.response, - ); + let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>( + resp.clone(), + router_data.request.to_owned(), + resp.response, + ); Ok(authorize_router_data) } else { diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index baf4190395f..667fa3feed0 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -172,7 +172,7 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>( Err(types::ErrorResponse::default()); let preprocessing_router_data = - payments::helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>( + helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>( router_data.clone(), preprocessing_request_data, preprocessing_response_data, @@ -206,15 +206,14 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>( connector_metadata, .. }) = &resp.response { - router_data_request.connector_meta = connector_metadata.to_owned(); + connector_metadata.clone_into(&mut router_data_request.connector_meta); }; - let authorize_router_data = - payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>( - resp.clone(), - router_data_request, - resp.response, - ); + let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>( + resp.clone(), + router_data_request, + resp.response, + ); Ok(authorize_router_data) } else { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index f17a7075d43..e4c4540cacf 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -636,7 +636,7 @@ pub async fn get_token_for_recurring_mandate( merchant_connector_id: mandate.merchant_connector_id, }; - if let Some(diesel_models::enums::PaymentMethod::Card) = payment_method.payment_method { + if let Some(enums::PaymentMethod::Card) = payment_method.payment_method { if state.conf.locker.locker_enabled { let _ = cards::get_lookup_key_from_locker( state, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 87943b4cf2b..8dffd8eaec3 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -59,10 +59,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> helpers::validate_payment_status_against_not_allowed_statuses( &payment_intent.status, - &[ - storage_enums::IntentStatus::Failed, - storage_enums::IntentStatus::Succeeded, - ], + &[IntentStatus::Failed, IntentStatus::Succeeded], "approve", )?; diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 3e531280831..32035391fb7 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -112,7 +112,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); - payment_attempt.cancellation_reason = request.cancellation_reason.clone(); + payment_attempt + .cancellation_reason + .clone_from(&request.cancellation_reason); let creds_identifier = request .merchant_connector_details diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index e770da70747..0d241202208 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -31,7 +31,6 @@ use crate::{ routes::{app::ReqState, AppState}, services, types::{ - self, api::{self, PaymentIdTypeExt}, domain, storage::{ @@ -949,7 +948,7 @@ impl PaymentCreate { #[allow(clippy::too_many_arguments)] async fn make_payment_intent( payment_id: &str, - merchant_account: &types::domain::MerchantAccount, + merchant_account: &domain::MerchantAccount, money: (api::Amount, enums::Currency), request: &api::PaymentsRequest, shipping_address_id: Option<String>, @@ -971,7 +970,7 @@ impl PaymentCreate { request.confirm, ); let client_secret = - crate::utils::generate_id(consts::ID_LENGTH, format!("{payment_id}_secret").as_str()); + utils::generate_id(consts::ID_LENGTH, format!("{payment_id}_secret").as_str()); let (amount, currency) = (money.0, Some(money.1)); let order_details = request diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index b40ee8e5c9c..c3ef748c037 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -19,7 +19,6 @@ use crate::{ mandate, payment_methods::{self, PaymentMethodRetrieve}, payments::{ - self, helpers::{ self as payments_helpers, update_additional_payment_data_with_connector_response_pm_data, @@ -727,8 +726,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( Some(multiple_capture_data) => { let capture_update = storage::CaptureUpdate::ErrorUpdate { status: match err.status_code { - 500..=511 => storage::enums::CaptureStatus::Pending, - _ => storage::enums::CaptureStatus::Failed, + 500..=511 => enums::CaptureStatus::Pending, + _ => enums::CaptureStatus::Failed, }, error_code: Some(err.code), error_message: Some(err.message), @@ -761,20 +760,20 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( if flow_name == "PSync" { match err.status_code { // marking failure for 2xx because this is genuine payment failure - 200..=299 => storage::enums::AttemptStatus::Failure, + 200..=299 => enums::AttemptStatus::Failure, _ => router_data.status, } } else if flow_name == "Capture" { match err.status_code { - 500..=511 => storage::enums::AttemptStatus::Pending, + 500..=511 => enums::AttemptStatus::Pending, // don't update the status for 429 error status 429 => router_data.status, - _ => storage::enums::AttemptStatus::Failure, + _ => enums::AttemptStatus::Failure, } } else { match err.status_code { - 500..=511 => storage::enums::AttemptStatus::Pending, - _ => storage::enums::AttemptStatus::Failure, + 500..=511 => enums::AttemptStatus::Pending, + _ => enums::AttemptStatus::Failure, } } } @@ -896,8 +895,10 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }; if router_data.status == enums::AttemptStatus::Charged { - payment_data.payment_intent.fingerprint_id = - payment_data.payment_attempt.fingerprint_id.clone(); + payment_data + .payment_intent + .fingerprint_id + .clone_from(&payment_data.payment_attempt.fingerprint_id); metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]); } @@ -1075,8 +1076,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( payment_data.authentication = match payment_data.authentication { Some(authentication) => { let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate { - authentication_lifecycle_status: - storage::enums::AuthenticationLifecycleStatus::Used, + authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used, }; let updated_authentication = state .store @@ -1159,7 +1159,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }; if let Some(payment_method) = payment_data.payment_method_info.clone() { let connector_mandate_details = - payments::tokenization::update_connector_mandate_details_in_payment_method( + tokenization::update_connector_mandate_details_in_payment_method( payment_method.clone(), payment_method.payment_method_type, Some(payment_data.payment_attempt.amount), diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 4c0359c28f0..06ad57346f5 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -289,7 +289,7 @@ async fn get_tracker_for_sync< ) .await?; - payment_attempt.encoded_data = request.param.clone(); + payment_attempt.encoded_data.clone_from(&request.param); let attempts = match request.expand_attempts { Some(true) => { diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 0aaa6006052..de83b935ff0 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -727,8 +727,6 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_data.mandate_id = payment_data.mandate_id.clone(); - Ok(( payments::is_confirm(self, payment_data.confirm), payment_data, @@ -832,7 +830,9 @@ impl PaymentUpdate { payment_intent.business_country = request.business_country; - payment_intent.business_label = request.business_label.clone(); + payment_intent + .business_label + .clone_from(&request.business_label); request .description diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 958c3f4362f..e7bb8f86d5d 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -205,9 +205,7 @@ where }; let pm_card_details = resp.card.as_ref().map(|card| { - api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from( - card.clone(), - )) + PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())) }); let pm_data_encrypted = @@ -243,7 +241,7 @@ where match &existing_pm_by_locker_id { Ok(pm) => { - payment_method_id = pm.payment_method_id.clone() + payment_method_id.clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = @@ -351,7 +349,8 @@ where match &existing_pm_by_locker_id { Ok(pm) => { - payment_method_id = pm.payment_method_id.clone() + payment_method_id + .clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = @@ -564,7 +563,7 @@ async fn skip_saving_card_in_locker( .customer_id .clone() .get_required_value("customer_id")?; - let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let last4_digits = payment_method_request .card @@ -616,7 +615,7 @@ async fn skip_saving_card_in_locker( Ok((pm_resp, None)) } None => { - let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_string(), customer_id: Some(customer_id), @@ -666,7 +665,7 @@ pub async fn save_in_locker( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed"), None => { - let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_string(), customer_id: Some(customer_id), @@ -732,18 +731,12 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( let pm_token_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> = Err(types::ErrorResponse::default()); - let mut pm_token_router_data = payments::helpers::router_data_type_conversion::< - _, - api::PaymentMethodToken, - _, - _, - _, - _, - >( - router_data.clone(), - pm_token_request_data, - pm_token_response_data, - ); + let mut pm_token_router_data = + helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( + router_data.clone(), + pm_token_request_data, + pm_token_response_data, + ); connector_integration .execute_pretasks(&mut pm_token_router_data, state) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 56874e5a9fc..2b7ba070d2c 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1547,8 +1547,8 @@ impl TryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { .. } => Ok(Self::ErrorUpdate { status: match status_code { - 500..=511 => storage::enums::CaptureStatus::Pending, - _ => storage::enums::CaptureStatus::Failed, + 500..=511 => enums::CaptureStatus::Pending, + _ => enums::CaptureStatus::Failed, }, error_code: Some(code), error_message: Some(message), diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index e521fac9a80..790cb25c479 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -403,7 +403,9 @@ pub async fn save_payout_data_to_locker( .await .flatten() .map(|card_info| { - payment_method.payment_method_issuer = card_info.card_issuer.clone(); + payment_method + .payment_method_issuer + .clone_from(&card_info.card_issuer); payment_method.card_network = card_info.card_network.clone().map(|cn| cn.to_string()); api::payment_methods::PaymentMethodsData::Card( @@ -641,7 +643,7 @@ pub async fn decide_payout_connector( request_straight_through: Option<api::routing::StraightThroughAlgorithm>, routing_data: &mut storage::RoutingData, payout_data: &mut PayoutData, - eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, + eligible_connectors: Option<Vec<enums::RoutableConnectors>>, ) -> RouterResult<api::ConnectorCallType> { // 1. For existing attempts, use stored connector let payout_attempt = &payout_data.payout_attempt; diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index 6bbee9a4cec..a7dcfa864a0 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -114,7 +114,7 @@ pub async fn do_gsm_single_connector_actions( if let Ordering::Equal = gsm.cmp(&previous_gsm) { break; } - previous_gsm = gsm.clone(); + previous_gsm.clone_from(&gsm); match get_gsm_decision(gsm) { api_models::gsm::GsmDecision::Retry => { diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 09ea935ea76..88138d7909f 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -64,7 +64,7 @@ pub async fn create_link_token( let redis_conn = db .get_redis_conn() - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let pm_auth_key = format!("pm_auth_{}", payload.payment_id); @@ -75,7 +75,7 @@ pub async fn create_link_token( "Vec<PaymentMethodAuthConnectorChoice>", ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get payment method auth choices from redis")?; let selected_config = pm_auth_configs @@ -132,7 +132,7 @@ pub async fn create_link_token( &key_store, ) .await - .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_account.merchant_id.clone(), })?; @@ -145,7 +145,7 @@ pub async fn create_link_token( request: pm_auth_types::LinkTokenRequest { client_name: "HyperSwitch".to_string(), country_codes: Some(vec![billing_country.ok_or( - errors::ApiErrorResponse::MissingRequiredField { + ApiErrorResponse::MissingRequiredField { field_name: "billing_country", }, )?]), @@ -216,8 +216,7 @@ pub async fn exchange_token_core( let connector_name = config.connector_name.as_str(); - let connector = - pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(connector_name)?; + let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?; let merchant_connector_account = state .store @@ -227,7 +226,7 @@ pub async fn exchange_token_core( &key_store, ) .await - .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_account.merchant_id.clone(), })?; @@ -405,9 +404,7 @@ async fn store_bank_details_in_payment_methods( connector_details: vec![payment_methods::BankAccountConnectorDetails { connector: connector_name.to_string(), mca_id: mca_id.clone(), - access_token: payment_methods::BankAccountAccessCreds::AccessToken( - access_token.clone(), - ), + access_token: BankAccountAccessCreds::AccessToken(access_token.clone()), account_id: creds.account_id, }], }; @@ -612,7 +609,7 @@ async fn get_selected_config_from_redis( ) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> { let redis_conn = db .get_redis_conn() - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let pm_auth_key = format!("pm_auth_{}", payload.payment_id); @@ -623,7 +620,7 @@ async fn get_selected_config_from_redis( "Vec<PaymentMethodAuthConnectorChoice>", ) .await - .change_context(errors::ApiErrorResponse::GenericNotFoundError { + .change_context(ApiErrorResponse::GenericNotFoundError { message: "payment method auth connector name not found".to_string(), }) .attach_printable("Failed to get payment method auth choices from redis")?; @@ -651,14 +648,14 @@ pub async fn retrieve_payment_method_from_auth_service( ) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> { let db = state.store.as_ref(); - let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( + let connector = PaymentAuthConnectorData::get_connector_by_name( auth_token.connector_details.connector.as_str(), )?; let merchant_account = db .find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store) .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( @@ -667,7 +664,7 @@ pub async fn retrieve_payment_method_from_auth_service( key_store, ) .await - .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { id: auth_token.connector_details.mca_id.clone(), }) .attach_printable( @@ -697,7 +694,7 @@ pub async fn retrieve_payment_method_from_auth_service( acc.payment_method_type == auth_token.payment_method_type && acc.payment_method == auth_token.payment_method }) - .ok_or(errors::ApiErrorResponse::InternalServerError) + .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Bank account details not found")?; let mut bank_type = None; @@ -720,7 +717,7 @@ pub async fn retrieve_payment_method_from_auth_service( let name = address .as_ref() .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner())) - .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + .ok_or(ApiErrorResponse::GenericNotFoundError { message: "billing_first_name not found".to_string(), }) .attach_printable("billing_first_name not found")?; diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index c3512c32f42..ee1693b0c9d 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -8,15 +8,15 @@ use masking::ExposeInterface; #[cfg(feature = "email")] use router_env::logger; +#[cfg(feature = "email")] +use crate::services::email::types as email_types; use crate::{ core::errors::{UserErrors, UserResponse, UserResult}, routes::{app::ReqState, AppState}, services::{authentication::UserFromToken, ApplicationResponse}, - types::domain::{user::dashboard_metadata as types, MerchantKeyStore}, + types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore}, utils::user::dashboard_metadata as utils, }; -#[cfg(feature = "email")] -use crate::{services::email::types as email_types, types::domain}; pub async fn set_metadata( state: AppState, @@ -709,7 +709,7 @@ pub async fn get_merchant_connector_account_by_name( merchant_id: &str, connector_name: &str, key_store: &MerchantKeyStore, -) -> UserResult<Option<crate::types::domain::MerchantConnectorAccount>> { +) -> UserResult<Option<domain::MerchantConnectorAccount>> { state .store .find_merchant_connector_account_by_merchant_id_connector_name( diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 3923663f5d1..ac546ef5e49 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -564,7 +564,7 @@ pub async fn construct_accept_dispute_router_data<'a>( dispute_id: dispute.dispute_id.clone(), connector_dispute_id: dispute.connector_dispute_id.clone(), }, - response: Err(types::ErrorResponse::default()), + response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, @@ -654,7 +654,7 @@ pub async fn construct_submit_evidence_router_data<'a>( connector_meta_data: merchant_connector_account.get_metadata(), amount_captured: payment_intent.amount_captured, request: submit_evidence_request_data, - response: Err(types::ErrorResponse::default()), + response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, @@ -752,7 +752,7 @@ pub async fn construct_upload_file_router_data<'a>( file_type: create_file_request.file_type.clone(), file_size: create_file_request.file_size, }, - response: Err(types::ErrorResponse::default()), + response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, @@ -936,7 +936,7 @@ pub async fn construct_retrieve_file_router_data<'a>( .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing provider file id")?, }, - response: Err(types::ErrorResponse::default()), + response: Err(ErrorResponse::default()), access_token: None, session_token: None, reference_id: None, @@ -1225,9 +1225,7 @@ pub fn get_incremental_authorization_allowed_value( incremental_authorization_allowed: Option<bool>, request_incremental_authorization: Option<RequestIncrementalAuthorization>, ) -> Option<bool> { - if request_incremental_authorization - == Some(common_enums::RequestIncrementalAuthorization::False) - { + if request_incremental_authorization == Some(RequestIncrementalAuthorization::False) { Some(false) } else { incremental_authorization_allowed diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index 8782126b0b6..fe3d752497a 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -89,7 +89,7 @@ pub async fn get_verified_apple_domains_with_mid_mca_id( merchant_id: String, merchant_connector_id: String, ) -> CustomResult< - services::ApplicationResponse<api_models::verifications::ApplepayVerifiedDomainsResponse>, + services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>, api_error_response::ApiErrorResponse, > { let db = state.store.as_ref(); @@ -110,6 +110,6 @@ pub async fn get_verified_apple_domains_with_mid_mca_id( .unwrap_or_default(); Ok(services::api::ApplicationResponse::Json( - api_models::verifications::ApplepayVerifiedDomainsResponse { verified_domains }, + verifications::ApplepayVerifiedDomainsResponse { verified_domains }, )) } diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 6647549e399..3c04fdb7e49 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -74,7 +74,7 @@ pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>( payments::CallConnectorAction::Trigger }; let payments_response = match webhook_details.object_reference_id { - api_models::webhooks::ObjectReferenceId::PaymentId(id) => { + webhooks::ObjectReferenceId::PaymentId(id) => { let payment_id = get_payment_id( state.store.as_ref(), &id, @@ -84,7 +84,7 @@ pub async fn payments_incoming_webhook_flow<Ctx: PaymentMethodRetrieve>( .await?; let lock_action = api_locking::LockAction::Hold { - input: super::api_locking::LockingInput { + input: api_locking::LockingInput { unique_locking_key: payment_id, api_identifier: lock_utils::ApiIdentifier::Payments, override_lock_retries: None, @@ -213,13 +213,13 @@ pub async fn refunds_incoming_webhook_flow( webhook_details: api::IncomingWebhookDetails, connector_name: &str, source_verified: bool, - event_type: api_models::webhooks::IncomingWebhookEvent, + event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { let db = &*state.store; //find refund by connector refund id let refund = match webhook_details.object_reference_id { - api_models::webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type { - api_models::webhooks::RefundIdType::RefundId(id) => db + webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type { + webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( &merchant_account.merchant_id, &id, @@ -228,7 +228,7 @@ pub async fn refunds_incoming_webhook_flow( .await .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable("Failed to fetch the refund")?, - api_models::webhooks::RefundIdType::ConnectorRefundId(id) => db + webhooks::RefundIdType::ConnectorRefundId(id) => db .find_refund_by_merchant_id_connector_refund_id_connector( &merchant_account.merchant_id, &id, @@ -305,7 +305,7 @@ pub async fn refunds_incoming_webhook_flow( pub async fn get_payment_attempt_from_object_reference_id( state: &AppState, - object_reference_id: api_models::webhooks::ObjectReferenceId, + object_reference_id: webhooks::ObjectReferenceId, merchant_account: &domain::MerchantAccount, ) -> CustomResult< hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, @@ -349,7 +349,7 @@ pub async fn get_or_update_dispute_object( dispute_details: api::disputes::DisputePayload, merchant_id: &str, payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, - event_type: api_models::webhooks::IncomingWebhookEvent, + event_type: webhooks::IncomingWebhookEvent, business_profile: &diesel_models::business_profile::BusinessProfile, connector_name: &str, ) -> CustomResult<diesel_models::dispute::Dispute, errors::ApiErrorResponse> { @@ -425,7 +425,7 @@ pub async fn external_authentication_incoming_webhook_flow<Ctx: PaymentMethodRet merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, source_verified: bool, - event_type: api_models::webhooks::IncomingWebhookEvent, + event_type: webhooks::IncomingWebhookEvent, request_details: &api::IncomingWebhookRequestDetails<'_>, connector: &(dyn api::Connector + Sync), object_ref_id: api::ObjectReferenceId, @@ -601,7 +601,7 @@ pub async fn mandates_incoming_webhook_flow( key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, - event_type: api_models::webhooks::IncomingWebhookEvent, + event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { if source_verified { let db = &*state.store; @@ -691,7 +691,7 @@ pub async fn disputes_incoming_webhook_flow( source_verified: bool, connector: &(dyn api::Connector + Sync), request_details: &api::IncomingWebhookRequestDetails<'_>, - event_type: api_models::webhooks::IncomingWebhookEvent, + event_type: webhooks::IncomingWebhookEvent, ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); if source_verified { @@ -1612,7 +1612,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr let is_webhook_event_supported = !matches!( event_type, - api_models::webhooks::IncomingWebhookEvent::EventNotSupported + webhooks::IncomingWebhookEvent::EventNotSupported ); let is_webhook_event_enabled = !utils::is_webhook_event_disabled( &*state.clone().store, @@ -2102,7 +2102,7 @@ pub(crate) fn get_outgoing_webhook_request( >( outgoing_webhook, payment_response_hash_key ), - _ => get_outgoing_webhook_request_inner::<api_models::webhooks::OutgoingWebhook>( + _ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>( outgoing_webhook, payment_response_hash_key, ), diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 3bf8c7c7f21..ad1aafd3125 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -124,8 +124,8 @@ pub async fn construct_webhook_router_data<'a>( #[inline] pub(crate) fn get_idempotent_event_id( primary_object_id: &str, - event_type: crate::types::storage::enums::EventType, - delivery_attempt: crate::types::storage::enums::WebhookDeliveryAttempt, + event_type: types::storage::enums::EventType, + delivery_attempt: types::storage::enums::WebhookDeliveryAttempt, ) -> String { use crate::types::storage::enums::WebhookDeliveryAttempt; diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 9b222486d18..ca9432fcba9 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -190,7 +190,7 @@ where let bytes = db.get_key(key).await?; bytes .parse_struct(type_name) - .change_context(redis_interface::errors::RedisError::JsonDeserializationFailed) + .change_context(RedisError::JsonDeserializationFailed) } dyn_clone::clone_trait_object!(StorageInterface); diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs index 7b5ade8c965..5e7c9bd0b20 100644 --- a/crates/router/src/db/business_profile.rs +++ b/crates/router/src/db/business_profile.rs @@ -6,7 +6,7 @@ use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, - types::storage::{self, business_profile}, + types::storage::business_profile, }; #[async_trait::async_trait] @@ -65,7 +65,7 @@ impl BusinessProfileInterface for Store { profile_id: &str, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::business_profile::BusinessProfile::find_by_profile_id(&conn, profile_id) + business_profile::BusinessProfile::find_by_profile_id(&conn, profile_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -77,7 +77,7 @@ impl BusinessProfileInterface for Store { merchant_id: &str, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::business_profile::BusinessProfile::find_by_profile_name_merchant_id( + business_profile::BusinessProfile::find_by_profile_name_merchant_id( &conn, profile_name, merchant_id, @@ -93,7 +93,7 @@ impl BusinessProfileInterface for Store { business_profile_update: business_profile::BusinessProfileUpdate, ) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::business_profile::BusinessProfile::update_by_profile_id( + business_profile::BusinessProfile::update_by_profile_id( current_state, &conn, business_profile_update, @@ -109,7 +109,7 @@ impl BusinessProfileInterface for Store { merchant_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::business_profile::BusinessProfile::delete_by_profile_id_merchant_id( + business_profile::BusinessProfile::delete_by_profile_id_merchant_id( &conn, profile_id, merchant_id, @@ -124,12 +124,9 @@ impl BusinessProfileInterface for Store { merchant_id: &str, ) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::business_profile::BusinessProfile::list_business_profile_by_merchant_id( - &conn, - merchant_id, - ) - .await - .map_err(|error| report!(errors::StorageError::from(error))) + business_profile::BusinessProfile::list_business_profile_by_merchant_id(&conn, merchant_id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) } } diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs index 7f2462b3fc8..d9db13dde80 100644 --- a/crates/router/src/db/cache.rs +++ b/crates/router/src/db/cache.rs @@ -43,7 +43,7 @@ where }; match redis_val { Err(err) => match err.current_context() { - errors::RedisError::NotFound | errors::RedisError::JsonDeserializationFailed => { + RedisError::NotFound | RedisError::JsonDeserializationFailed => { get_data_set_redis().await } _ => Err(err diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index 0fe5f3d7666..097ad9beab9 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -444,7 +444,7 @@ mod tests { #[tokio::test] async fn test_find_by_merchant_id_payment_id_connector_dispute_id() { #[allow(clippy::expect_used)] - let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) + let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -487,7 +487,7 @@ mod tests { #[tokio::test] async fn test_find_dispute_by_merchant_id_dispute_id() { #[allow(clippy::expect_used)] - let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) + let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -524,7 +524,7 @@ mod tests { #[tokio::test] async fn test_find_disputes_by_merchant_id() { #[allow(clippy::expect_used)] - let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) + let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); @@ -578,7 +578,7 @@ mod tests { #[tokio::test] async fn test_find_disputes_by_merchant_id_payment_id() { #[allow(clippy::expect_used)] - let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) + let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index e31a2663354..fff82334be0 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -377,8 +377,8 @@ impl UserRoleInterface for MockDb { status, modified_by, } => { - user_role.status = status.to_owned(); - user_role.last_modified_by = modified_by.to_owned(); + status.clone_into(&mut user_role.status); + modified_by.clone_into(&mut user_role.last_modified_by); } } updated_user_roles.push(user_role.to_owned()); diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index fdabd07fa01..d11e5cf997a 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -188,7 +188,7 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio errors::ApplicationError::ApiClientError(error.current_context().clone()) })?, ); - let state = Box::pin(routes::AppState::new(conf, tx, api_client)).await; + let state = Box::pin(AppState::new(conf, tx, api_client)).await; let request_body_limit = server.request_body_limit; let server = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) .bind((server.host.as_str(), server.port))? diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 55959589152..f1170f0f0bb 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -131,7 +131,7 @@ pub async fn api_key_update( let (merchant_id, key_id) = path.into_inner(); let mut payload = json_payload.into_inner(); payload.key_id = key_id; - payload.merchant_id = merchant_id.clone(); + payload.merchant_id.clone_from(&merchant_id); api::server_wrap( flow, diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs index 029c1c61f24..ef53ad83f2c 100644 --- a/crates/router/src/routes/metrics/request.rs +++ b/crates/router/src/routes/metrics/request.rs @@ -24,7 +24,7 @@ where #[inline] pub async fn record_operation_time<F, R>( future: F, - metric: &once_cell::sync::Lazy<router_env::opentelemetry::metrics::Histogram<f64>>, + metric: &once_cell::sync::Lazy<opentelemetry::metrics::Histogram<f64>>, key_value: &[opentelemetry::KeyValue], ) -> R where @@ -35,11 +35,11 @@ where result } -pub fn add_attributes<T: Into<router_env::opentelemetry::Value>>( +pub fn add_attributes<T: Into<opentelemetry::Value>>( key: &'static str, value: T, -) -> router_env::opentelemetry::KeyValue { - router_env::opentelemetry::KeyValue::new(key, value) +) -> opentelemetry::KeyValue { + opentelemetry::KeyValue::new(key, value) } pub fn status_code_metrics(status_code: i64, flow: String, merchant_id: String) { diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index c9e1cf14ce3..70112e27037 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -131,7 +131,7 @@ pub async fn payments_create( req_state, auth.merchant_account, auth.key_store, - payment_types::HeaderPayload::default(), + HeaderPayload::default(), req, api::AuthFlow::Merchant, ) @@ -420,7 +420,7 @@ pub async fn payments_update( req_state, auth.merchant_account, auth.key_store, - payment_types::HeaderPayload::default(), + HeaderPayload::default(), req, auth_flow, ) @@ -471,7 +471,7 @@ pub async fn payments_confirm( tracing::Span::current().record("payment_id", &payment_id); payload.payment_id = Some(payment_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); - let header_payload = match payment_types::HeaderPayload::foreign_try_from(req.headers()) { + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { Ok(headers) => headers, Err(err) => { return api::log_and_return_error_response(err); @@ -1019,7 +1019,7 @@ pub async fn payments_approve( api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, - payment_types::HeaderPayload::default(), + HeaderPayload::default(), ) }, match env::which() { @@ -1081,7 +1081,7 @@ pub async fn payments_reject( api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, - payment_types::HeaderPayload::default(), + HeaderPayload::default(), ) }, match env::which() { @@ -1107,7 +1107,7 @@ async fn authorize_verify_select<Op, Ctx>( header_payload: HeaderPayload, req: api_models::payments::PaymentsRequest, auth_flow: api::AuthFlow, -) -> app::core::errors::RouterResponse<api_models::payments::PaymentsResponse> +) -> errors::RouterResponse<api_models::payments::PaymentsResponse> where Ctx: PaymentMethodRetrieve, Op: Sync @@ -1530,8 +1530,10 @@ impl GetLockingInput for payment_types::PaymentsCaptureRequest { } } +#[cfg(feature = "oltp")] struct FPaymentsApproveRequest<'a>(&'a payment_types::PaymentsApproveRequest); +#[cfg(feature = "oltp")] impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where @@ -1548,8 +1550,10 @@ impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> { } } +#[cfg(feature = "oltp")] struct FPaymentsRejectRequest<'a>(&'a payment_types::PaymentsRejectRequest); +#[cfg(feature = "oltp")] impl<'a> GetLockingInput for FPaymentsRejectRequest<'a> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs index 7845f52c924..fc0794ff9e0 100644 --- a/crates/router/src/routes/recon.rs +++ b/crates/router/src/routes/recon.rs @@ -1,6 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::recon as recon_api; -use common_enums::ReconStatus; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use router_env::Flow; @@ -195,7 +194,7 @@ pub async fn recon_merchant_account_update( subject: "Approval of Recon Request - Access Granted to Recon Dashboard", }; - if req.recon_status == ReconStatus::Active { + if req.recon_status == enums::ReconStatus::Active { let _is_email_sent = state .email_client .compose_and_send_email( diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index a3f18168501..1ffb4dc8d1a 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -167,9 +167,10 @@ pub async fn set_dashboard_metadata( let flow = Flow::SetDashboardMetadata; let mut payload = json_payload.into_inner(); - if let Err(e) = common_utils::errors::ReportSwitchExt::<(), ApiErrorResponse>::switch( - set_ip_address_if_required(&mut payload, req.headers()), - ) { + if let Err(e) = ReportSwitchExt::<(), ApiErrorResponse>::switch(set_ip_address_if_required( + &mut payload, + req.headers(), + )) { return api::log_and_return_error_response(e); } diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index 073b1c57000..cdf680548a1 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -43,19 +43,3 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( )) .await } - -#[derive(Debug)] -struct WebhookBytes(web::Bytes); - -impl serde::Serialize for WebhookBytes { - fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { - let payload: serde_json::Value = serde_json::from_slice(&self.0).unwrap_or_default(); - payload.serialize(serializer) - } -} - -impl common_utils::events::ApiEventMetric for WebhookBytes { - fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { - Some(common_utils::events::ApiEventsType::Miscellaneous) - } -} diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 30c3ce164e2..cfe4fea11bb 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -273,7 +273,7 @@ pub enum CaptureSyncMethod { pub async fn execute_connector_processing_step< 'b, 'a, - T: 'static, + T, Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, >( @@ -284,7 +284,7 @@ pub async fn execute_connector_processing_step< connector_request: Option<Request>, ) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError> where - T: Clone + Debug, + T: Clone + Debug + 'static, // BoxedConnectorIntegration<T, Req, Resp>: 'b, { // If needed add an error stack as follows @@ -651,7 +651,7 @@ pub async fn send_request( } .add_headers(headers) .timeout(Duration::from_secs( - option_timeout_secs.unwrap_or(crate::consts::REQUEST_TIME_OUT), + option_timeout_secs.unwrap_or(consts::REQUEST_TIME_OUT), )) }; @@ -920,7 +920,7 @@ pub enum RedirectForm { impl From<(url::Url, Method)> for RedirectForm { fn from((mut redirect_url, method): (url::Url, Method)) -> Self { - let form_fields = std::collections::HashMap::from_iter( + let form_fields = HashMap::from_iter( redirect_url .query_pairs() .map(|(key, value)| (key.to_string(), value.to_string())), @@ -1127,10 +1127,7 @@ where if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) { acc.insert(key.clone(), value.clone()); } else { - acc.insert( - key.clone(), - http::header::HeaderValue::from_static("**MASKED**"), - ); + acc.insert(key.clone(), HeaderValue::from_static("**MASKED**")); } acc }); diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index 09b4d25d0b6..ae45a2a7fce 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -27,7 +27,7 @@ fn get_client_builder( ) -> CustomResult<reqwest::ClientBuilder, ApiClientError> { let mut client_builder = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) - .pool_idle_timeout(std::time::Duration::from_secs( + .pool_idle_timeout(Duration::from_secs( proxy_config .idle_pool_connection_timeout .unwrap_or_default(), diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 5f15474115d..9aac92acd2a 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -876,13 +876,13 @@ impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest { } } -impl ClientSecretFetch for api_models::payments::PaymentsRetrieveRequest { +impl ClientSecretFetch for payments::PaymentsRetrieveRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } } -impl ClientSecretFetch for api_models::payments::RetrievePaymentLinkRequest { +impl ClientSecretFetch for payments::RetrievePaymentLinkRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() } diff --git a/crates/router/src/services/pm_auth.rs b/crates/router/src/services/pm_auth.rs index 91b752aaf13..a54ba881995 100644 --- a/crates/router/src/services/pm_auth.rs +++ b/crates/router/src/services/pm_auth.rs @@ -11,22 +11,16 @@ use crate::{ services::{self}, }; -pub async fn execute_connector_processing_step< - 'b, - 'a, - T: 'static, - Req: Clone + 'static, - Resp: Clone + 'static, ->( +pub async fn execute_connector_processing_step<'b, 'a, T, Req, Resp>( state: &'b AppState, connector_integration: BoxedConnectorIntegration<'a, T, Req, Resp>, req: &'b PaymentAuthRouterData<T, Req, Resp>, connector: &pm_auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError> where - T: Clone, - Req: Clone, - Resp: Clone, + T: Clone + 'static, + Req: Clone + 'static, + Resp: Clone + 'static, { let mut router_data = req.clone(); diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs index 6f08a7fd7e4..e0ef95bcb0d 100644 --- a/crates/router/src/types/api/customers.rs +++ b/crates/router/src/types/api/customers.rs @@ -3,7 +3,7 @@ pub use api_models::customers::{CustomerDeleteResponse, CustomerId, CustomerRequ use serde::Serialize; use super::payments; -use crate::{core::errors::RouterResult, newtype, types::domain}; +use crate::{newtype, types::domain}; newtype!( pub CustomerResponse = customers::CustomerResponse, @@ -16,10 +16,6 @@ impl common_utils::events::ApiEventMetric for CustomerResponse { } } -pub(crate) trait CustomerRequestExt: Sized { - fn validate(self) -> RouterResult<Self>; -} - impl From<(domain::Customer, Option<payments::AddressDetails>)> for CustomerResponse { fn from((cust, address): (domain::Customer, Option<payments::AddressDetails>)) -> Self { customers::CustomerResponse { diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index e36c68c27d5..9f68cac98c9 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -21,20 +21,6 @@ use crate::{ types::{self, api as api_types}, }; -pub(crate) trait PaymentsRequestExt { - fn is_mandate(&self) -> Option<MandateTransactionType>; -} - -impl PaymentsRequestExt for PaymentsRequest { - fn is_mandate(&self) -> Option<MandateTransactionType> { - match (&self.mandate_data, &self.mandate_id) { - (None, None) => None, - (_, Some(_)) => Some(MandateTransactionType::RecurringMandateTransaction), - (Some(_), _) => Some(MandateTransactionType::NewMandateTransaction), - } - } -} - impl super::Router for PaymentsRequest {} // Core related api layer. diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 39891a7075d..af7cb9160b2 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -14,7 +14,7 @@ use crate::{ #[derive(Clone, Debug)] pub struct VerifyConnectorData { - pub connector: &'static (dyn types::api::Connector + Sync), + pub connector: &'static (dyn api::Connector + Sync), pub connector_auth: types::ConnectorAuthType, pub card_details: domain::Card, } @@ -155,11 +155,11 @@ pub trait VerifyConnector { } async fn handle_payment_error_response<F, R1, R2>( - connector: &(dyn types::api::Connector + Sync), + connector: &(dyn api::Connector + Sync), error_response: types::Response, ) -> errors::RouterResponse<()> where - dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, + dyn api::Connector + Sync: ConnectorIntegration<F, R1, R2>, { let error = connector .get_error_response(error_response, None) @@ -171,11 +171,11 @@ pub trait VerifyConnector { } async fn handle_access_token_error_response<F, R1, R2>( - connector: &(dyn types::api::Connector + Sync), + connector: &(dyn api::Connector + Sync), error_response: types::Response, ) -> errors::RouterResult<Option<types::AccessToken>> where - dyn types::api::Connector + Sync: ConnectorIntegration<F, R1, R2>, + dyn api::Connector + Sync: ConnectorIntegration<F, R1, R2>, { let error = connector .get_error_response(error_response, None) diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs index de95251d9d4..139cd105779 100644 --- a/crates/router/src/types/domain/customer.rs +++ b/crates/router/src/types/domain/customer.rs @@ -148,14 +148,14 @@ impl From<CustomerUpdate> for CustomerUpdateInternal { }, CustomerUpdate::ConnectorCustomer { connector_customer } => Self { connector_customer, - modified_at: Some(common_utils::date_time::now()), + modified_at: Some(date_time::now()), ..Default::default() }, CustomerUpdate::UpdateDefaultPaymentMethod { default_payment_method_id, } => Self { default_payment_method_id, - modified_at: Some(common_utils::date_time::now()), + modified_at: Some(date_time::now()), ..Default::default() }, } diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index c84abbefc38..0e7f5b081c3 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -195,7 +195,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte metadata, frm_configs: None, frm_config: frm_configs, - modified_at: Some(common_utils::date_time::now()), + modified_at: Some(date_time::now()), connector_webhook_details, applepay_verified_domains, pm_auth_config, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index ef12e32d57c..ce11251b83e 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -176,20 +176,18 @@ impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStat } } -impl ForeignFrom<api_models::payments::MandateType> for storage_enums::MandateDataType { - fn foreign_from(from: api_models::payments::MandateType) -> Self { +impl ForeignFrom<payments::MandateType> for storage_enums::MandateDataType { + fn foreign_from(from: payments::MandateType) -> Self { match from { - api_models::payments::MandateType::SingleUse(inner) => { - Self::SingleUse(inner.foreign_into()) - } - api_models::payments::MandateType::MultiUse(inner) => { + payments::MandateType::SingleUse(inner) => Self::SingleUse(inner.foreign_into()), + payments::MandateType::MultiUse(inner) => { Self::MultiUse(inner.map(ForeignInto::foreign_into)) } } } } -impl ForeignFrom<storage_enums::MandateDataType> for api_models::payments::MandateType { +impl ForeignFrom<storage_enums::MandateDataType> for payments::MandateType { fn foreign_from(from: storage_enums::MandateDataType) -> Self { match from { storage_enums::MandateDataType::SingleUse(inner) => { @@ -302,7 +300,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { } } -impl ForeignFrom<storage_enums::MandateAmountData> for api_models::payments::MandateAmountData { +impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountData { fn foreign_from(from: storage_enums::MandateAmountData) -> Self { Self { amount: from.amount, @@ -315,18 +313,16 @@ impl ForeignFrom<storage_enums::MandateAmountData> for api_models::payments::Man } // TODO: remove foreign from since this conversion won't be needed in the router crate once data models is treated as a single & primary source of truth for structure information -impl ForeignFrom<api_models::payments::MandateData> - for hyperswitch_domain_models::mandates::MandateData -{ - fn foreign_from(d: api_models::payments::MandateData) -> Self { +impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates::MandateData { + fn foreign_from(d: payments::MandateData) -> Self { Self { customer_acceptance: d.customer_acceptance.map(|d| { hyperswitch_domain_models::mandates::CustomerAcceptance { acceptance_type: match d.acceptance_type { - api_models::payments::AcceptanceType::Online => { + payments::AcceptanceType::Online => { hyperswitch_domain_models::mandates::AcceptanceType::Online } - api_models::payments::AcceptanceType::Offline => { + payments::AcceptanceType::Offline => { hyperswitch_domain_models::mandates::AcceptanceType::Offline } }, @@ -340,7 +336,7 @@ impl ForeignFrom<api_models::payments::MandateData> } }), mandate_type: d.mandate_type.map(|d| match d { - api_models::payments::MandateType::MultiUse(Some(i)) => { + payments::MandateType::MultiUse(Some(i)) => { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some( hyperswitch_domain_models::mandates::MandateAmountData { amount: i.amount, @@ -351,7 +347,7 @@ impl ForeignFrom<api_models::payments::MandateData> }, )) } - api_models::payments::MandateType::SingleUse(i) => { + payments::MandateType::SingleUse(i) => { hyperswitch_domain_models::mandates::MandateDataType::SingleUse( hyperswitch_domain_models::mandates::MandateAmountData { amount: i.amount, @@ -362,7 +358,7 @@ impl ForeignFrom<api_models::payments::MandateData> }, ) } - api_models::payments::MandateType::MultiUse(None) => { + payments::MandateType::MultiUse(None) => { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) } }), @@ -371,8 +367,8 @@ impl ForeignFrom<api_models::payments::MandateData> } } -impl ForeignFrom<api_models::payments::MandateAmountData> for storage_enums::MandateAmountData { - fn foreign_from(from: api_models::payments::MandateAmountData) -> Self { +impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountData { + fn foreign_from(from: payments::MandateAmountData) -> Self { Self { amount: from.amount, currency: from.currency, @@ -503,26 +499,27 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { } } -impl ForeignTryFrom<api_models::payments::PaymentMethodData> for api_enums::PaymentMethod { +impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod { type Error = errors::ApiErrorResponse; fn foreign_try_from( - payment_method_data: api_models::payments::PaymentMethodData, + payment_method_data: payments::PaymentMethodData, ) -> Result<Self, Self::Error> { match payment_method_data { - api_models::payments::PaymentMethodData::Card(..) - | api_models::payments::PaymentMethodData::CardToken(..) => Ok(Self::Card), - api_models::payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet), - api_models::payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater), - api_models::payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect), - api_models::payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit), - api_models::payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer), - api_models::payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto), - api_models::payments::PaymentMethodData::Reward => Ok(Self::Reward), - api_models::payments::PaymentMethodData::Upi(..) => Ok(Self::Upi), - api_models::payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher), - api_models::payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard), - api_models::payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect), - api_models::payments::PaymentMethodData::MandatePayment => { + payments::PaymentMethodData::Card(..) | payments::PaymentMethodData::CardToken(..) => { + Ok(Self::Card) + } + payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet), + payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater), + payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect), + payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit), + payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer), + payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto), + payments::PaymentMethodData::Reward => Ok(Self::Reward), + payments::PaymentMethodData::Upi(..) => Ok(Self::Upi), + payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher), + payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard), + payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect), + payments::PaymentMethodData::MandatePayment => { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("Mandate payments cannot have payment_method_data field".to_string()), }) @@ -902,7 +899,7 @@ impl TryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantCo } } -impl ForeignFrom<storage::PaymentAttempt> for api_models::payments::PaymentAttemptResponse { +impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self { Self { attempt_id: payment_attempt.attempt_id, @@ -929,7 +926,7 @@ impl ForeignFrom<storage::PaymentAttempt> for api_models::payments::PaymentAttem } } -impl ForeignFrom<storage::Capture> for api_models::payments::CaptureResponse { +impl ForeignFrom<storage::Capture> for payments::CaptureResponse { fn foreign_from(capture: storage::Capture) -> Self { Self { capture_id: capture.capture_id, @@ -1003,7 +1000,7 @@ impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod { } } -impl ForeignTryFrom<&HeaderMap> for api_models::payments::HeaderPayload { +impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> { let payment_confirm_source: Option<api_enums::PaymentSource> = @@ -1047,7 +1044,7 @@ impl Option<&domain::Address>, Option<&domain::Address>, Option<&domain::Customer>, - )> for api_models::payments::PaymentsRequest + )> for payments::PaymentsRequest { fn foreign_from( value: ( @@ -1072,17 +1069,11 @@ impl } } -impl - ForeignFrom<( - storage::PaymentLink, - api_models::payments::PaymentLinkStatus, - )> for api_models::payments::RetrievePaymentLinkResponse +impl ForeignFrom<(storage::PaymentLink, payments::PaymentLinkStatus)> + for payments::RetrievePaymentLinkResponse { fn foreign_from( - (payment_link_config, status): ( - storage::PaymentLink, - api_models::payments::PaymentLinkStatus, - ), + (payment_link_config, status): (storage::PaymentLink, payments::PaymentLinkStatus), ) -> Self { Self { payment_link_id: payment_link_config.payment_link_id, @@ -1171,7 +1162,7 @@ impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { } } -impl ForeignFrom<&domain::Customer> for api_models::payments::CustomerDetails { +impl ForeignFrom<&domain::Customer> for payments::CustomerDetails { fn foreign_from(customer: &domain::Customer) -> Self { Self { id: customer.customer_id.clone(), diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 341c560e4d2..51854978b9e 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -99,7 +99,7 @@ pub mod error_parser { } pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error { - actix_web::error::Error::from(CustomJsonError { err }) + Error::from(CustomJsonError { err }) } } @@ -565,14 +565,14 @@ pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { pub trait CustomerAddress { async fn get_address_update( &self, - address_details: api_models::payments::AddressDetails, + address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, - address_details: api_models::payments::AddressDetails, + address_details: payments::AddressDetails, merchant_id: &str, customer_id: &str, key: &[u8], @@ -584,7 +584,7 @@ pub trait CustomerAddress { impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, - address_details: api_models::payments::AddressDetails, + address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { @@ -640,7 +640,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_domain_address( &self, - address_details: api_models::payments::AddressDetails, + address_details: payments::AddressDetails, merchant_id: &str, customer_id: &str, key: &[u8], diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 912f8fce94c..5cf68635c4e 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -525,10 +525,10 @@ pub async fn convert_currency( .await .change_context(ForexCacheError::ApiError)?; - let to_currency = api_models::enums::Currency::from_str(to_currency.as_str()) + let to_currency = enums::Currency::from_str(to_currency.as_str()) .change_context(ForexCacheError::CurrencyNotAcceptable)?; - let from_currency = api_models::enums::Currency::from_str(from_currency.as_str()) + let from_currency = enums::Currency::from_str(from_currency.as_str()) .change_context(ForexCacheError::CurrencyNotAcceptable)?; let converted_amount = diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index bde0fb72bd3..33e9aa6769c 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -11,7 +11,7 @@ use crate::{ routes::AppState, services::{ authentication::{AuthToken, UserFromToken}, - authorization::roles::{self, RoleInfo}, + authorization::roles::RoleInfo, }, types::domain::{self, MerchantAccount, UserFromStorage}, }; @@ -64,7 +64,7 @@ impl UserFromToken { } pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> { - roles::RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id) + RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id) .await .change_context(UserErrors::InternalServerError) } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 710d90a4ea3..2e5e8748f48 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -46,7 +46,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }), confirm: true, statement_descriptor_suffix: None, @@ -263,7 +263,7 @@ async fn payments_create_failure() { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }); let response = services::api::execute_connector_processing_step( diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 468834ca495..d19fff29003 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -151,7 +151,7 @@ impl AdyenTest { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }), confirm: true, statement_descriptor_suffix: None, diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index 95b07162ac3..2ef61099ca7 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -70,7 +70,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4035501000000008").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), @@ -80,7 +80,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), router_return_url: Some("https://google.com".to_string()), @@ -143,7 +143,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -272,7 +272,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -370,7 +370,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), @@ -393,7 +393,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -416,7 +416,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -439,7 +439,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 2b9a79b0b7b..4c724f368d7 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -55,9 +55,7 @@ async fn should_only_authorize_payment() { .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 300, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), @@ -72,7 +70,7 @@ async fn should_only_authorize_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() @@ -92,9 +90,7 @@ async fn should_capture_authorized_payment() { .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 301, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), @@ -109,9 +105,7 @@ async fn should_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - txn_id.clone(), - ), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() @@ -137,7 +131,7 @@ async fn should_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::CaptureInitiated, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() @@ -156,9 +150,7 @@ async fn should_partially_capture_authorized_payment() { .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 302, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), @@ -173,9 +165,7 @@ async fn should_partially_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - txn_id.clone(), - ), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() @@ -201,7 +191,7 @@ async fn should_partially_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::CaptureInitiated, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() @@ -220,9 +210,7 @@ async fn should_sync_authorized_payment() { .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 303, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), @@ -237,7 +225,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, ..Default::default() @@ -256,9 +244,7 @@ async fn should_void_authorized_payment() { .authorize_payment( Some(types::PaymentsAuthorizeData { amount: 304, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), @@ -273,9 +259,7 @@ async fn should_void_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - txn_id.clone(), - ), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() @@ -307,9 +291,7 @@ async fn should_make_payment() { .make_payment( Some(types::PaymentsAuthorizeData { amount: 310, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), @@ -323,9 +305,7 @@ async fn should_make_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::CaptureInitiated, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( - txn_id.clone(), - ), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()), encoded_data: None, capture_method: None, ..Default::default() @@ -347,9 +327,7 @@ async fn should_sync_auto_captured_payment() { .make_payment( Some(types::PaymentsAuthorizeData { amount: 311, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), @@ -364,7 +342,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -402,7 +380,7 @@ async fn should_fail_payment_for_empty_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("").unwrap(), ..utils::CCardType::default().0 }), @@ -425,7 +403,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -448,7 +426,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -470,7 +448,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), @@ -493,9 +471,7 @@ async fn should_fail_void_payment_for_auto_capture() { .make_payment( Some(types::PaymentsAuthorizeData { amount: 307, - payment_method_data: types::domain::PaymentMethodData::Card( - get_payment_method_data(), - ), + payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs index 5cd82d097aa..3115c1143d7 100644 --- a/crates/router/tests/connectors/bambora.rs +++ b/crates/router/tests/connectors/bambora.rs @@ -40,7 +40,7 @@ static CONNECTOR: BamboraTest = BamboraTest {}; fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4030000010001234").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), @@ -101,7 +101,7 @@ async fn should_sync_authorized_payment() { enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { mandate_id: None, - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -217,7 +217,7 @@ async fn should_sync_auto_captured_payment() { enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { mandate_id: None, - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -296,7 +296,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), card_exp_year: Secret::new("25".to_string()), ..utils::CCardType::default().0 @@ -319,7 +319,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 @@ -342,7 +342,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), card_number: cards::CardNumber::from_str("4030000010001234").unwrap(), card_exp_year: Secret::new("25".to_string()), @@ -367,7 +367,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), card_number: cards::CardNumber::from_str("4030000010001234").unwrap(), card_cvc: Secret::new("123".to_string()), diff --git a/crates/router/tests/connectors/bankofamerica.rs b/crates/router/tests/connectors/bankofamerica.rs index ca54e9c97b9..77085216dd5 100644 --- a/crates/router/tests/connectors/bankofamerica.rs +++ b/crates/router/tests/connectors/bankofamerica.rs @@ -93,7 +93,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -213,7 +213,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -303,7 +303,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -325,7 +325,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -347,7 +347,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/billwerk.rs b/crates/router/tests/connectors/billwerk.rs index 6795aa40115..4c992ef3d92 100644 --- a/crates/router/tests/connectors/billwerk.rs +++ b/crates/router/tests/connectors/billwerk.rs @@ -93,7 +93,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -213,7 +213,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index df82775d6cf..85b388f2fdb 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -10,12 +10,12 @@ use crate::{ struct BitpayTest; impl ConnectorActions for BitpayTest {} impl utils::Connector for BitpayTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Bitpay; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Bitpay), connector_name: types::Connector::Bitpay, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -67,7 +67,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, - payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData { + payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, }), confirm: true, @@ -126,7 +126,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "NPf27TDfyU5mhcTCw2oaq4".to_string(), ), ..Default::default() @@ -145,7 +145,7 @@ async fn should_sync_expired_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "bUsFf4RjQEahjbjGcETRS".to_string(), ), ..Default::default() diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs index 2e02f259341..3a654eda839 100644 --- a/crates/router/tests/connectors/bluesnap.rs +++ b/crates/router/tests/connectors/bluesnap.rs @@ -121,7 +121,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -261,7 +261,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -401,7 +401,7 @@ async fn should_fail_payment_for_incorrect_cvc() { .make_payment( Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("[email protected]").unwrap()), - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -426,7 +426,7 @@ async fn should_fail_payment_for_invalid_exp_month() { .make_payment( Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("[email protected]").unwrap()), - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -451,7 +451,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { .make_payment( Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("[email protected]").unwrap()), - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/boku.rs b/crates/router/tests/connectors/boku.rs index 2f496562e1d..f361a2365d5 100644 --- a/crates/router/tests/connectors/boku.rs +++ b/crates/router/tests/connectors/boku.rs @@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 616a080699b..025d9cdac64 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -39,7 +39,7 @@ static CONNECTOR: CashtocodeTest = CashtocodeTest {}; impl CashtocodeTest { fn get_payment_authorize_data( payment_method_type: Option<enums::PaymentMethodType>, - payment_method_data: types::domain::PaymentMethodData, + payment_method_data: domain::PaymentMethodData, ) -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1000, diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index 85b55afc8ea..886239878f2 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -97,7 +97,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -223,7 +223,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -320,7 +320,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -343,7 +343,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -366,7 +366,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 0136284c826..0bcb3c705ab 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -11,12 +11,12 @@ use crate::{ struct CoinbaseTest; impl ConnectorActions for CoinbaseTest {} impl utils::Connector for CoinbaseTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Coinbase; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Coinbase), connector_name: types::Connector::Coinbase, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -69,7 +69,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, - payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData { + payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, }), confirm: true, @@ -128,7 +128,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "ADFY3789".to_string(), ), ..Default::default() @@ -147,7 +147,7 @@ async fn should_sync_unresolved_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "YJ6RFZXZ".to_string(), ), ..Default::default() @@ -166,7 +166,7 @@ async fn should_sync_expired_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "FZ89KDDB".to_string(), ), ..Default::default() @@ -185,7 +185,7 @@ async fn should_sync_cancelled_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "C35AAXKF".to_string(), ), ..Default::default() diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index 56c0e29f621..626c05fe114 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -10,12 +10,12 @@ use crate::{ struct CryptopayTest; impl ConnectorActions for CryptopayTest {} impl utils::Connector for CryptopayTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Cryptopay; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Cryptopay), connector_name: types::Connector::Cryptopay, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -68,7 +68,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, - payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData { + payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: Some("XRP".to_string()), }), confirm: true, @@ -126,7 +126,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "ea684036-2b54-44fa-bffe-8256650dce7c".to_string(), ), ..Default::default() @@ -145,7 +145,7 @@ async fn should_sync_unresolved_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "7993d4c2-efbc-4360-b8ce-d1e957e6f827".to_string(), ), ..Default::default() diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs index 98ec44abd8a..700e9a2d946 100644 --- a/crates/router/tests/connectors/cybersource.rs +++ b/crates/router/tests/connectors/cybersource.rs @@ -2,10 +2,7 @@ use std::str::FromStr; use common_utils::pii::Email; use masking::Secret; -use router::types::{ - self, api, domain, - storage::{self, enums}, -}; +use router::types::{self, api, domain, storage::enums}; use crate::{ connector_auth, @@ -14,12 +11,12 @@ use crate::{ struct Cybersource; impl ConnectorActions for Cybersource {} impl utils::Connector for Cybersource { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Cybersource; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Cybersource), connector_name: types::Connector::Cybersource, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -64,7 +61,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { } fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - currency: storage::enums::Currency::USD, + currency: enums::Currency::USD, email: Some(Email::from_str("[email protected]").unwrap()), ..PaymentAuthorizeType::default().0 }) @@ -127,7 +124,7 @@ async fn should_sync_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "6699597903496176903954".to_string(), ), ..Default::default() @@ -160,7 +157,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), @@ -185,7 +182,7 @@ async fn should_fail_payment_for_invalid_exp_year() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2022".to_string()), ..utils::CCardType::default().0 }), @@ -203,7 +200,7 @@ async fn should_fail_payment_for_invalid_card_cvc() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("2131233213".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs index edb24646bcb..b715e20fec4 100644 --- a/crates/router/tests/connectors/dlocal.rs +++ b/crates/router/tests/connectors/dlocal.rs @@ -13,12 +13,12 @@ use crate::{ struct DlocalTest; impl ConnectorActions for DlocalTest {} impl utils::Connector for DlocalTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Dlocal; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Dlocal), connector_name: types::Connector::Dlocal, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -89,7 +89,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -200,7 +200,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -289,7 +289,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1891011").unwrap(), ..utils::CCardType::default().0 }), @@ -310,7 +310,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("1ad2345".to_string()), ..utils::CCardType::default().0 }), @@ -331,7 +331,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("201".to_string()), ..utils::CCardType::default().0 }), @@ -352,7 +352,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("20001".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/dummyconnector.rs b/crates/router/tests/connectors/dummyconnector.rs index 76f72b64907..e357eda94c4 100644 --- a/crates/router/tests/connectors/dummyconnector.rs +++ b/crates/router/tests/connectors/dummyconnector.rs @@ -95,7 +95,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -215,7 +215,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -305,7 +305,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), @@ -327,7 +327,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -349,7 +349,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -371,7 +371,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/ebanx.rs b/crates/router/tests/connectors/ebanx.rs index 8571ed1e3f8..6f02c80ebde 100644 --- a/crates/router/tests/connectors/ebanx.rs +++ b/crates/router/tests/connectors/ebanx.rs @@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 050d6a54067..f95c0d276ec 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -42,7 +42,7 @@ impl utils::Connector for FiservTest { fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), @@ -52,7 +52,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -123,7 +123,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -252,7 +252,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -347,7 +347,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), @@ -370,7 +370,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -393,7 +393,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -416,7 +416,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs index c58cab38a22..1c99c2ff7b5 100644 --- a/crates/router/tests/connectors/forte.rs +++ b/crates/router/tests/connectors/forte.rs @@ -13,12 +13,12 @@ use crate::{ struct ForteTest; impl ConnectorActions for ForteTest {} impl utils::Connector for ForteTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Forte; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Forte), connector_name: types::Connector::Forte, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -41,7 +41,7 @@ static CONNECTOR: ForteTest = ForteTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), @@ -148,7 +148,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -319,7 +319,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -467,7 +467,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -489,7 +489,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -512,7 +512,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), @@ -630,7 +630,7 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() { #[actix_web::test] async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("6759649826438453").unwrap(), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/globalpay.rs b/crates/router/tests/connectors/globalpay.rs index e2ca19869f5..8ca4d6f1ae3 100644 --- a/crates/router/tests/connectors/globalpay.rs +++ b/crates/router/tests/connectors/globalpay.rs @@ -13,12 +13,12 @@ struct Globalpay; impl ConnectorActions for Globalpay {} static CONNECTOR: Globalpay = Globalpay {}; impl Connector for Globalpay { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Globalpay; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Globalpay), connector_name: types::Connector::Globalpay, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -42,7 +42,7 @@ impl Connector for Globalpay { } fn get_access_token() -> Option<AccessToken> { - match utils::Connector::get_auth_token(&CONNECTOR) { + match Connector::get_auth_token(&CONNECTOR) { ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken { token: api_key, expires: 18600, @@ -120,7 +120,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -137,7 +137,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), @@ -345,7 +345,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), @@ -367,7 +367,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -410,7 +410,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() diff --git a/crates/router/tests/connectors/globepay.rs b/crates/router/tests/connectors/globepay.rs index 70167970210..34a2ecb4c88 100644 --- a/crates/router/tests/connectors/globepay.rs +++ b/crates/router/tests/connectors/globepay.rs @@ -94,7 +94,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -214,7 +214,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -304,7 +304,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -326,7 +326,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -348,7 +348,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/gocardless.rs b/crates/router/tests/connectors/gocardless.rs index 0564ea7da6d..f7f2ed864bf 100644 --- a/crates/router/tests/connectors/gocardless.rs +++ b/crates/router/tests/connectors/gocardless.rs @@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/helcim.rs b/crates/router/tests/connectors/helcim.rs index dc3bb4d47e6..7bb4b9ab785 100644 --- a/crates/router/tests/connectors/helcim.rs +++ b/crates/router/tests/connectors/helcim.rs @@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/iatapay.rs b/crates/router/tests/connectors/iatapay.rs index d685756094e..dfb8e097be3 100644 --- a/crates/router/tests/connectors/iatapay.rs +++ b/crates/router/tests/connectors/iatapay.rs @@ -12,12 +12,12 @@ use crate::{ struct IatapayTest; impl ConnectorActions for IatapayTest {} impl Connector for IatapayTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Iatapay; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Iatapay), connector_name: types::Connector::Iatapay, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -155,7 +155,7 @@ async fn should_sync_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "PE9OTYNP639XW".to_string(), ), ..Default::default() diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index eb1c00a227b..78e67b7670a 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -62,6 +62,7 @@ mod trustpay; mod tsys; mod utils; mod volt; +#[cfg(feature = "payouts")] mod wise; mod worldline; mod worldpay; diff --git a/crates/router/tests/connectors/mollie.rs b/crates/router/tests/connectors/mollie.rs index 14c77e2a9f0..be0b5d1c1d7 100644 --- a/crates/router/tests/connectors/mollie.rs +++ b/crates/router/tests/connectors/mollie.rs @@ -5,6 +5,7 @@ use crate::{ utils::{self, ConnectorActions}, }; +#[allow(dead_code)] #[derive(Clone, Copy)] struct MollieTest; impl ConnectorActions for MollieTest {} diff --git a/crates/router/tests/connectors/multisafepay.rs b/crates/router/tests/connectors/multisafepay.rs index f35fe05bf36..606b60b2490 100644 --- a/crates/router/tests/connectors/multisafepay.rs +++ b/crates/router/tests/connectors/multisafepay.rs @@ -59,7 +59,7 @@ fn get_default_payment_info() -> Option<PaymentInfo> { )); Some(PaymentInfo { address, - ..utils::PaymentInfo::default() + ..PaymentInfo::default() }) } @@ -121,7 +121,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -237,7 +237,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -331,7 +331,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("123498765".to_string()), ..utils::CCardType::default().0 }), @@ -350,7 +350,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -369,7 +369,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/netcetera.rs b/crates/router/tests/connectors/netcetera.rs index f06e2a0f5d7..d7fceca9c5d 100644 --- a/crates/router/tests/connectors/netcetera.rs +++ b/crates/router/tests/connectors/netcetera.rs @@ -91,7 +91,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -211,7 +211,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs index 5948855ae8d..cdf94113c5a 100644 --- a/crates/router/tests/connectors/nexinets.rs +++ b/crates/router/tests/connectors/nexinets.rs @@ -41,7 +41,7 @@ impl utils::Connector for NexinetsTest { fn payment_method_details() -> Option<PaymentsAuthorizeData> { Some(PaymentsAuthorizeData { currency: diesel_models::enums::Currency::EUR, - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("374111111111111").unwrap(), ..utils::CCardType::default().0 }), @@ -118,7 +118,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, @@ -341,7 +341,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), capture_method: Some(enums::CaptureMethod::Automatic), connector_meta, ..Default::default() @@ -506,7 +506,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -528,7 +528,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -550,7 +550,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/nmi.rs b/crates/router/tests/connectors/nmi.rs index 5b569fa497f..1d719e052a0 100644 --- a/crates/router/tests/connectors/nmi.rs +++ b/crates/router/tests/connectors/nmi.rs @@ -38,7 +38,7 @@ static CONNECTOR: NmiTest = NmiTest {}; fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), @@ -60,10 +60,10 @@ async fn should_only_authorize_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -87,10 +87,10 @@ async fn should_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -110,10 +110,10 @@ async fn should_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -136,10 +136,10 @@ async fn should_partially_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -167,10 +167,10 @@ async fn should_partially_capture_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -194,10 +194,10 @@ async fn should_void_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -223,10 +223,10 @@ async fn should_void_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Voided, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -250,10 +250,10 @@ async fn should_refund_manually_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -273,10 +273,10 @@ async fn should_refund_manually_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -319,10 +319,10 @@ async fn should_partially_refund_manually_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -349,10 +349,10 @@ async fn should_partially_refund_manually_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -402,10 +402,10 @@ async fn should_make_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, @@ -429,10 +429,10 @@ async fn should_refund_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, @@ -475,10 +475,10 @@ async fn should_partially_refund_succeeded_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, @@ -528,10 +528,10 @@ async fn should_refund_succeeded_payment_multiple_times() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, @@ -600,10 +600,10 @@ async fn should_fail_void_payment_for_auto_capture() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, @@ -633,10 +633,10 @@ async fn should_fail_capture_for_invalid_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Manual), + capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, @@ -665,10 +665,10 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() { .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), - capture_method: Some(types::storage::enums::CaptureMethod::Automatic), + capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, diff --git a/crates/router/tests/connectors/noon.rs b/crates/router/tests/connectors/noon.rs index 7e0bb954c6c..47e76d5ec76 100644 --- a/crates/router/tests/connectors/noon.rs +++ b/crates/router/tests/connectors/noon.rs @@ -1,10 +1,7 @@ use std::str::FromStr; use masking::Secret; -use router::types::{ - self, - storage::{self, enums}, -}; +use router::types::{self, storage::enums}; use crate::{ connector_auth, @@ -47,7 +44,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - currency: storage::enums::Currency::AED, + currency: enums::Currency::AED, ..utils::PaymentAuthorizeType::default().0 }) } @@ -102,7 +99,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -222,7 +219,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), diff --git a/crates/router/tests/connectors/nuvei.rs b/crates/router/tests/connectors/nuvei.rs index 04a83b3a606..55a8f234219 100644 --- a/crates/router/tests/connectors/nuvei.rs +++ b/crates/router/tests/connectors/nuvei.rs @@ -1,10 +1,7 @@ use std::str::FromStr; use masking::Secret; -use router::types::{ - self, - storage::{self, enums}, -}; +use router::types::{self, storage::enums}; use serde_json::json; use crate::{ @@ -102,7 +99,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), connector_meta: Some(json!({ @@ -126,7 +123,7 @@ async fn should_void_authorized_payment() { Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), amount: Some(100), - currency: Some(storage::enums::Currency::USD), + currency: Some(enums::Currency::USD), ..Default::default() }), None, @@ -194,7 +191,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), connector_meta: Some(json!({ @@ -345,7 +342,7 @@ async fn should_fail_void_payment_for_auto_capture() { Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), amount: Some(100), - currency: Some(storage::enums::Currency::USD), + currency: Some(enums::Currency::USD), ..Default::default() }), None, diff --git a/crates/router/tests/connectors/opayo.rs b/crates/router/tests/connectors/opayo.rs index f4badf9b116..b383a2e1b0e 100644 --- a/crates/router/tests/connectors/opayo.rs +++ b/crates/router/tests/connectors/opayo.rs @@ -97,7 +97,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -217,7 +217,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -307,7 +307,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), @@ -329,7 +329,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -351,7 +351,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -373,7 +373,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index e4d347c26d1..c91126953de 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -10,12 +10,12 @@ use crate::{ struct OpennodeTest; impl ConnectorActions for OpennodeTest {} impl utils::Connector for OpennodeTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Opennode; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Opennode), connector_name: types::Connector::Opennode, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -68,7 +68,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, - payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData { + payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, }), confirm: true, @@ -127,7 +127,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "5adebfb1-802e-432b-8b42-5db4b754b2eb".to_string(), ), ..Default::default() @@ -146,7 +146,7 @@ async fn should_sync_unresolved_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "4cf63e6b-5135-49cb-997f-6e0b30fecebc".to_string(), ), ..Default::default() @@ -165,7 +165,7 @@ async fn should_sync_expired_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "c36a097a-5091-4317-8749-80343a71c1c4".to_string(), ), ..Default::default() diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index a1682001488..234f3a0eeb8 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -91,7 +91,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("[email protected]").unwrap()), - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_cvc: Secret::new("123".to_string()), card_exp_month: Secret::new("10".to_string()), @@ -155,7 +155,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -280,7 +280,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -372,7 +372,7 @@ async fn should_fail_payment_for_incorrect_cvc() { Some(types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::ILS, - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -391,7 +391,7 @@ async fn should_fail_payment_for_incorrect_cvc() { router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("[email protected]").unwrap()), - ..utils::PaymentAuthorizeType::default().0 + ..PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) @@ -411,7 +411,7 @@ async fn should_fail_payment_for_invalid_exp_month() { Some(types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::ILS, - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -430,7 +430,7 @@ async fn should_fail_payment_for_invalid_exp_month() { router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("[email protected]").unwrap()), - ..utils::PaymentAuthorizeType::default().0 + ..PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) @@ -450,7 +450,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { Some(types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::ILS, - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2012".to_string()), ..utils::CCardType::default().0 }), @@ -469,7 +469,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("[email protected]").unwrap()), - ..utils::PaymentAuthorizeType::default().0 + ..PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs index bded135f45d..704aeca5936 100644 --- a/crates/router/tests/connectors/paypal.rs +++ b/crates/router/tests/connectors/paypal.rs @@ -56,7 +56,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4000020000000000").unwrap(), ..utils::CCardType::default().0 }), @@ -136,7 +136,7 @@ async fn should_sync_authorized_payment() { enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { mandate_id: None, - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(txn_id), + connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, @@ -332,7 +332,7 @@ async fn should_sync_auto_captured_payment() { enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { mandate_id: None, - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -450,7 +450,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -476,7 +476,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -502,7 +502,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs index fc916e33677..2f6ebcefe6a 100644 --- a/crates/router/tests/connectors/payu.rs +++ b/crates/router/tests/connectors/payu.rs @@ -70,7 +70,7 @@ async fn should_authorize_card_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), ..Default::default() @@ -115,7 +115,7 @@ async fn should_authorize_gpay_payment() { let sync_response = Payu {} .sync_payment( Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), ..Default::default() @@ -148,7 +148,7 @@ async fn should_capture_already_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), ..Default::default() @@ -167,7 +167,7 @@ async fn should_capture_already_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id, ), ..Default::default() @@ -203,7 +203,7 @@ async fn should_sync_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id, ), ..Default::default() @@ -246,7 +246,7 @@ async fn should_void_already_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Voided, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id, ), ..Default::default() @@ -280,7 +280,7 @@ async fn should_refund_succeeded_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), ..Default::default() @@ -301,7 +301,7 @@ async fn should_refund_succeeded_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), ..Default::default() diff --git a/crates/router/tests/connectors/placetopay.rs b/crates/router/tests/connectors/placetopay.rs index 41675b9751b..d9b75cbe0e8 100644 --- a/crates/router/tests/connectors/placetopay.rs +++ b/crates/router/tests/connectors/placetopay.rs @@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/powertranz.rs b/crates/router/tests/connectors/powertranz.rs index 0701ec006d9..7f1e1937e05 100644 --- a/crates/router/tests/connectors/powertranz.rs +++ b/crates/router/tests/connectors/powertranz.rs @@ -96,7 +96,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -218,7 +218,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -310,7 +310,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -332,7 +332,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -354,7 +354,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/prophetpay.rs b/crates/router/tests/connectors/prophetpay.rs index 9a0e2dbfa0e..5e326c0bcd3 100644 --- a/crates/router/tests/connectors/prophetpay.rs +++ b/crates/router/tests/connectors/prophetpay.rs @@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index 61bc7ccdf15..4b5357c51ec 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -42,7 +42,7 @@ async fn should_only_authorize_payment() { let response = Rapyd {} .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), @@ -52,7 +52,7 @@ async fn should_only_authorize_payment() { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 @@ -69,7 +69,7 @@ async fn should_authorize_and_capture_payment() { let response = Rapyd {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), @@ -79,7 +79,7 @@ async fn should_authorize_and_capture_payment() { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }), ..utils::PaymentAuthorizeType::default().0 }), @@ -157,7 +157,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = Rapyd {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("0000000000000000").unwrap(), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs index 8f11fbfa1d8..632e5389351 100644 --- a/crates/router/tests/connectors/shift4.rs +++ b/crates/router/tests/connectors/shift4.rs @@ -90,7 +90,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -114,7 +114,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -151,7 +151,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), @@ -173,7 +173,7 @@ async fn should_succeed_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("asdasd".to_string()), //shift4 accept invalid CVV as it doesn't accept CVV ..utils::CCardType::default().0 }), @@ -192,7 +192,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -214,7 +214,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/square.rs b/crates/router/tests/connectors/square.rs index 01d90c73c42..2dcd93cc105 100644 --- a/crates/router/tests/connectors/square.rs +++ b/crates/router/tests/connectors/square.rs @@ -1,11 +1,7 @@ use std::{str::FromStr, time::Duration}; use masking::Secret; -use router::types::{ - self, - storage::{self, enums}, - PaymentsResponseData, -}; +use router::types::{self, storage::enums, PaymentsResponseData}; use test_utils::connector_auth::ConnectorAuthentication; use crate::utils::{self, get_connector_transaction_id, Connector, ConnectorActions}; @@ -71,7 +67,7 @@ fn token_details() -> Option<types::PaymentMethodTokenizationData> { }), browser_info: None, amount: None, - currency: storage::enums::Currency::USD, + currency: enums::Currency::USD, }) } @@ -147,7 +143,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -291,7 +287,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -444,7 +440,7 @@ async fn should_fail_payment_for_incorrect_cvc() { }), browser_info: None, amount: None, - currency: storage::enums::Currency::USD, + currency: enums::Currency::USD, }), get_default_payment_info(None), ) @@ -475,7 +471,7 @@ async fn should_fail_payment_for_invalid_exp_month() { }), browser_info: None, amount: None, - currency: storage::enums::Currency::USD, + currency: enums::Currency::USD, }), get_default_payment_info(None), ) @@ -506,7 +502,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { }), browser_info: None, amount: None, - currency: storage::enums::Currency::USD, + currency: enums::Currency::USD, }), get_default_payment_info(None), ) diff --git a/crates/router/tests/connectors/stax.rs b/crates/router/tests/connectors/stax.rs index d16f209a49a..421ad9524c3 100644 --- a/crates/router/tests/connectors/stax.rs +++ b/crates/router/tests/connectors/stax.rs @@ -63,7 +63,7 @@ fn customer_details() -> Option<types::ConnectorCustomerData> { fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), @@ -167,7 +167,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -344,7 +344,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -473,7 +473,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), @@ -511,7 +511,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), @@ -549,7 +549,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2000".to_string()), diff --git a/crates/router/tests/connectors/stripe.rs b/crates/router/tests/connectors/stripe.rs index 3dcaeba45b0..2d6b3e0cfd3 100644 --- a/crates/router/tests/connectors/stripe.rs +++ b/crates/router/tests/connectors/stripe.rs @@ -37,7 +37,7 @@ impl utils::Connector for Stripe { fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4242424242424242").unwrap(), ..utils::CCardType::default().0 }), @@ -100,7 +100,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -124,7 +124,7 @@ async fn should_sync_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -158,7 +158,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), @@ -180,7 +180,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), @@ -202,7 +202,7 @@ async fn should_fail_payment_for_invalid_exp_year() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2022".to_string()), ..utils::CCardType::default().0 }), @@ -221,7 +221,7 @@ async fn should_fail_payment_for_invalid_card_cvc() { let response = Stripe {} .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/trustpay.rs b/crates/router/tests/connectors/trustpay.rs index 48cd165767c..fba612863b4 100644 --- a/crates/router/tests/connectors/trustpay.rs +++ b/crates/router/tests/connectors/trustpay.rs @@ -12,12 +12,12 @@ use crate::{ struct TrustpayTest; impl ConnectorActions for TrustpayTest {} impl utils::Connector for TrustpayTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Trustpay; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Trustpay), connector_name: types::Connector::Trustpay, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } @@ -53,7 +53,7 @@ fn get_default_browser_info() -> BrowserInformation { fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), @@ -122,7 +122,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -182,7 +182,7 @@ async fn should_sync_refund() { #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let payment_authorize_data = types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), @@ -205,7 +205,7 @@ async fn should_fail_payment_for_incorrect_card_number() { #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let payment_authorize_data = Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("22".to_string()), card_cvc: Secret::new("123".to_string()), diff --git a/crates/router/tests/connectors/tsys.rs b/crates/router/tests/connectors/tsys.rs index d7a688bd128..ef4f576ad9e 100644 --- a/crates/router/tests/connectors/tsys.rs +++ b/crates/router/tests/connectors/tsys.rs @@ -46,7 +46,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> { fn payment_method_details(amount: i64) -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount, - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), @@ -108,7 +108,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -244,7 +244,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("".to_string()), ..utils::CCardType::default().0 }), @@ -368,7 +368,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -390,7 +390,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("abcd".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 9678eca73f3..3196c4c763b 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -8,7 +8,7 @@ use masking::Secret; use router::core::utils as core_utils; use router::{ configs::settings::Settings, - core::{errors, errors::ConnectorError, payments}, + core::{errors::ConnectorError, payments}, db::StorageImpl, routes, services, types::{self, storage::enums, AccessToken, PaymentAddress, RouterData}, @@ -57,7 +57,7 @@ pub struct PaymentInfo { impl PaymentInfo { pub fn with_default_billing_name() -> Self { Self { - address: Some(types::PaymentAddress::new( + address: Some(PaymentAddress::new( None, None, Some(types::api::Address { @@ -215,7 +215,7 @@ pub trait ConnectorActions: Connector { } tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; } - Err(errors::ConnectorError::ProcessingStepFailed(None).into()) + Err(ConnectorError::ProcessingStepFailed(None).into()) } async fn capture_payment( @@ -453,7 +453,7 @@ pub trait ConnectorActions: Connector { } tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; } - Err(errors::ConnectorError::ProcessingStepFailed(None).into()) + Err(ConnectorError::ProcessingStepFailed(None).into()) } #[cfg(feature = "payouts")] @@ -523,7 +523,7 @@ pub trait ConnectorActions: Connector { .unwrap(), connector_meta_data: info .clone() - .and_then(|a| a.connector_meta_data.map(masking::Secret::new)), + .and_then(|a| a.connector_meta_data.map(Secret::new)), amount_captured: None, access_token: info.clone().and_then(|a| a.access_token), session_token: None, @@ -902,7 +902,7 @@ impl Default for CCardType { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }) } } diff --git a/crates/router/tests/connectors/volt.rs b/crates/router/tests/connectors/volt.rs index 7bcdf63d918..efe6d603e70 100644 --- a/crates/router/tests/connectors/volt.rs +++ b/crates/router/tests/connectors/volt.rs @@ -92,7 +92,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() @@ -212,7 +212,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), @@ -302,7 +302,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -324,7 +324,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -346,7 +346,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rs index b85fb4f1c96..fd5bbc109d9 100644 --- a/crates/router/tests/connectors/wise.rs +++ b/crates/router/tests/connectors/wise.rs @@ -1,38 +1,36 @@ -#[cfg(feature = "payouts")] use api_models::payments::{Address, AddressDetails}; -#[cfg(feature = "payouts")] use masking::Secret; -use router::types; -#[cfg(feature = "payouts")] -use router::types::{api, storage::enums, PaymentAddress}; +use router::{ + types, + types::{api, storage::enums, PaymentAddress}, +}; -#[cfg(feature = "payouts")] -use crate::utils::PaymentInfo; use crate::{ connector_auth, - utils::{self, ConnectorActions}, + utils::{self, ConnectorActions, PaymentInfo}, }; struct WiseTest; + impl ConnectorActions for WiseTest {} + impl utils::Connector for WiseTest { - fn get_data(&self) -> types::api::ConnectorData { + fn get_data(&self) -> api::ConnectorData { use router::connector::Adyen; - types::api::ConnectorData { + api::ConnectorData { connector: Box::new(&Adyen), connector_name: types::Connector::Adyen, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, } } - #[cfg(feature = "payouts")] - fn get_payout_data(&self) -> Option<types::api::ConnectorData> { + fn get_payout_data(&self) -> Option<api::ConnectorData> { use router::connector::Wise; - Some(types::api::ConnectorData { + Some(api::ConnectorData { connector: Box::new(&Wise), connector_name: types::Connector::Wise, - get_token: types::api::GetToken::Connector, + get_token: api::GetToken::Connector, merchant_connector_id: None, }) } @@ -52,7 +50,6 @@ impl utils::Connector for WiseTest { } impl WiseTest { - #[cfg(feature = "payouts")] fn get_payout_info() -> Option<PaymentInfo> { Some(PaymentInfo { country: Some(api_models::enums::CountryAlpha2::NL), @@ -86,12 +83,11 @@ impl WiseTest { } } -#[cfg(feature = "payouts")] static CONNECTOR: WiseTest = WiseTest {}; /******************** Payouts test cases ********************/ // Creates a recipient at connector's end -#[cfg(feature = "payouts")] + #[actix_web::test] async fn should_create_payout_recipient() { let payout_type = enums::PayoutType::Bank; @@ -107,7 +103,7 @@ async fn should_create_payout_recipient() { } // Create BACS payout -#[cfg(feature = "payouts")] + #[actix_web::test] async fn should_create_bacs_payout() { let payout_type = enums::PayoutType::Bank; @@ -138,7 +134,7 @@ async fn should_create_bacs_payout() { } // Create and fulfill BACS payout -#[cfg(feature = "payouts")] + #[actix_web::test] async fn should_create_and_fulfill_bacs_payout() { let payout_type = enums::PayoutType::Bank; diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 21a5a574122..4f8119bfc52 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -81,7 +81,7 @@ impl WorldlineTest { card_type: None, card_issuing_country: None, bank_code: None, - nick_name: Some(masking::Secret::new("nick_name".into())), + nick_name: Some(Secret::new("nick_name".into())), }), confirm: true, statement_descriptor_suffix: None, @@ -231,7 +231,7 @@ async fn should_sync_manual_auth_payment() { let sync_response = connector .sync_payment( Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( connector_payment_id, ), capture_method: Some(enums::CaptureMethod::Manual), @@ -264,7 +264,7 @@ async fn should_sync_auto_auth_payment() { let sync_response = connector .sync_payment( Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( connector_payment_id, ), capture_method: Some(enums::CaptureMethod::Automatic), diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs index 649b1bebbb1..571de7d959d 100644 --- a/crates/router/tests/connectors/worldpay.rs +++ b/crates/router/tests/connectors/worldpay.rs @@ -62,7 +62,7 @@ async fn should_authorize_gpay_payment() { let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Wallet( + payment_method_data: domain::PaymentMethodData::Wallet( domain::WalletData::GooglePay(domain::GooglePayWalletData { pm_type: "CARD".to_string(), description: "Visa1234567890".to_string(), @@ -97,7 +97,7 @@ async fn should_authorize_applepay_payment() { let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Wallet( + payment_method_data: domain::PaymentMethodData::Wallet( domain::WalletData::ApplePay(domain::ApplePayWalletData { payment_data: "someData".to_string(), transaction_identifier: "someId".to_string(), @@ -149,7 +149,7 @@ async fn should_sync_payment() { let response = connector .sync_payment( Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( "112233".to_string(), ), ..Default::default() diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs index e076aee42c4..b11b78025d0 100644 --- a/crates/router/tests/connectors/zen.rs +++ b/crates/router/tests/connectors/zen.rs @@ -95,7 +95,7 @@ async fn should_sync_authorized_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -211,7 +211,7 @@ async fn should_sync_auto_captured_payment() { .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { - connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, @@ -310,7 +310,7 @@ async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), @@ -352,7 +352,7 @@ async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -394,7 +394,7 @@ async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -436,7 +436,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { - payment_method_data: types::domain::PaymentMethodData::Card(domain::Card { + payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 646a11d4cdd..f4325d01b90 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -26,7 +26,7 @@ use uuid::Uuid; async fn payments_create_stripe() { Box::pin(utils::setup()).await; - let payment_id = format!("test_{}", uuid::Uuid::new_v4()); + let payment_id = format!("test_{}", Uuid::new_v4()); let api_key = ("API-KEY", "MySecretApiKey"); let request = serde_json::json!({ @@ -95,7 +95,7 @@ async fn payments_create_stripe() { async fn payments_create_adyen() { Box::pin(utils::setup()).await; - let payment_id = format!("test_{}", uuid::Uuid::new_v4()); + let payment_id = format!("test_{}", Uuid::new_v4()); let api_key = ("API-KEY", "321"); let request = serde_json::json!({ @@ -164,7 +164,7 @@ async fn payments_create_adyen() { async fn payments_create_fail() { Box::pin(utils::setup()).await; - let payment_id = format!("test_{}", uuid::Uuid::new_v4()); + let payment_id = format!("test_{}", Uuid::new_v4()); let api_key = ("API-KEY", "MySecretApiKey"); let invalid_request = serde_json::json!({ diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 9b622d11fd1..56ab453a0f5 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -14,7 +14,7 @@ use uuid::Uuid; #[test] fn connector_list() { - let connector_list = router::types::ConnectorsList { + let connector_list = types::ConnectorsList { connectors: vec![String::from("stripe"), "adyen".to_string()], }; @@ -22,7 +22,7 @@ fn connector_list() { println!("{}", &json); - let newlist: router::types::ConnectorsList = serde_json::from_str(&json).unwrap(); + let newlist: types::ConnectorsList = serde_json::from_str(&json).unwrap(); println!("{newlist:#?}"); assert_eq!(true, true); @@ -125,7 +125,7 @@ async fn payments_create_core() { }; let expected_response = services::ApplicationResponse::JsonWithHeaders((expected_response, vec![])); - let actual_response = Box::pin(router::core::payments::payments_core::< + let actual_response = Box::pin(payments::payments_core::< api::Authorize, api::PaymentsResponse, _, @@ -316,7 +316,7 @@ async fn payments_create_core_adyen_no_redirect() { }, vec![], )); - let actual_response = Box::pin(router::core::payments::payments_core::< + let actual_response = Box::pin(payments::payments_core::< api::Authorize, api::PaymentsResponse, _, diff --git a/crates/router_derive/src/macros/api_error/helpers.rs b/crates/router_derive/src/macros/api_error/helpers.rs index 5781d786ee5..deb1b349cb1 100644 --- a/crates/router_derive/src/macros/api_error/helpers.rs +++ b/crates/router_derive/src/macros/api_error/helpers.rs @@ -260,9 +260,9 @@ pub(super) fn get_unused_fields( ignore: &std::collections::HashSet<String>, ) -> Vec<Field> { let fields = match fields { - syn::Fields::Unit => Vec::new(), - syn::Fields::Unnamed(_) => Vec::new(), - syn::Fields::Named(fields) => fields.named.iter().cloned().collect(), + Fields::Unit => Vec::new(), + Fields::Unnamed(_) => Vec::new(), + Fields::Named(fields) => fields.named.iter().cloned().collect(), }; fields .iter() diff --git a/crates/router_derive/src/macros/helpers.rs b/crates/router_derive/src/macros/helpers.rs index b6490c4d629..1cb7e21bb9d 100644 --- a/crates/router_derive/src/macros/helpers.rs +++ b/crates/router_derive/src/macros/helpers.rs @@ -58,7 +58,7 @@ pub(super) fn get_struct_fields( Ok(named.to_owned()) } else { Err(syn::Error::new( - proc_macro2::Span::call_site(), + Span::call_site(), "This macro cannot be used on structs with no fields", )) } diff --git a/crates/router_derive/src/macros/try_get_enum.rs b/crates/router_derive/src/macros/try_get_enum.rs index f607b7f06c9..bdfbdb66938 100644 --- a/crates/router_derive/src/macros/try_get_enum.rs +++ b/crates/router_derive/src/macros/try_get_enum.rs @@ -68,7 +68,7 @@ pub fn try_get_enum_variant( let try_into_fn = syn::Ident::new( &format!("try_into_{}", variant_name.to_string().to_lowercase()), - proc_macro2::Span::call_site(), + Span::call_site(), ); Ok(quote::quote! { diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index af77991e804..3a9e719db18 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -265,7 +265,7 @@ fn setup_tracing_pipeline( .with_exporter(get_opentelemetry_exporter(config)) .with_batch_config(batch_config) .with_trace_config(trace_config) - .install_batch(opentelemetry::runtime::TokioCurrentThread) + .install_batch(runtime::TokioCurrentThread) .map(|tracer| tracing_opentelemetry::layer().with_tracer(tracer)); if config.ignore_errors { diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rs index fd2b9b654a4..397aab84e91 100644 --- a/crates/scheduler/src/producer.rs +++ b/crates/scheduler/src/producer.rs @@ -43,11 +43,10 @@ where tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await; - let mut interval = tokio::time::interval(std::time::Duration::from_millis( - scheduler_settings.loop_interval, - )); + let mut interval = + tokio::time::interval(Duration::from_millis(scheduler_settings.loop_interval)); - let mut shutdown_interval = tokio::time::interval(std::time::Duration::from_millis( + let mut shutdown_interval = tokio::time::interval(Duration::from_millis( scheduler_settings.graceful_shutdown_interval, )); diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 11924dd1be2..8b80b7c72c1 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -254,7 +254,7 @@ pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime } #[instrument(skip_all)] -pub async fn consumer_operation_handler<E, T: Send + Sync + 'static>( +pub async fn consumer_operation_handler<E, T>( state: T, settings: sync::Arc<SchedulerSettings>, error_handler_fun: E, @@ -263,7 +263,7 @@ pub async fn consumer_operation_handler<E, T: Send + Sync + 'static>( ) where // Error handler function E: FnOnce(error_stack::Report<errors::ProcessTrackerError>), - T: SchedulerAppState, + T: SchedulerAppState + Send + Sync + 'static, { consumer_operation_counter.fetch_add(1, atomic::Ordering::SeqCst); let start_time = std_time::Instant::now(); diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 41099bea75f..4356b6b7997 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -8,7 +8,7 @@ use hyperswitch_domain_models::errors::StorageError as DataStorageError; pub use redis_interface::errors::RedisError; use router_env::opentelemetry::metrics::MetricsError; -use crate::{errors as storage_errors, store::errors::DatabaseError}; +use crate::store::errors::DatabaseError; pub type ApplicationResult<T> = Result<T, ApplicationError>; @@ -56,20 +56,16 @@ impl Into<DataStorageError> for &StorageError { fn into(self) -> DataStorageError { match self { StorageError::DatabaseError(i) => match i.current_context() { - storage_errors::DatabaseError::DatabaseConnectionError => { - DataStorageError::DatabaseConnectionError - } + DatabaseError::DatabaseConnectionError => DataStorageError::DatabaseConnectionError, // TODO: Update this error type to encompass & propagate the missing type (instead of generic `db value not found`) - storage_errors::DatabaseError::NotFound => { + DatabaseError::NotFound => { DataStorageError::ValueNotFound(String::from("db value not found")) } // TODO: Update this error type to encompass & propagate the duplicate type (instead of generic `db value not found`) - storage_errors::DatabaseError::UniqueViolation => { - DataStorageError::DuplicateValue { - entity: "db entity", - key: None, - } - } + DatabaseError::UniqueViolation => DataStorageError::DuplicateValue { + entity: "db entity", + key: None, + }, err => DataStorageError::DatabaseError(error_stack::report!(*err)), }, StorageError::ValueNotFound(i) => DataStorageError::ValueNotFound(i.clone()), diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index e35d1f41511..7a3ef30bef3 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -217,7 +217,7 @@ impl<T: DatabaseStore> KVRouterStore<T> { partition_key: redis::kv_store::PartitionKey<'_>, ) -> error_stack::Result<(), RedisError> where - R: crate::redis::kv_store::KvStorePartition, + R: redis::kv_store::KvStorePartition, { let global_id = format!("{}", partition_key); let request_id = self.request_id.clone().unwrap_or_default(); diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index 5cf0123eb7b..3657201f878 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -41,9 +41,9 @@ pub struct MockDb { pub disputes: Arc<Mutex<Vec<store::Dispute>>>, pub lockers: Arc<Mutex<Vec<store::LockerMockUp>>>, pub mandates: Arc<Mutex<Vec<store::Mandate>>>, - pub captures: Arc<Mutex<Vec<crate::store::capture::Capture>>>, - pub merchant_key_store: Arc<Mutex<Vec<crate::store::merchant_key_store::MerchantKeyStore>>>, - pub business_profiles: Arc<Mutex<Vec<crate::store::business_profile::BusinessProfile>>>, + pub captures: Arc<Mutex<Vec<store::capture::Capture>>>, + pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>, + pub business_profiles: Arc<Mutex<Vec<store::business_profile::BusinessProfile>>>, pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>, pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>, diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index fcc4ec63ff2..2cbcbaaf01e 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -257,7 +257,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, StorageError> { match payment.active_attempt.clone() { - hyperswitch_domain_models::RemoteStorageObject::ForeignID(attempt_id) => { + RemoteStorageObject::ForeignID(attempt_id) => { let conn = pg_connection_read(self).await?; let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id( @@ -271,11 +271,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model)?; - payment.active_attempt = - hyperswitch_domain_models::RemoteStorageObject::Object(pa.clone()); + payment.active_attempt = RemoteStorageObject::Object(pa.clone()); Ok(pa) } - hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()), + RemoteStorageObject::Object(pa) => Ok(pa.clone()), } } @@ -397,7 +396,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, StorageError> { match &payment.active_attempt { - hyperswitch_domain_models::RemoteStorageObject::ForeignID(attempt_id) => { + RemoteStorageObject::ForeignID(attempt_id) => { let conn = pg_connection_read(self).await?; let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id( @@ -411,11 +410,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { er.change_context(new_err) }) .map(PaymentAttempt::from_storage_model)?; - payment.active_attempt = - hyperswitch_domain_models::RemoteStorageObject::Object(pa.clone()); + payment.active_attempt = RemoteStorageObject::Object(pa.clone()); Ok(pa) } - hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()), + RemoteStorageObject::Object(pa) => Ok(pa.clone()), } } diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs index e70c630cffe..c90292683ff 100644 --- a/crates/test_utils/src/newman_runner.rs +++ b/crates/test_utils/src/newman_runner.rs @@ -63,7 +63,7 @@ fn get_dir_path(name: impl AsRef<str>) -> String { // This function currently allows you to add only custom headers. // In future, as we scale, this can be modified based on the need -fn insert_content<T, U>(dir: T, content_to_insert: U) -> std::io::Result<()> +fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()> where T: AsRef<Path>, U: AsRef<str>, @@ -72,7 +72,7 @@ where let file_path = dir.as_ref().join(file_name); // Open the file in write mode or create it if it doesn't exist - let mut file = std::fs::OpenOptions::new() + let mut file = OpenOptions::new() .append(true) .create(true) .open(file_path)?;
chore
address Rust 1.78 clippy lints (#4545)
aaf7088afc9870be0819b188031970ed7948be7b
2023-01-10 17:33:12
Kartikeya Hegde
chore: Add cancellation reason to response (#329)
false
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 55b5fd2b9cd..4aba347d326 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -319,6 +319,7 @@ where .to_owned() .set_next_action(next_action_response) .set_return_url(payment_intent.return_url) + .set_cancellation_reason(payment_attempt.cancellation_reason) .set_authentication_type( payment_attempt .authentication_type
chore
Add cancellation reason to response (#329)
642085dc745f87b4edd2f7a744c31b8979b23cfa
2023-10-12 14:39:10
Sahkal Poddar
feat(router): Add payment link support (#2105)
false
diff --git a/Cargo.lock b/Cargo.lock index b8290efee02..e843210faa0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -392,6 +392,7 @@ dependencies = [ "router_derive", "serde", "serde_json", + "serde_with", "strum 0.24.1", "thiserror", "time 0.3.22", @@ -1202,6 +1203,16 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "bstr" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6798148dccfbff0fae41c7574d2fa8f1ef3492fba0face179de5d8d447d67b05" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "bumpalo" version = "3.13.0" @@ -1358,6 +1369,28 @@ dependencies = [ "winapi", ] +[[package]] +name = "chrono-tz" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1369bc6b9e9a7dfdae2055f6ec151fe9c554a9d23d357c0237cee2e25eaabb7" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2f5ebdc942f57ed96d560a6d1a459bae5851102a25d5bf89dc04ae453e31ecf" +dependencies = [ + "parse-zoneinfo", + "phf", + "phf_codegen", +] + [[package]] name = "clap" version = "4.3.4" @@ -1786,6 +1819,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "deunicode" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d95203a6a50906215a502507c0f879a0ce7ff205a6111e2db2a5ef8e4bb92e43" + [[package]] name = "diesel" version = "2.1.0" @@ -2407,6 +2446,30 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +[[package]] +name = "globset" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "759c97c1e17c55525b57192c06a267cda0ac5210b222d6b82189a2338fa1c13d" +dependencies = [ + "aho-corasick", + "bstr", + "fnv", + "log", + "regex", +] + +[[package]] +name = "globwalk" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e3af942408868f6934a7b85134a3230832b9977cf66125df2f9edcfce4ddcc" +dependencies = [ + "bitflags 1.3.2", + "ignore", + "walkdir", +] + [[package]] name = "h2" version = "0.3.19" @@ -2541,6 +2604,15 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" +[[package]] +name = "humansize" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" +dependencies = [ + "libm", +] + [[package]] name = "humantime" version = "1.3.0" @@ -2653,6 +2725,23 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "ignore" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbe7873dab538a9a44ad79ede1faf5f30d49f9a5c883ddbab48bce81b64b7492" +dependencies = [ + "globset", + "lazy_static", + "log", + "memchr", + "regex", + "same-file", + "thread_local", + "walkdir", + "winapi-util", +] + [[package]] name = "image" version = "0.23.14" @@ -3450,6 +3539,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "944553dd59c802559559161f9816429058b869003836120e262e8caec061b7ae" +[[package]] +name = "parse-zoneinfo" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c705f256449c60da65e11ff6626e0c16a0a0b96aaa348de61376b249bc340f41" +dependencies = [ + "regex", +] + [[package]] name = "paste" version = "1.0.12" @@ -3521,6 +3619,44 @@ dependencies = [ "sha2", ] +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared", + "rand 0.8.5", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + [[package]] name = "phonenumber" version = "0.3.3+8.13.9" @@ -4144,6 +4280,7 @@ dependencies = [ "signal-hook-tokio", "storage_impl", "strum 0.24.1", + "tera", "test_utils", "thirtyfour", "thiserror", @@ -4720,6 +4857,12 @@ dependencies = [ "time 0.3.22", ] +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + [[package]] name = "skeptic" version = "0.13.7" @@ -4744,6 +4887,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "slug" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3bc762e6a4b6c6fcaade73e77f9ebc6991b676f88bb2358bddb56560f073373" +dependencies = [ + "deunicode", +] + [[package]] name = "smallvec" version = "1.10.0" @@ -4926,6 +5078,28 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "tera" +version = "1.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "970dff17c11e884a4a09bc76e3a17ef71e01bb13447a11e85226e254fe6d10b8" +dependencies = [ + "chrono", + "chrono-tz", + "globwalk", + "humansize", + "lazy_static", + "percent-encoding", + "pest", + "pest_derive", + "rand 0.8.5", + "regex", + "serde", + "serde_json", + "slug", + "unic-segment", +] + [[package]] name = "termcolor" version = "1.2.0" @@ -5477,6 +5651,56 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-segment" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4ed5d26be57f84f176157270c112ef57b86debac9cd21daaabbe56db0f88f23" +dependencies = [ + "unic-ucd-segment", +] + +[[package]] +name = "unic-ucd-segment" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2079c122a62205b421f499da10f3ee0f7697f012f55b675e002483c73ea34700" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + [[package]] name = "unicase" version = "2.6.0" diff --git a/config/config.example.toml b/config/config.example.toml index bee61f2f615..e97b73d87c6 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -431,3 +431,7 @@ apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" #Payment apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" #Private key generate by Elliptic-curve prime256v1 curve apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE" #Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key generate by RSA:2048 algorithm + + +[payment_link] +sdk_url = "http://localhost:9090/dist/HyperLoader.js" \ No newline at end of file diff --git a/config/development.toml b/config/development.toml index 64bdd45f1c3..a29cc9ec5be 100644 --- a/config/development.toml +++ b/config/development.toml @@ -441,6 +441,9 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE" apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" +[payment_link] +sdk_url = "http://localhost:9090/dist/HyperLoader.js" + [lock_settings] redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 \ No newline at end of file diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 08646a4a0b3..3888d6d1d21 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -294,6 +294,8 @@ pub struct PaymentsRequest { /// additional data that might be required by hyperswitch pub feature_metadata: Option<FeatureMetadata>, + /// payment link object required for generating the payment_link + pub payment_link_object: Option<PaymentLinkObject>, /// The business profile to use for this payment, if not passed the default business profile /// associated with the merchant account will be used. @@ -2079,6 +2081,7 @@ pub struct PaymentsResponse { #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, + pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment pub profile_id: Option<String>, @@ -3066,3 +3069,44 @@ mod tests { ) } } + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] +pub struct PaymentLinkObject { + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub link_expiry: Option<PrimitiveDateTime>, + pub merchant_custom_domain_name: Option<String>, +} + +#[derive(Default, Debug, serde::Deserialize, Clone, ToSchema)] +pub struct RetrievePaymentLinkRequest { + pub client_secret: Option<String>, +} + +#[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] +pub struct PaymentLinkResponse { + pub link: String, + pub payment_link_id: String, +} + +#[derive(Clone, Debug, serde::Serialize, ToSchema)] +pub struct RetrievePaymentLinkResponse { + pub payment_link_id: String, + pub payment_id: String, + pub merchant_id: String, + pub link_to_pay: String, + pub amount: i64, + #[schema(value_type = Option<Currency>, example = "USD")] + pub currency: Option<api_enums::Currency>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub last_modified_at: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub link_expiry: Option<PrimitiveDateTime>, +} + +#[derive(Clone, Debug, serde::Deserialize, ToSchema)] +pub struct PaymentLinkInitiateRequest { + pub merchant_id: String, + pub payment_id: String, +} diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs index b3bf8af8c36..3d8f52d0006 100644 --- a/crates/data_models/src/payments/payment_intent.rs +++ b/crates/data_models/src/payments/payment_intent.rs @@ -104,6 +104,7 @@ pub struct PaymentIntent { // Denotes the action(approve or reject) taken by merchant in case of manual review. // 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 pub merchant_decision: Option<String>, + pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, } @@ -143,6 +144,7 @@ pub struct PaymentIntentNew { pub attempt_count: i16, pub profile_id: Option<String>, pub merchant_decision: Option<String>, + pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, } diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 474ac984e69..3de35d73f82 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -25,6 +25,7 @@ pub mod merchant_connector_account; pub mod merchant_key_store; pub mod payment_attempt; pub mod payment_intent; +pub mod payment_link; pub mod payment_method; pub mod payout_attempt; pub mod payouts; diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 1212c9d5242..1669cd7e779 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -46,6 +46,7 @@ pub struct PaymentIntent { // Denotes the action(approve or reject) taken by merchant in case of manual review. // 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 pub merchant_decision: Option<String>, + pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, } @@ -97,6 +98,7 @@ pub struct PaymentIntentNew { pub attempt_count: i16, pub profile_id: Option<String>, pub merchant_decision: Option<String>, + pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, } diff --git a/crates/diesel_models/src/payment_link.rs b/crates/diesel_models/src/payment_link.rs new file mode 100644 index 00000000000..4b182a8155a --- /dev/null +++ b/crates/diesel_models/src/payment_link.rs @@ -0,0 +1,50 @@ +use diesel::{Identifiable, Insertable, Queryable}; +use serde::{self, Deserialize, Serialize}; +use time::PrimitiveDateTime; + +use crate::{enums as storage_enums, schema::payment_link}; + +#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize)] +#[diesel(table_name = payment_link)] +#[diesel(primary_key(payment_link_id))] +pub struct PaymentLink { + pub payment_link_id: String, + pub payment_id: String, + pub link_to_pay: String, + pub merchant_id: String, + pub amount: i64, + pub currency: Option<storage_enums::Currency>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub last_modified_at: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub fulfilment_time: Option<PrimitiveDateTime>, +} + +#[derive( + Clone, + Debug, + Default, + Eq, + PartialEq, + Insertable, + serde::Serialize, + serde::Deserialize, + router_derive::DebugAsDisplay, +)] +#[diesel(table_name = payment_link)] +pub struct PaymentLinkNew { + pub payment_link_id: String, + pub payment_id: String, + pub link_to_pay: String, + pub merchant_id: String, + pub amount: i64, + pub currency: Option<storage_enums::Currency>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub created_at: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub last_modified_at: Option<PrimitiveDateTime>, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub fulfilment_time: Option<PrimitiveDateTime>, +} diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index bd280864cc4..ef4ab9f32fa 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -18,6 +18,7 @@ pub mod merchant_connector_account; pub mod merchant_key_store; pub mod payment_attempt; pub mod payment_intent; +pub mod payment_link; pub mod payment_method; pub mod payout_attempt; pub mod payouts; diff --git a/crates/diesel_models/src/query/payment_link.rs b/crates/diesel_models/src/query/payment_link.rs new file mode 100644 index 00000000000..085257633c6 --- /dev/null +++ b/crates/diesel_models/src/query/payment_link.rs @@ -0,0 +1,29 @@ +use diesel::{associations::HasTable, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + payment_link::{PaymentLink, PaymentLinkNew}, + schema::payment_link::dsl, + PgPooledConn, StorageResult, +}; + +impl PaymentLinkNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentLink> { + generics::generic_insert(conn, self).await + } +} + +impl PaymentLink { + pub async fn find_link_by_payment_link_id( + conn: &PgPooledConn, + payment_link_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::payment_link_id.eq(payment_link_id.to_owned()), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 0da819f2a70..93a204446a3 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -610,10 +610,33 @@ diesel::table! { profile_id -> Nullable<Varchar>, #[max_length = 64] merchant_decision -> Nullable<Varchar>, + #[max_length = 255] + payment_link_id -> Nullable<Varchar>, payment_confirm_source -> Nullable<PaymentSource>, } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + payment_link (payment_link_id) { + #[max_length = 255] + payment_link_id -> Varchar, + #[max_length = 64] + payment_id -> Varchar, + #[max_length = 255] + link_to_pay -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + amount -> Int8, + currency -> Nullable<Currency>, + created_at -> Timestamp, + last_modified_at -> Timestamp, + fulfilment_time -> Nullable<Timestamp>, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -833,6 +856,7 @@ diesel::allow_tables_to_appear_in_same_query!( merchant_key_store, payment_attempt, payment_intent, + payment_link, payment_methods, payout_attempt, payouts, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f271c6e3629..da207e91493 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -81,6 +81,7 @@ strum = { version = "0.24.1", features = ["derive"] } thiserror = "1.0.40" time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.28.2", features = ["macros", "rt-multi-thread"] } +tera = "1.19.1" url = { version = "2.4.0", features = ["serde"] } utoipa = { version = "3.3.0", features = ["preserve_order", "time"] } utoipa-swagger-ui = { version = "3.1.3", features = ["actix-web"] } diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index d79533e73b4..5d4d3082aff 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -232,6 +232,8 @@ pub enum StripeErrorCode { HyperswitchUnprocessableEntity { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")] CurrencyNotSupported { message: String }, + #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")] + PaymentLinkNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")] LockTimeout, // [#216]: https://github.com/juspay/hyperswitch/issues/216 @@ -490,6 +492,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::ClientSecretNotGiven | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, + errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => { Self::MerchantConnectorAccountNotFound { id } @@ -652,6 +655,7 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::PaymentMethodUnactivated => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed + | Self::PaymentLinkNotFound | Self::InternalServerError | Self::MandateActive | Self::CustomerRedacted diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs index edc56fcee73..f1892698ace 100644 --- a/crates/router/src/compatibility/wrap.rs +++ b/crates/router/src/compatibility/wrap.rs @@ -132,6 +132,20 @@ where .respond_to(request) .map_into_boxed_body() } + + Ok(api::ApplicationResponse::PaymenkLinkForm(payment_link_data)) => { + match api::build_payment_link_html(*payment_link_data) { + Ok(rendered_html) => api::http_response_html_data(rendered_html), + Err(_) => api::http_response_err( + r#"{ + "error": { + "message": "Error while rendering payment link html page" + } + }"#, + ), + } + } + Err(error) => api::log_and_return_error_response(error), }; diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 9ee84e5baea..5dd58c5d5f2 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -100,6 +100,12 @@ pub struct Settings { pub applepay_merchant_configs: ApplepayMerchantConfigs, pub lock_settings: LockSettings, pub temp_locker_enable_config: TempLockerEnableConfig, + pub payment_link: PaymentLink, +} + +#[derive(Debug, Deserialize, Clone, Default)] +pub struct PaymentLink { + pub sdk_url: String, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 2e090a6436b..a3bb3c78915 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -10,6 +10,7 @@ pub mod errors; pub mod files; pub mod mandate; pub mod metrics; +pub mod payment_link; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 6805bc2be19..e606771b372 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -230,6 +230,8 @@ pub enum ApiErrorResponse { IncorrectPaymentMethodConfiguration, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")] WebhookUnprocessableEntity, + #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")] + PaymentLinkNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Merchant Secret set my merchant for webhook source verification is invalid")] WebhookInvalidMerchantSecret, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")] diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index 37725b7391f..38d42596cdf 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -264,6 +264,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::ResourceBusy => { AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None)) } + Self::PaymentLinkNotFound => { + AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None)) + } } } } diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs new file mode 100644 index 00000000000..2f817beb53e --- /dev/null +++ b/crates/router/src/core/payment_link.rs @@ -0,0 +1,172 @@ +use common_utils::ext_traits::AsyncExt; +use error_stack::ResultExt; + +use super::errors::{self, StorageErrorExt}; +use crate::{ + core::payments::helpers, + errors::RouterResponse, + routes::AppState, + services, + types::{domain, storage::enums as storage_enums, transformers::ForeignFrom}, + utils::OptionExt, +}; + +pub async fn retrieve_payment_link( + state: AppState, + payment_link_id: String, +) -> RouterResponse<api_models::payments::RetrievePaymentLinkResponse> { + let db = &*state.store; + let payment_link_object = db + .find_payment_link_by_payment_link_id(&payment_link_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; + + let response = + api_models::payments::RetrievePaymentLinkResponse::foreign_from(payment_link_object); + Ok(services::ApplicationResponse::Json(response)) +} + +pub async fn intiate_payment_link_flow( + state: AppState, + merchant_account: domain::MerchantAccount, + merchant_id: String, + payment_id: String, +) -> RouterResponse<services::PaymentLinkFormData> { + let db = &*state.store; + let payment_intent = db + .find_payment_intent_by_payment_id_merchant_id( + &payment_id, + &merchant_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let fulfillment_time = payment_intent + .payment_link_id + .as_ref() + .async_and_then(|pli| async move { + db.find_payment_link_by_payment_link_id(pli) + .await + .ok()? + .fulfilment_time + .ok_or(errors::ApiErrorResponse::PaymentNotFound) + .ok() + }) + .await + .get_required_value("fulfillment_time") + .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + + helpers::validate_payment_status_against_not_allowed_statuses( + &payment_intent.status, + &[ + storage_enums::IntentStatus::Cancelled, + storage_enums::IntentStatus::Succeeded, + storage_enums::IntentStatus::Processing, + storage_enums::IntentStatus::RequiresCapture, + storage_enums::IntentStatus::RequiresMerchantAction, + ], + "create payment link", + )?; + + let expiry = fulfillment_time.assume_utc().unix_timestamp(); + + let js_script = get_js_script( + payment_intent.amount.to_string(), + payment_intent.currency.unwrap_or_default().to_string(), + merchant_account.publishable_key.unwrap_or_default(), + payment_intent.client_secret.unwrap_or_default(), + payment_intent.payment_id, + expiry, + ); + + let payment_link_data = services::PaymentLinkFormData { + js_script, + sdk_url: state.conf.payment_link.sdk_url.clone(), + }; + Ok(services::ApplicationResponse::PaymenkLinkForm(Box::new( + payment_link_data, + ))) +} + +/* +The get_js_script function is used to inject dynamic value to payment_link sdk, which is unique to every payment. +*/ + +fn get_js_script( + amount: String, + currency: String, + pub_key: String, + secret: String, + payment_id: String, + expiry: i64, +) -> String { + format!( + "window.__PAYMENT_DETAILS_STR = JSON.stringify({{ + client_secret: '{secret}', + amount: '{amount}', + currency: '{currency}', + payment_id: '{payment_id}', + expiry: {expiry}, + // TODO: Remove hardcoded values + merchant_logo: 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + return_url: 'http://localhost:5500/public/index.html', + currency_symbol: '$', + merchant: 'Steam', + max_items_visible_after_collapse: 3, + order_details: [ + {{ + product_name: + 'dskjghbdsiuh sagfvbsajd ugbfiusedg fiudshgiu sdhgvishd givuhdsifu gnb gidsug biuesbdg iubsedg bsduxbg jhdxbgv jdskfbgi sdfgibuh ew87t54378 ghdfjbv jfdhgvb dufhvbfidu hg5784ghdfbjnk f (taxes incl.)', + quantity: 2, + amount: 100, + product_image: + 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + }}, + {{ + product_name: \"F1 '23\", + quantity: 4, + amount: 500, + product_image: + 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + }}, + {{ + product_name: \"Motosport '24\", + quantity: 4, + amount: 500, + product_image: + 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + }}, + {{ + product_name: 'Trackmania', + quantity: 4, + amount: 500, + product_image: + 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + }}, + {{ + product_name: 'Ghost Recon', + quantity: 4, + amount: 500, + product_image: + 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + }}, + {{ + product_name: 'Cup of Tea', + quantity: 4, + amount: 500, + product_image: + 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + }}, + {{ + product_name: 'Tea cups', + quantity: 4, + amount: 500, + product_image: + 'https://upload.wikimedia.org/wikipedia/commons/8/83/Steam_icon_logo.svg', + }}, + ] + }}); + + const hyper = Hyper(\"{pub_key}\");" + ) +} diff --git a/crates/router/src/core/payment_link/payment_link.html b/crates/router/src/core/payment_link/payment_link.html new file mode 100644 index 00000000000..4ce2ff1919b --- /dev/null +++ b/crates/router/src/core/payment_link/payment_link.html @@ -0,0 +1,1310 @@ +<!DOCTYPE html> +<html> + <head> + {{ hyperloader_sdk_link }} + <style> + :root { + --primary-color: #26c5a0; + --primary-accent-color: #f8e5a0; + --secondary-color: #1c7ed9; + } + + html, + body { + height: 100%; + } + + body { + display: flex; + flex-flow: column; + align-items: center; + justify-content: flex-start; + margin: 0; + background-color: #fafafa; + color: #292929; + } + + .hidden { + display: none !important; + } + + .hyper-checkout { + display: flex; + background-color: #fafafa; + height: 100%; + width: 100%; + max-width: 1900px; + } + + .main { + display: flex; + flex-flow: column; + justify-content: center; + align-items: center; + background-color: #fdfdfd; + min-width: 500px; + width: 50vw; + } + + #hyper-checkout-details { + font-family: "Montserrat"; + } + + .hyper-checkout-payment { + border: 1px solid #e6e6e6; + border-radius: 8px; + min-width: 582px; + } + + .hyper-checkout-payment-content-details { + display: flex; + flex-flow: row; + margin: 20px; + justify-content: space-between; + } + + .hyper-checkout-payment-price { + font-weight: 700; + font-size: 40px; + height: 64px; + display: flex; + align-items: center; + } + + #hyper-checkout-payment-merchant-details { + margin-top: 20px; + } + + .hyper-checkout-payment-merchant-name { + font-weight: 600; + font-size: 18px; + } + + .hyper-checkout-payment-ref { + font-size: 13px; + } + + .hyper-checkout-image-header { + display: flex; + justify-content: space-between; + align-items: center; + } + + #hyper-checkout-merchant-image, + #hyper-checkout-cart-image { + height: 64px; + width: 64px; + border: 1px solid #e6e6e6; + border-radius: 4px; + display: flex; + align-items: center; + justify-content: center; + } + + #hyper-checkout-merchant-image > img { + height: 48px; + width: 48px; + } + + #hyper-checkout-cart-image { + display: none; + cursor: pointer; + height: 60px; + width: 60px; + border-radius: 100px; + background-color: #f5f5f5; + } + + #hyper-checkout-payment-footer { + padding: 8px 20px; + background-color: #f5f5f5; + font-size: 13px; + font-weight: 500; + } + + #hyper-checkout-cart { + display: flex; + flex-flow: column; + min-width: 582px; + width: min-content; + margin-top: 30px; + max-height: 600px; + } + + #hyper-checkout-cart-items { + margin: 10px 0; + max-height: 600px; + overflow: scroll; + padding-right: 20px; + } + + .hyper-checkout-cart-header { + font-size: 15px; + display: flex; + flex-flow: row; + align-items: center; + } + + .hyper-checkout-cart-header > span { + margin-left: 5px; + font-weight: 500; + } + + .cart-close { + display: none; + } + + .hyper-checkout-cart-item { + display: flex; + flex-flow: row; + margin: 20px 0; + font-size: 15px; + } + + .hyper-checkout-cart-product-image { + height: 88px; + width: 88px; + } + + .hyper-checkout-card-item-name { + font-weight: 500; + overflow: hidden; + text-overflow: ellipsis; + -webkit-line-clamp: 2; + display: -webkit-box; + -webkit-box-orient: vertical; + } + + .hyper-checkout-card-item-quantity { + border: 1px solid #e6e6e6; + border-radius: 3px; + width: max-content; + padding: 5px 12px; + background-color: #fafafa; + font-size: 13px; + font-weight: 500; + } + + .hyper-checkout-cart-product-details { + display: flex; + flex-flow: column; + margin-left: 10px; + justify-content: space-between; + width: 100%; + } + + .hyper-checkout-card-item-price { + justify-self: flex-end; + font-weight: 600; + font-size: 16px; + padding-left: 30px; + text-align: end; + } + + .hyper-checkout-cart-item-divider { + height: 1px; + background-color: #e6e6e6; + } + + .hyper-checkout-cart-button { + color: var(--primary-color); + font-size: 15px; + font-weight: 600; + cursor: pointer; + } + + .hyper-checkout-sdk { + width: 50vw; + min-width: 584px; + z-index: 2; + background-color: var(--primary-color); + box-shadow: 0px 1px 10px #f2f2f2; + display: flex; + align-items: center; + justify-content: center; + } + + #payment-form-wrap { + min-width: 584px; + padding: 50px; + } + + #hyper-checkout-sdk-header { + padding: 10px 10px 10px 22px; + display: flex; + align-items: flex-start; + justify-content: flex-start; + border-bottom: 1px solid #f2f2f2; + } + + .hyper-checkout-sdk-header-logo { + height: 60px; + width: 60px; + background-color: white; + border-radius: 2px; + } + + .hyper-checkout-sdk-header-logo > img { + height: 56px; + width: 56px; + margin: 2px; + } + + .hyper-checkout-sdk-header-items { + display: flex; + flex-flow: column; + color: white; + font-size: 20px; + font-weight: 700; + } + + .hyper-checkout-sdk-items { + margin-left: 10px; + } + + .hyper-checkout-sdk-header-brand-name, + .hyper-checkout-sdk-header-amount { + font-size: 18px; + font-weight: 600; + display: flex; + align-items: center; + font-family: "Montserrat"; + justify-self: flex-start; + } + + .hyper-checkout-sdk-header-amount { + font-weight: 800; + font-size: 25px; + } + + .payNow { + margin-top: 10px; + } + + .checkoutButton { + height: 48px; + border-radius: 25px; + width: 100%; + border: transparent; + background: var(--secondary-color); + color: #ffffff; + font-weight: 600; + cursor: pointer; + } + + .page-spinner, + .page-spinner::before, + .page-spinner::after, + .spinner, + .spinner:before, + .spinner:after { + border-radius: 50%; + } + + .page-spinner, + .spinner { + color: #ffffff; + font-size: 22px; + text-indent: -99999px; + margin: 0px auto; + position: relative; + width: 20px; + height: 20px; + box-shadow: inset 0 0 0 2px; + -webkit-transform: translateZ(0); + -ms-transform: translateZ(0); + transform: translateZ(0); + } + + .page-spinner::before, + .page-spinner::after, + .spinner:before, + .spinner:after { + position: absolute; + content: ""; + } + + .page-spinner { + color: var(--primary-color) !important; + height: 50px !important; + width: 50px !important; + box-shadow: inset 0 0 0 4px !important; + margin: auto !important; + } + + #hyper-checkout-status { + margin: 40px !important; + } + + .hyper-checkout-status-header { + display: flex; + align-items: center; + font-family: "Montserrat"; + font-size: 24px; + font-weight: 600; + } + + #status-img { + height: 70px; + } + + #status-date { + font-size: 13px; + font-weight: 500; + color: #53655c; + } + + #status-details { + margin-left: 10px; + justify-content: center; + display: flex; + flex-flow: column; + } + + @keyframes loading { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + + 100% { + -webkit-transform: rotate(360deg); + transform: rotate(360deg); + } + } + + .spinner:before { + width: 10.4px; + height: 20.4px; + background: var(--primary-color); + border-radius: 20.4px 0 0 20.4px; + top: -0.2px; + left: -0.2px; + -webkit-transform-origin: 10.4px 10.2px; + transform-origin: 10.4px 10.2px; + -webkit-animation: loading 2s infinite ease 1.5s; + animation: loading 2s infinite ease 1.5s; + } + + #payment-message { + font-size: 12px; + font-weight: 500; + padding: 2%; + color: #ff0000; + font-family: "Montserrat"; + } + + .spinner:after { + width: 10.4px; + height: 10.2px; + background: var(--primary-color); + border-radius: 0 10.2px 10.2px 0; + top: -0.1px; + left: 10.2px; + -webkit-transform-origin: 0px 10.2px; + transform-origin: 0px 10.2px; + -webkit-animation: loading 2s infinite ease; + animation: loading 2s infinite ease; + } + + #payment-form { + max-width: 560px; + width: 100%; + margin: 0 auto; + text-align: center; + } + + @media only screen and (max-width: 1200px) { + .checkoutButton { + width: 95%; + background-color: var(--primary-color); + } + + .hyper-checkout { + flex-flow: column; + margin: 0; + } + + .main { + width: auto; + min-width: 300px; + } + + .hyper-checkout-payment { + min-width: 100px; + width: 100vw; + margin: 0; + border: 0; + border-radius: 0; + background-color: var(--primary-color); + display: flex; + flex-flow: column; + justify-self: flex-start; + align-self: flex-start; + } + + .hyper-checkout-payment-content-details { + flex-flow: column; + flex-direction: column-reverse; + margin: 24px; + } + + #hyper-checkout-merchant-image { + background-color: white; + } + + #hyper-checkout-cart-image { + display: flex; + } + + .hyper-checkout-payment-price { + font-size: 48px; + margin-top: 20px; + } + + .hyper-checkout-payment-merchant-name { + font-size: 18px; + } + + #hyper-checkout-payment-footer { + background-color: var(--primary-accent-color); + border-radius: 50px; + width: auto; + align-self: center; + margin: 0 24px 24px 24px; + } + + #hyper-checkout-cart { + position: absolute; + top: 0; + right: 0; + z-index: 100; + margin: 0; + min-width: 300px; + max-width: 600px; + max-height: 100vh; + width: 100vw; + height: 100vh; + background-color: #f5f5f5; + box-shadow: 0px 10px 10px #aeaeae; + } + + .hyper-checkout-cart-header { + margin: 10px 0 0 10px; + } + + .cart-close { + margin: 0 10px 0 auto; + display: inline; + } + + #hyper-checkout-cart-items { + margin: 20px; + padding: 0; + max-height: max-content; + } + + .hyper-checkout-cart-button { + margin: 10px; + text-align: right; + } + + #hyper-checkout-sdk { + margin: 20px 0 0 0; + background-color: transparent; + min-width: 300px; + width: 100vw; + } + + #payment-form-wrap { + min-width: 300px; + padding: 10px; + width: 100vw; + } + + #hyper-checkout-status { + padding: 15px; + } + + #status-img { + height: 60px; + } + + #status-text { + font-size: 19px; + } + + #status-date { + font-size: 12px; + } + + .hyper-checkout-item-header { + font-size: 11px; + } + + .hyper-checkout-item-value { + font-size: 17px; + } + } + </style> + <link + rel="stylesheet" + href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" + /> + </head> + + <body onload="showSDK()"> + <div class="page-spinner hidden" id="page-spinner"></div> + <div class="hyper-checkout"> + <div class="main hidden" id="hyper-checkout-status"> + <div class="hyper-checkout-status-header"> + <img id="status-img" /> + <div id="status-details"> + <div id="status-text"></div> + <div id="status-date"></div> + </div> + </div> + <div id="hyper-checkout-status-items"></div> + </div> + <div class="main" id="hyper-checkout-details"> + <div class="hyper-checkout-payment"> + <div class="hyper-checkout-payment-content-details"> + <div id="hyper-checkout-payment-context"> + <div id="hyper-checkout-payment-merchant-details"></div> + </div> + <div class="hyper-checkout-image-header"> + <div id="hyper-checkout-merchant-image"></div> + <div + id="hyper-checkout-cart-image" + onclick="viewCartInMobileView()" + > + <svg + fill="#000000" + version="1.1" + id="Capa_1" + xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + width="30px" + height="30px" + viewBox="0 0 902.86 902.86" + xml:space="preserve" + > + <g> + <g> + <path + d="M671.504,577.829l110.485-432.609H902.86v-68H729.174L703.128,179.2L0,178.697l74.753,399.129h596.751V577.829z + M685.766,247.188l-67.077,262.64H131.199L81.928,246.756L685.766,247.188z" + /> + <path + d="M578.418,825.641c59.961,0,108.743-48.783,108.743-108.744s-48.782-108.742-108.743-108.742H168.717 + c-59.961,0-108.744,48.781-108.744,108.742s48.782,108.744,108.744,108.744c59.962,0,108.743-48.783,108.743-108.744 + c0-14.4-2.821-28.152-7.927-40.742h208.069c-5.107,12.59-7.928,26.342-7.928,40.742 + C469.675,776.858,518.457,825.641,578.418,825.641z M209.46,716.897c0,22.467-18.277,40.744-40.743,40.744 + c-22.466,0-40.744-18.277-40.744-40.744c0-22.465,18.277-40.742,40.744-40.742C191.183,676.155,209.46,694.432,209.46,716.897z + M619.162,716.897c0,22.467-18.277,40.744-40.743,40.744s-40.743-18.277-40.743-40.744c0-22.465,18.277-40.742,40.743-40.742 + S619.162,694.432,619.162,716.897z" + /> + </g> + </g> + </svg> + </div> + </div> + </div> + <div id="hyper-checkout-payment-footer"></div> + </div> + <div id="hyper-checkout-cart"> + <div class="hyper-checkout-cart-header"> + <svg + width="16" + height="16" + viewBox="0 0 16 16" + fill="none" + xmlns="http://www.w3.org/2000/svg" + class="cart-icon" + > + <g clip-path="url(#clip0_11421_6708)"> + <mask + id="mask0_11421_6708" + style="mask-type: alpha" + maskUnits="userSpaceOnUse" + x="0" + y="0" + width="16" + height="16" + > + <rect width="16" height="16" fill="#D9D9D9" /> + </mask> + <g mask="url(#mask0_11421_6708)"> + <path + d="M3.53716 14.3331C3.20469 14.3331 2.92071 14.2153 2.68525 13.9798C2.44977 13.7444 2.33203 13.4604 2.33203 13.1279V5.53823C2.33203 5.20575 2.44977 4.92178 2.68525 4.68631C2.92071 4.45083 3.20469 4.3331 3.53716 4.3331H4.9987C4.9987 3.50063 5.29058 2.79252 5.87433 2.20876C6.4581 1.62501 7.16621 1.33313 7.99868 1.33313C8.83115 1.33313 9.53927 1.62501 10.123 2.20876C10.7068 2.79252 10.9987 3.50063 10.9987 4.3331H12.4602C12.7927 4.3331 13.0766 4.45083 13.3121 4.68631C13.5476 4.92178 13.6653 5.20575 13.6653 5.53823V13.1279C13.6653 13.4604 13.5476 13.7444 13.3121 13.9798C13.0766 14.2153 12.7927 14.3331 12.4602 14.3331H3.53716ZM3.53716 13.3331H12.4602C12.5115 13.3331 12.5585 13.3117 12.6012 13.269C12.644 13.2262 12.6653 13.1792 12.6653 13.1279V5.53823C12.6653 5.48694 12.644 5.43992 12.6012 5.39718C12.5585 5.35445 12.5115 5.33308 12.4602 5.33308H3.53716C3.48588 5.33308 3.43886 5.35445 3.39611 5.39718C3.35338 5.43992 3.33201 5.48694 3.33201 5.53823V13.1279C3.33201 13.1792 3.35338 13.2262 3.39611 13.269C3.43886 13.3117 3.48588 13.3331 3.53716 13.3331ZM7.99868 8.99973C8.83115 8.99973 9.53927 8.70785 10.123 8.1241C10.7068 7.54033 10.9987 6.83221 10.9987 5.99975H9.99868C9.99868 6.5553 9.80424 7.02752 9.41535 7.41641C9.02646 7.8053 8.55424 7.99975 7.99868 7.99975C7.44313 7.99975 6.9709 7.8053 6.58202 7.41641C6.19313 7.02752 5.99868 6.5553 5.99868 5.99975H4.9987C4.9987 6.83221 5.29058 7.54033 5.87433 8.1241C6.4581 8.70785 7.16621 8.99973 7.99868 8.99973ZM5.99868 4.3331H9.99868C9.99868 3.77754 9.80424 3.30532 9.41535 2.91643C9.02646 2.52754 8.55424 2.3331 7.99868 2.3331C7.44313 2.3331 6.9709 2.52754 6.58202 2.91643C6.19313 3.30532 5.99868 3.77754 5.99868 4.3331Z" + fill="#333333" + /> + </g> + </g> + <defs> + <clipPath id="clip0_11421_6708"> + <rect width="16" height="16" fill="white" /> + </clipPath> + </defs> + </svg> + <span>Your Cart</span> + <svg + xmlns="http://www.w3.org/2000/svg" + viewBox="0 0 50 50" + width="25px" + height="25px" + class="cart-close" + onclick="hideCartInMobileView()" + > + <path + d="M 9.15625 6.3125 L 6.3125 9.15625 L 22.15625 25 L 6.21875 40.96875 L 9.03125 43.78125 L 25 27.84375 L 40.9375 43.78125 L 43.78125 40.9375 L 27.84375 25 L 43.6875 9.15625 L 40.84375 6.3125 L 25 22.15625 Z" + /> + </svg> + </div> + <div id="hyper-checkout-cart-items"></div> + </div> + </div> + <div class="hyper-checkout-sdk" id="hyper-checkout-sdk"> + <div id="payment-form-wrap"> + <form id="payment-form" onsubmit="handleSubmit(); return false;"> + <div id="unified-checkout"> + <div + id="orca-element-unified-checkout" + style="height: auto" + class="payment base" + > + <div id="orca-fullscreen-iframeRef-unified-checkout"></div> + <iframe + id="orca-payment-element-iframeRef-unified-checkout" + name="orca-payment-element-iframeRef-unified-checkout" + src="http://localhost:9050/?componentName=payment" + allow="payment *" + style=" + border: 0px none; + transition: height 0.35s ease 0s, opacity 0.4s ease 0.1s; + height: 338px; + " + width="100%" + ></iframe> + </div> + </div> + <button id="submit" class="checkoutButton payNow"> + <div class="spinner hidden" id="spinner"></div> + <span id="button-text">Pay now</span> + </button> + <div id="payment-message" class="hidden"></div> + </form> + </div> + </div> + </div> + <div id="hyper-footer" class="hidden"> + <svg class="fill-current" height="18px" width="130px" transform=""> + <path + opacity="0.4" + d="M0.791016 11.7578H1.64062V9.16992H1.71875C2.00684 9.73145 2.63672 10.0928 3.35938 10.0928C4.69727 10.0928 5.56641 9.02344 5.56641 7.37305V7.36328C5.56641 5.72266 4.69238 4.64355 3.35938 4.64355C2.62695 4.64355 2.04102 4.99023 1.71875 5.57617H1.64062V4.73633H0.791016V11.7578ZM3.16406 9.34082C2.20703 9.34082 1.62109 8.58887 1.62109 7.37305V7.36328C1.62109 6.14746 2.20703 5.39551 3.16406 5.39551C4.12598 5.39551 4.69727 6.1377 4.69727 7.36328V7.37305C4.69727 8.59863 4.12598 9.34082 3.16406 9.34082ZM8.85762 10.0928C10.3566 10.0928 11.2844 9.05762 11.2844 7.37305V7.36328C11.2844 5.67383 10.3566 4.64355 8.85762 4.64355C7.35859 4.64355 6.43086 5.67383 6.43086 7.36328V7.37305C6.43086 9.05762 7.35859 10.0928 8.85762 10.0928ZM8.85762 9.34082C7.86152 9.34082 7.3 8.61328 7.3 7.37305V7.36328C7.3 6.11816 7.86152 5.39551 8.85762 5.39551C9.85371 5.39551 10.4152 6.11816 10.4152 7.36328V7.37305C10.4152 8.61328 9.85371 9.34082 8.85762 9.34082ZM13.223 10H14.0727L15.2445 5.92773H15.3227L16.4994 10H17.3539L18.8285 4.73633H17.9838L16.9486 8.94531H16.8705L15.6938 4.73633H14.8881L13.7113 8.94531H13.6332L12.598 4.73633H11.7484L13.223 10ZM21.7047 10.0928C22.9449 10.0928 23.6969 9.38965 23.8775 8.67676L23.8873 8.6377H23.0377L23.0182 8.68164C22.8766 8.99902 22.4371 9.33594 21.7242 9.33594C20.7867 9.33594 20.1861 8.70117 20.1617 7.6123H23.9508V7.28027C23.9508 5.70801 23.0816 4.64355 21.651 4.64355C20.2203 4.64355 19.2926 5.75684 19.2926 7.38281V7.3877C19.2926 9.03809 20.2008 10.0928 21.7047 10.0928ZM21.6461 5.40039C22.4225 5.40039 22.9986 5.89355 23.0865 6.93359H20.1764C20.2691 5.93262 20.8648 5.40039 21.6461 5.40039ZM25.0691 10H25.9188V6.73828C25.9188 5.9668 26.4949 5.4541 27.3055 5.4541C27.491 5.4541 27.6521 5.47363 27.8279 5.50293V4.67773C27.7449 4.66309 27.5643 4.64355 27.4031 4.64355C26.6902 4.64355 26.1971 4.96582 25.9969 5.51758H25.9188V4.73633H25.0691V10ZM30.6797 10.0928C31.9199 10.0928 32.6719 9.38965 32.8525 8.67676L32.8623 8.6377H32.0127L31.9932 8.68164C31.8516 8.99902 31.4121 9.33594 30.6992 9.33594C29.7617 9.33594 29.1611 8.70117 29.1367 7.6123H32.9258V7.28027C32.9258 5.70801 32.0566 4.64355 30.626 4.64355C29.1953 4.64355 28.2676 5.75684 28.2676 7.38281V7.3877C28.2676 9.03809 29.1758 10.0928 30.6797 10.0928ZM30.6211 5.40039C31.3975 5.40039 31.9736 5.89355 32.0615 6.93359H29.1514C29.2441 5.93262 29.8398 5.40039 30.6211 5.40039ZM35.9875 10.0928C36.7199 10.0928 37.3059 9.74609 37.6281 9.16016H37.7062V10H38.5559V2.64648H37.7062V5.56641H37.6281C37.34 5.00488 36.7102 4.64355 35.9875 4.64355C34.6496 4.64355 33.7805 5.71289 33.7805 7.36328V7.37305C33.7805 9.01367 34.6545 10.0928 35.9875 10.0928ZM36.1828 9.34082C35.2209 9.34082 34.6496 8.59863 34.6496 7.37305V7.36328C34.6496 6.1377 35.2209 5.39551 36.1828 5.39551C37.1398 5.39551 37.7258 6.14746 37.7258 7.36328V7.37305C37.7258 8.58887 37.1398 9.34082 36.1828 9.34082ZM45.2164 10.0928C46.5494 10.0928 47.4234 9.01367 47.4234 7.37305V7.36328C47.4234 5.71289 46.5543 4.64355 45.2164 4.64355C44.4938 4.64355 43.8639 5.00488 43.5758 5.56641H43.4977V2.64648H42.648V10H43.4977V9.16016H43.5758C43.898 9.74609 44.484 10.0928 45.2164 10.0928ZM45.0211 9.34082C44.0641 9.34082 43.4781 8.58887 43.4781 7.37305V7.36328C43.4781 6.14746 44.0641 5.39551 45.0211 5.39551C45.983 5.39551 46.5543 6.1377 46.5543 7.36328V7.37305C46.5543 8.59863 45.983 9.34082 45.0211 9.34082ZM48.7957 11.8457C49.7283 11.8457 50.1629 11.5039 50.5975 10.3223L52.6531 4.73633H51.7596L50.3191 9.06738H50.241L48.7957 4.73633H47.8875L49.8357 10.0049L49.7381 10.3174C49.5477 10.9229 49.2547 11.1426 48.7713 11.1426C48.6541 11.1426 48.5223 11.1377 48.4197 11.1182V11.8164C48.5369 11.8359 48.6834 11.8457 48.7957 11.8457Z" + fill="currentColor" + ></path> + <g opacity="0.6"> + <path + d="M78.42 6.9958C78.42 9.15638 77.085 10.4444 75.2379 10.4444C74.2164 10.4444 73.3269 10.0276 72.9206 9.33816V12.9166H71.4929V3.65235H72.8018L72.9193 4.66772C73.3256 3.97825 74.189 3.5225 75.2366 3.5225C77.017 3.5225 78.4186 4.75861 78.4186 6.9971L78.42 6.9958ZM76.94 6.9958C76.94 5.62985 76.1288 4.78328 74.9492 4.78328C73.8232 4.77029 72.9598 5.62855 72.9598 7.00878C72.9598 8.38901 73.8246 9.18235 74.9492 9.18235C76.0739 9.18235 76.94 8.36304 76.94 6.9958Z" + fill="currentColor" + ></path> + <path + d="M86.0132 7.3736H80.8809C80.9071 8.62268 81.7313 9.2732 82.7789 9.2732C83.564 9.2732 84.2197 8.90834 84.494 8.17992H85.9479C85.5939 9.53288 84.3895 10.4444 82.7528 10.4444C80.749 10.4444 79.4271 9.06545 79.4271 6.96978C79.4271 4.87412 80.749 3.50818 82.7397 3.50818C84.7305 3.50818 86.0132 4.83517 86.0132 6.83994V7.3736ZM80.894 6.38419H84.5594C84.481 5.226 83.709 4.6404 82.7397 4.6404C81.7705 4.6404 80.9985 5.226 80.894 6.38419Z" + fill="currentColor" + ></path> + <path + d="M88.5407 3.65204C87.8745 3.65204 87.335 4.18829 87.335 4.85048V10.3156H88.7758V5.22703C88.7758 5.06213 88.9104 4.92709 89.0776 4.92709H91.2773V3.65204H88.5407Z" + fill="currentColor" + ></path> + - + <path + d="M69.1899 3.63908L67.3442 9.17039L65.3535 3.65207H63.8082L66.3606 10.2247C66.439 10.4325 66.4782 10.6026 66.4782 10.7713C66.4782 10.8635 66.469 10.9479 66.4533 11.0258L66.4494 11.0401C66.4403 11.0817 66.4298 11.1206 66.4168 11.1583L66.3201 11.5102C66.2966 11.5971 66.2169 11.6569 66.1268 11.6569H64.0956V12.9189H65.5755C66.5709 12.9189 67.3952 12.6852 67.8667 11.3829L70.6817 3.65207L69.1886 3.63908H69.1899Z" + fill="currentColor" + ></path> + <path + d="M57 10.3144H58.4264V6.72299C58.4264 5.60375 59.0417 4.82339 60.1807 4.82339C61.1761 4.81041 61.7913 5.396 61.7913 6.68404V10.3144H63.2191V6.46201C63.2191 4.18457 61.8188 3.50809 60.5478 3.50809C59.5785 3.50809 58.8196 3.88593 58.4264 4.51047V0.919022H57V10.3144Z" + fill="currentColor" + ></path> + <path + d="M93.1623 8.29808C93.1753 8.98755 93.8167 9.39136 94.6945 9.39136C95.5723 9.39136 96.0948 9.06545 96.0948 8.47986C96.0948 7.97218 95.8336 7.69951 95.0733 7.58135L93.7253 7.34763C92.4164 7.1269 91.9057 6.44912 91.9057 5.49997C91.9057 4.30282 93.097 3.52246 94.6161 3.52246C96.2529 3.52246 97.4442 4.30282 97.4572 5.63111H96.0439C96.0308 4.95463 95.4417 4.57679 94.6174 4.57679C93.7932 4.57679 93.3347 4.90269 93.3347 5.44933C93.3347 5.93105 93.6756 6.15178 94.4215 6.28162L95.7434 6.51534C96.987 6.73607 97.563 7.34763 97.563 8.35002C97.563 9.72895 96.2803 10.4457 94.722 10.4457C92.9546 10.4457 91.7633 9.60041 91.7372 8.29808H93.1649H93.1623Z" + fill="currentColor" + ></path> + <path + d="M100.808 8.75352L102.327 3.652H103.82L105.313 8.75352L106.583 3.652H108.089L106.191 10.3155H104.58L103.061 5.23997L101.529 10.3155H99.9052L97.9941 3.652H99.5002L100.809 8.75352H100.808Z" + fill="currentColor" + ></path> + <path + d="M108.926 0.918945H110.511V2.40305H108.926V0.918945ZM109.005 3.65214H110.431V10.3157H109.005V3.65214Z" + fill="currentColor" + ></path> + <path + d="M119.504 4.7452C118.391 4.7452 117.632 5.55152 117.632 6.9707C117.632 8.46779 118.417 9.19621 119.465 9.19621C120.302 9.19621 120.919 8.72748 121.193 7.84325H122.712C122.371 9.45719 121.141 10.4466 119.491 10.4466C117.502 10.4466 116.165 9.06767 116.165 6.972C116.165 4.87634 117.5 3.51039 119.504 3.51039C121.141 3.51039 122.358 4.43487 122.712 6.04752H121.167C120.932 5.21523 120.289 4.7465 119.504 4.7465V4.7452Z" + fill="currentColor" + ></path> + <path + d="M113.959 9.05208C113.875 9.05208 113.809 8.98456 113.809 8.90276V4.91399H115.367V3.65191H113.809V1.86787H112.382V3.02607C112.382 3.44287 112.252 3.65062 111.833 3.65062H111.256V4.91269H112.382V8.50414C112.382 9.66234 113.024 10.3128 114.189 10.3128H115.354V9.05078H113.96L113.959 9.05208Z" + fill="currentColor" + ></path> + <path + d="M127.329 3.50801C126.359 3.50801 125.601 3.88585 125.207 4.5104V0.918945H123.781V10.3144H125.207V6.72292C125.207 5.60367 125.823 4.82332 126.962 4.82332C127.957 4.81033 128.572 5.39592 128.572 6.68397V10.3144H130V6.46193C130 4.18449 128.6 3.50801 127.329 3.50801Z" + fill="currentColor" + ></path> + </g> + </svg> + </div> + </body> + + <script> + {{ payment_details_js_script }} + + window.state = { + prevHeight: window.innerHeight, + prevWidth: window.innerWidth, + isMobileView: window.innerWidth <= 1200, + } + + var widgets = null; + + window.__PAYMENT_DETAILS = {}; + try { + window.__PAYMENT_DETAILS = JSON.parse(window.__PAYMENT_DETAILS_STR); + } catch (error) { + console.error("Failed to parse payment details"); + } + + async function initialize() { + const paymentDetails = window.__PAYMENT_DETAILS; + var client_secret = paymentDetails.client_secret; + const appearance = { + variables: { + colorPrimary: "rgb(0, 109, 249)", + fontFamily: "Work Sans, sans-serif", + fontSizeBase: "16px", + colorText: "rgb(51, 65, 85)", + colorTextSecondary: "#334155B3", + colorPrimaryText: "rgb(51, 65, 85)", + colorTextPlaceholder: "#33415550", + borderColor: "#33415550", + colorBackground: "rgb(255, 255, 255)", + }, + }; + + widgets = hyper.widgets({ + appearance, + clientSecret: client_secret, + }); + + const unifiedCheckoutOptions = { + layout: "tabs", + wallets: { + walletReturnUrl: paymentDetails.return_url, + style: { + theme: "dark", + type: "default", + height: 55, + }, + }, + }; + + const unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions); + unifiedCheckout.mount("#unified-checkout"); + } + initialize(); + + async function handleSubmit(e) { + setLoading(true); + const paymentDetails = window.__PAYMENT_DETAILS; + const { error, data, status } = await hyper.confirmPayment({ + widgets, + confirmParams: { + // Make sure to change this to your payment completion page + return_url: paymentDetails.return_url, + }, + }); + // This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your `return_url`. + // For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the `return_url`. + + if (error) { + if (error.type === "validation_error") { + showMessage(error.message); + } else { + showMessage("An unexpected error occurred."); + } + } else { + const { paymentIntent } = await hyper.retrievePaymentIntent( + paymentDetails.client_secret + ); + if (paymentIntent && paymentIntent.status) { + hide("#hyper-checkout-sdk"); + hide("#hyper-checkout-details"); + show("#hyper-checkout-status"); + show("#hyper-footer"); + showStatus(paymentIntent); + } + } + + setLoading(false); + } + + // Fetches the payment status after payment submission + async function checkStatus() { + const clientSecret = new URLSearchParams(window.location.search).get( + "payment_intent_client_secret" + ); + const res = { + showSdk: true, + }; + + if (!clientSecret) { + return res; + } + + const { paymentIntent } = await hyper.retrievePaymentIntent(clientSecret); + + if (!paymentIntent || !paymentIntent.status) { + return res; + } + + showStatus(paymentIntent); + res.showSdk = false; + + return res; + } + + function setPageLoading(showLoader) { + if (showLoader) { + show(".page-spinner"); + } else { + hide(".page-spinner"); + } + } + + function setLoading(showLoader) { + if (showLoader) { + show(".spinner"); + hide("#button-text"); + } else { + hide(".spinner"); + show("#button-text"); + } + } + + function show(id) { + removeClass(id, "hidden"); + } + function hide(id) { + addClass(id, "hidden"); + } + + function showMessage(msg) { + show("#payment-message"); + addText("#payment-message", msg); + } + function showStatus(paymentDetails) { + const status = paymentDetails.status; + let statusDetails = { + imageSource: "", + message: "", + status: status, + amountText: "", + items: [], + }; + + switch (status) { + case "succeeded": + statusDetails.imageSource = + "http://www.clipartbest.com/cliparts/4ib/oRa/4iboRa7RT.png"; + statusDetails.message = "Payment successful"; + statusDetails.status = "Succeeded"; + statusDetails.amountText = new Date( + paymentDetails.created + ).toTimeString(); + + // Payment details + var amountNode = createItem( + "AMOUNT PAID", + paymentDetails.currency + " " + paymentDetails.amount + ); + var paymentId = createItem("PAYMENT ID", paymentDetails.payment_id); + // @ts-ignore + statusDetails.items.push(amountNode, paymentId); + break; + + case "processing": + statusDetails.imageSource = + "http://www.clipartbest.com/cliparts/4ib/oRa/4iboRa7RT.png"; + statusDetails.message = "Payment in progress"; + statusDetails.status = "Processing"; + // Payment details + var amountNode = createItem( + "AMOUNT PAID", + paymentDetails.currency + " " + paymentDetails.amount + ); + var paymentId = createItem("PAYMENT ID", paymentDetails.payment_id); + // @ts-ignore + statusDetails.items.push(amountNode, paymentId); + break; + + case "failed": + statusDetails.imageSource = ""; + statusDetails.message = "Payment failed"; + statusDetails.status = "Failed"; + // Payment details + var amountNode = createItem( + "AMOUNT PAID", + paymentDetails.currency + " " + paymentDetails.amount + ); + var paymentId = createItem("PAYMENT ID", paymentDetails.payment_id); + // @ts-ignore + statusDetails.items.push(amountNode, paymentId); + break; + + case "cancelled": + statusDetails.imageSource = ""; + statusDetails.message = "Payment cancelled"; + statusDetails.status = "Cancelled"; + // Payment details + var amountNode = createItem( + "AMOUNT PAID", + paymentDetails.currency + " " + paymentDetails.amount + ); + var paymentId = createItem("PAYMENT ID", paymentDetails.payment_id); + // @ts-ignore + statusDetails.items.push(amountNode, paymentId); + break; + + case "requires_merchant_action": + statusDetails.imageSource = ""; + statusDetails.message = "Payment under review"; + statusDetails.status = "Under review"; + // Payment details + var amountNode = createItem( + "AMOUNT PAID", + paymentDetails.currency + " " + paymentDetails.amount + ); + var paymentId = createItem("PAYMENT ID", paymentDetails.payment_id); + var paymentId = createItem( + "MESSAGE", + "Your payment is under review by the merchant." + ); + // @ts-ignore + statusDetails.items.push(amountNode, paymentId); + break; + + default: + statusDetails.imageSource = + "http://www.clipartbest.com/cliparts/4ib/oRa/4iboRa7RT.png"; + statusDetails.message = "Something went wrong"; + statusDetails.status = "Something went wrong"; + // Error details + if (typeof paymentDetails.error === "object") { + var errorCodeNode = createItem( + "ERROR CODE", + paymentDetails.error.code + ); + var errorMessageNode = createItem( + "ERROR MESSAGE", + paymentDetails.error.message + ); + // @ts-ignore + statusDetails.items.push(errorMessageNode, errorCodeNode); + } + break; + } + + // Append status + var statusTextNode = document.getElementById("status-text"); + if (statusTextNode !== null) { + statusTextNode.innerText = statusDetails.message; + } + + // Append image + var statusImageNode = document.getElementById("status-img"); + if (statusImageNode !== null) { + statusImageNode.src = statusDetails.imageSource; + } + + // Append status details + var statusDateNode = document.getElementById("status-date"); + if (statusDateNode !== null) { + statusDateNode.innerText = statusDetails.amountText; + } + + // Append items + var statusItemNode = document.getElementById( + "hyper-checkout-status-items" + ); + if (statusItemNode !== null) { + statusDetails.items.map((item) => statusItemNode?.append(item)); + } + } + + function createItem(heading, value) { + var itemNode = document.createElement("div"); + itemNode.className = "hyper-checkout-item"; + var headerNode = document.createElement("div"); + headerNode.className = "hyper-checkout-item-header"; + headerNode.innerText = heading; + var valueNode = document.createElement("div"); + valueNode.className = "hyper-checkout-item-value"; + valueNode.innerText = value; + itemNode.append(headerNode); + itemNode.append(valueNode); + return itemNode; + } + + function addText(id, msg) { + var element = document.querySelector(id); + element.innerText = msg; + } + + function addClass(id, className) { + var element = document.querySelector(id); + element.classList.add(className); + } + + function removeClass(id, className) { + var element = document.querySelector(id); + element.classList.remove(className); + } + + function renderPaymentDetails() { + const paymentDetails = window.__PAYMENT_DETAILS; + + // Create price node + var priceNode = document.createElement("div"); + priceNode.className = "hyper-checkout-payment-price"; + priceNode.innerText = + paymentDetails.currency_symbol + paymentDetails.amount; + + // Create merchant name's node + var merchantNameNode = document.createElement("div"); + merchantNameNode.className = "hyper-checkout-payment-merchant-name"; + merchantNameNode.innerText = "Requested by " + paymentDetails.merchant; + + // Create payment ID node + var paymentIdNode = document.createElement("div"); + paymentIdNode.className = "hyper-checkout-payment-ref"; + paymentIdNode.innerText = "Ref Id: " + paymentDetails.payment_id; + + // Create merchant logo's node + var merchantLogoNode = document.createElement("img"); + merchantLogoNode.src = paymentDetails.merchant_logo; + + // Create expiry node + var paymentExpiryNode = document.createElement("div"); + paymentExpiryNode.className = "hyper-checkout-payment-footer-expiry"; + paymentExpiryNode.innerText = + "Link expires on: " + new Date(paymentDetails.expiry).toTimeString(); + + // Append information to DOM + var paymentContextNode = document.getElementById( + "hyper-checkout-payment-context" + ); + paymentContextNode.prepend(priceNode); + var paymentMerchantDetails = document.getElementById( + "hyper-checkout-payment-merchant-details" + ); + paymentMerchantDetails.append(merchantNameNode); + paymentMerchantDetails.append(paymentIdNode); + var merchantImageNode = document.getElementById( + "hyper-checkout-merchant-image" + ); + merchantImageNode.prepend(merchantLogoNode); + var footerNode = document.getElementById("hyper-checkout-payment-footer"); + footerNode.append(paymentExpiryNode); + } + + function renderCart() { + const paymentDetails = window.__PAYMENT_DETAILS; + const orderDetails = paymentDetails.order_details; + var cartNode = document.getElementById("hyper-checkout-cart"); + var cartItemsNode = document.getElementById("hyper-checkout-cart-items"); + + const MAX_ITEMS_VISIBLE_AFTER_COLLAPSE = + paymentDetails.max_items_visible_after_collapse; + + // Cart items + if (Array.isArray(orderDetails)) { + orderDetails.map((item, index) => { + // Wrappers + var itemWrapperNode = document.createElement("div"); + itemWrapperNode.className = `${ + index >= MAX_ITEMS_VISIBLE_AFTER_COLLAPSE ? "hidden " : "" + }hyper-checkout-cart-item`; + var nameAndQuantityWrapperNode = document.createElement("div"); + nameAndQuantityWrapperNode.className = + "hyper-checkout-cart-product-details"; + + // Image + var productImageNode = document.createElement("img"); + productImageNode.className = "hyper-checkout-cart-product-image"; + productImageNode.src = item.product_image; + // Product title + var productNameNode = document.createElement("div"); + productNameNode.className = "hyper-checkout-card-item-name"; + productNameNode.innerText = item.product_name; + // Product quantity + var quantityNode = document.createElement("div"); + quantityNode.className = "hyper-checkout-card-item-quantity"; + quantityNode.innerText = "Qty: " + item.quantity; + // Product price + var priceNode = document.createElement("div"); + priceNode.className = "hyper-checkout-card-item-price"; + priceNode.innerText = paymentDetails.currency_symbol + item.amount; + // Divider node + var dividerNode = document.createElement("div"); + dividerNode.className = `${ + index !== 0 && index < MAX_ITEMS_VISIBLE_AFTER_COLLAPSE + ? "" + : "hidden " + }hyper-checkout-cart-item-divider`; + // Append items + nameAndQuantityWrapperNode.append(productNameNode, quantityNode); + itemWrapperNode.append( + productImageNode, + nameAndQuantityWrapperNode, + priceNode + ); + cartItemsNode.append(dividerNode, itemWrapperNode); + }); + } + + // Expand / collapse button + const totalItems = orderDetails.length; + if (totalItems > MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) { + var expandButtonNode = document.createElement("div"); + expandButtonNode.className = "hyper-checkout-cart-button"; + expandButtonNode.onclick = handleCartView; + var buttonImageNode = document.createElement("img"); + var buttonTextNode = document.createElement("span"); + buttonTextNode.id = "hyper-checkout-cart-button-text"; + const hiddenItemsCount = + orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE; + buttonTextNode.innerText = `Show More (${hiddenItemsCount})`; + expandButtonNode.append(buttonTextNode, buttonImageNode); + cartNode.append(expandButtonNode); + } + } + + function handleCartView() { + const paymentDetails = window.__PAYMENT_DETAILS; + const orderDetails = paymentDetails.order_details; + const MAX_ITEMS_VISIBLE_AFTER_COLLAPSE = + paymentDetails.max_items_visible_after_collapse; + var itemsHTMLCollection = document.getElementsByClassName( + "hyper-checkout-cart-item" + ); + var dividerHTMLCollection = document.getElementsByClassName( + "hyper-checkout-cart-item-divider" + ); + var cartItems = [].slice.call(itemsHTMLCollection); + var dividerItems = [].slice.call(dividerHTMLCollection); + var isHidden = false; + cartItems.map((item) => { + isHidden = item.classList.contains("hidden"); + }); + + cartItems.map((item, index) => { + if (index >= MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) { + item.className = `${ + isHidden ? "" : "hidden " + }hyper-checkout-cart-item`; + } + }); + dividerItems.map((divider, index) => { + if (index >= MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) { + divider.className = `${ + isHidden ? "" : "hidden " + }hyper-checkout-cart-item-divider`; + } + }); + + var cartButtonTextNode = document.getElementById( + "hyper-checkout-cart-button-text" + ); + const hiddenItemsCount = + orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE; + cartButtonTextNode.innerText = isHidden + ? "Show Less" + : `Show More (${hiddenItemsCount})`; + } + + function hideCartInMobileView() { + window.history.back(); + hide("#hyper-checkout-cart"); + } + + function viewCartInMobileView() { + show("#hyper-checkout-cart"); + window.history.pushState("view-cart", ""); + } + + function renderSDKHeader() { + const paymentDetails = window.__PAYMENT_DETAILS; + + // SDK headers' items + var sdkHeaderItemNode = document.createElement("div"); + sdkHeaderItemNode.className = "hyper-checkout-sdk-items"; + var sdkHeaderMerchantNameNode = document.createElement("div"); + sdkHeaderMerchantNameNode.className = + "hyper-checkout-sdk-header-brand-name"; + sdkHeaderMerchantNameNode.innerText = paymentDetails.merchant; + var sdkHeaderAmountNode = document.createElement("div"); + sdkHeaderAmountNode.className = "hyper-checkout-sdk-header-amount"; + sdkHeaderAmountNode.innerText = + paymentDetails.currency + " " + paymentDetails.amount; + sdkHeaderItemNode.append(sdkHeaderMerchantNameNode); + sdkHeaderItemNode.append(sdkHeaderAmountNode); + + // Append to SDK header's node + var sdkHeaderNode = document.getElementById("hyper-checkout-sdk-header"); + if (sdkHeaderNode !== null) { + sdkHeaderNode.append(sdkHeaderLogoNode); + sdkHeaderNode.append(sdkHeaderItemNode); + } + } + + function showSDK(e) { + if (window.state.isMobileView) { + hide("#hyper-checkout-cart"); + } else { + show("#hyper-checkout-cart"); + } + setPageLoading(true); + checkStatus() + .then((res) => { + if (res.showSdk) { + renderPaymentDetails(); + renderCart(); + renderSDKHeader(); + show("#hyper-checkout-sdk"); + show("#hyper-checkout-details"); + } else { + show("#hyper-checkout-status"); + show("#hyper-footer"); + } + }) + .catch((err) => {}) + .finally(() => { + setPageLoading(false); + }); + } + + window.addEventListener("resize", (event) => { + const currentHeight = window.innerHeight; + const currentWidth = window.innerWidth; + + if (currentWidth <= 1200 && window.state.prevWidth > 1200) { + hide("#hyper-checkout-cart"); + } else if (currentWidth > 1200 && window.state.prevWidth <= 1200) { + show("#hyper-checkout-cart"); + } + + window.state.prevHeight = currentHeight; + window.state.prevWidth = currentWidth; + window.state.isMobileView = currentWidth <= 1200; + }); + </script> +</html> diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 14b97fec42e..39c709687d8 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1486,6 +1486,7 @@ where pub redirect_response: Option<api_models::payments::RedirectResponse>, pub surcharge_details: Option<SurchargeDetailsResponse>, pub frm_message: Option<FraudCheck>, + pub payment_link_data: Option<api_models::payments::PaymentLinkResponse>, } #[derive(Debug, Default, Clone)] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a4cb7b2b9e6..c513ed02ae0 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2194,6 +2194,26 @@ pub fn authenticate_client_secret( } } +pub async fn get_merchant_fullfillment_time( + payment_link_id: Option<String>, + intent_fulfillment_time: Option<i64>, + db: &dyn StorageInterface, +) -> RouterResult<Option<i64>> { + if let Some(payment_link_id) = payment_link_id { + let payment_link_db = db + .find_payment_link_by_payment_link_id(&payment_link_id) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?; + + let curr_time = common_utils::date_time::now(); + Ok(payment_link_db + .fulfilment_time + .map(|merchant_expiry_time| (merchant_expiry_time - curr_time).whole_seconds())) + } else { + Ok(intent_fulfillment_time) + } +} + pub(crate) fn validate_payment_status_against_not_allowed_statuses( intent_status: &storage_enums::IntentStatus, not_allowed_statuses: &[storage_enums::IntentStatus], @@ -2252,11 +2272,14 @@ pub async fn verify_payment_intent_time_and_client_secret( .await .change_context(errors::ApiErrorResponse::PaymentNotFound)?; - authenticate_client_secret( - Some(&cs), - &payment_intent, + let intent_fulfillment_time = get_merchant_fullfillment_time( + payment_intent.payment_link_id.clone(), merchant_account.intent_fulfillment_time, - )?; + db, + ) + .await?; + + authenticate_client_secret(Some(&cs), &payment_intent, intent_fulfillment_time)?; Ok(payment_intent) }) .await @@ -2377,6 +2400,7 @@ mod tests { connector_metadata: None, feature_metadata: None, attempt_count: 1, + payment_link_id: None, profile_id: None, merchant_decision: None, payment_confirm_source: None, @@ -2386,7 +2410,7 @@ mod tests { assert!(authenticate_client_secret( req_cs.as_ref(), &payment_intent, - merchant_fulfillment_time + merchant_fulfillment_time, ) .is_ok()); // Check if the result is an Ok variant } @@ -2424,6 +2448,7 @@ mod tests { connector_metadata: None, feature_metadata: None, attempt_count: 1, + payment_link_id: None, profile_id: None, merchant_decision: None, payment_confirm_source: None, @@ -2433,7 +2458,7 @@ mod tests { assert!(authenticate_client_secret( req_cs.as_ref(), &payment_intent, - merchant_fulfillment_time + merchant_fulfillment_time, ) .is_err()) } @@ -2471,6 +2496,7 @@ mod tests { connector_metadata: None, feature_metadata: None, attempt_count: 1, + payment_link_id: None, profile_id: None, merchant_decision: None, payment_confirm_source: None, @@ -2480,7 +2506,7 @@ mod tests { assert!(authenticate_client_secret( req_cs.as_ref(), &payment_intent, - merchant_fulfillment_time + merchant_fulfillment_time, ) .is_err()) } @@ -3380,3 +3406,24 @@ impl ApplePayData { Ok(decrypted) } } + +pub fn validate_payment_link_request( + payment_link_object: &api_models::payments::PaymentLinkObject, + confirm: Option<bool>, +) -> Result<(), errors::ApiErrorResponse> { + if let Some(cnf) = confirm { + if !cnf { + let current_time = Some(common_utils::date_time::now()); + if current_time > payment_link_object.link_expiry { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "link_expiry time cannot be less than current time".to_string(), + }); + } + } else { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "cannot confirm a payment while creating a payment link".to_string(), + }); + } + } + Ok(()) +} diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index edb6478efec..95995c46bfb 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -253,6 +253,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response, surcharge_details: None, frm_message: frm_response.ok(), + payment_link_data: None, }, Some(CustomerDetails { customer_id: request.customer_id.clone(), diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index d92d86e7923..cd221c0be70 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -173,6 +173,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data: None, }, None, )) diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index eb88265bfc8..0d5dd5c7741 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -231,6 +231,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data: None, }, None, )) diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 02965290224..25143df386a 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -248,6 +248,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response, surcharge_details: None, frm_message: None, + payment_link_data: None, }, Some(CustomerDetails { customer_id: request.customer_id.clone(), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index a40de370b36..86304cbf175 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -88,10 +88,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> "confirm", )?; + let intent_fulfillment_time = helpers::get_merchant_fullfillment_time( + payment_intent.payment_link_id.clone(), + merchant_account.intent_fulfillment_time, + db, + ) + .await?; + helpers::authenticate_client_secret( request.client_secret.as_ref(), &payment_intent, - merchant_account.intent_fulfillment_time, + intent_fulfillment_time, )?; let customer_details = helpers::get_customer_details_from_request(request); @@ -361,6 +368,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data: None, }, Some(customer_details), )) diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 0be92418183..aec9a13f038 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -70,6 +70,21 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + let payment_link_data = if let Some(payment_link_object) = &request.payment_link_object { + create_payment_link( + request, + payment_link_object.clone(), + merchant_id.clone(), + payment_id.clone(), + db, + state, + amount, + ) + .await? + } else { + None + }; + helpers::validate_business_details( request.business_country, request.business_label.as_ref(), @@ -147,6 +162,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> money, request, shipping_address.clone().map(|x| x.address_id), + payment_link_data.clone(), billing_address.clone().map(|x| x.address_id), attempt_id, state, @@ -239,7 +255,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> request.confirm, self, ); - let creds_identifier = request .merchant_connector_details .as_ref() @@ -296,6 +311,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data, }, Some(customer_details), )) @@ -431,6 +447,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let customer_id = payment_data.payment_intent.customer_id.clone(); + payment_data.payment_intent = db .update_payment_intent( payment_data.payment_intent, @@ -447,7 +464,6 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // payment_data.mandate_id = response.and_then(|router_data| router_data.request.mandate_id); - Ok(( payments::is_confirm(self, payment_data.confirm), payment_data, @@ -469,6 +485,10 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen )> { helpers::validate_customer_details_in_request(request)?; + if let Some(payment_link_object) = &request.payment_link_object { + helpers::validate_payment_link_request(payment_link_object, request.confirm)?; + } + let given_payment_id = match &request.payment_id { Some(id_type) => Some( id_type @@ -615,6 +635,7 @@ impl PaymentCreate { money: (api::Amount, enums::Currency), request: &api::PaymentsRequest, shipping_address_id: Option<String>, + payment_link_data: Option<api_models::payments::PaymentLinkResponse>, billing_address_id: Option<String>, active_attempt_id: String, state: &AppState, @@ -657,6 +678,8 @@ impl PaymentCreate { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting feature_metadata to Value")?; + let payment_link_id = payment_link_data.map(|pl_data| pl_data.payment_link_id); + Ok(storage::PaymentIntentNew { payment_id: payment_id.to_string(), merchant_id: merchant_account.merchant_id.to_string(), @@ -689,6 +712,7 @@ impl PaymentCreate { attempt_count: 1, profile_id: Some(profile_id), merchant_decision: None, + payment_link_id, payment_confirm_source: None, }) } @@ -744,3 +768,50 @@ pub fn payments_create_request_validation( let amount = req.amount.get_required_value("amount")?; Ok((amount, currency)) } + +async fn create_payment_link( + request: &api::PaymentsRequest, + payment_link_object: api_models::payments::PaymentLinkObject, + merchant_id: String, + payment_id: String, + db: &dyn StorageInterface, + state: &AppState, + amount: api::Amount, +) -> RouterResult<Option<api_models::payments::PaymentLinkResponse>> { + let created_at @ last_modified_at = Some(common_utils::date_time::now()); + let domain = if let Some(domain_name) = payment_link_object.merchant_custom_domain_name { + format!("https://{domain_name}") + } else { + state.conf.server.base_url.clone() + }; + + let payment_link_id = utils::generate_id(consts::ID_LENGTH, "plink"); + let payment_link = format!( + "{}/payment_link/{}/{}", + domain, + merchant_id.clone(), + payment_id.clone() + ); + let payment_link_req = storage::PaymentLinkNew { + payment_link_id: payment_link_id.clone(), + payment_id: payment_id.clone(), + merchant_id: merchant_id.clone(), + link_to_pay: payment_link.clone(), + amount: amount.into(), + currency: request.currency, + created_at, + last_modified_at, + fulfilment_time: payment_link_object.link_expiry, + }; + let payment_link_db = db + .insert_payment_link(payment_link_req) + .await + .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { + message: "payment link already exists!".to_string(), + })?; + + Ok(Some(api_models::payments::PaymentLinkResponse { + link: payment_link_db.link_to_pay, + payment_link_id: payment_link_db.payment_link_id, + })) +} diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index 1b33f2dddb8..77e0a7dce2b 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -197,6 +197,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data: None, }, Some(payments::CustomerDetails { customer_id: request.customer_id.clone(), diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 2e9bd3eb9ed..938ce92af29 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -159,6 +159,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: frm_response.ok(), + payment_link_data: None, }, None, )) diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index cc91482440b..1decf13b37e 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -70,11 +70,19 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> "create a session token for", )?; + let intent_fulfillment_time = helpers::get_merchant_fullfillment_time( + payment_intent.payment_link_id.clone(), + merchant_account.intent_fulfillment_time, + db, + ) + .await?; + helpers::authenticate_client_secret( Some(&request.client_secret), &payment_intent, - merchant_account.intent_fulfillment_time, + intent_fulfillment_time, )?; + let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_intent.payment_id.as_str(), @@ -193,6 +201,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data: None, }, Some(customer_details), )) diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 4979b7902c8..c3462079cb0 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -70,10 +70,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> "update", )?; + let intent_fulfillment_time = helpers::get_merchant_fullfillment_time( + payment_intent.payment_link_id.clone(), + merchant_account.intent_fulfillment_time, + db, + ) + .await?; + helpers::authenticate_client_secret( payment_intent.client_secret.as_ref(), &payment_intent, - merchant_account.intent_fulfillment_time, + intent_fulfillment_time, )?; payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( @@ -168,6 +175,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data: None, }, Some(customer_details), )) diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index c2762a96663..ed642d3c468 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -235,11 +235,18 @@ async fn get_tracker_for_sync< ) .await?; + let intent_fulfillment_time = helpers::get_merchant_fullfillment_time( + payment_intent.payment_link_id.clone(), + merchant_account.intent_fulfillment_time, + db, + ) + .await?; helpers::authenticate_client_secret( request.client_secret.as_ref(), &payment_intent, - merchant_account.intent_fulfillment_time, + intent_fulfillment_time, )?; + let payment_id_str = payment_attempt.payment_id.clone(); let mut connector_response = db @@ -402,6 +409,7 @@ async fn get_tracker_for_sync< ephemeral_key: None, multiple_capture_data, redirect_response: None, + payment_link_data: None, surcharge_details: None, frm_message: frm_response.ok(), }, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 1c7b432c327..12c065c53eb 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -82,10 +82,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> "update", )?; + let intent_fulfillment_time = helpers::get_merchant_fullfillment_time( + payment_intent.payment_link_id.clone(), + merchant_account.intent_fulfillment_time, + db, + ) + .await?; + helpers::authenticate_client_secret( request.client_secret.as_ref(), &payment_intent, - merchant_account.intent_fulfillment_time, + intent_fulfillment_time, )?; let ( token, @@ -347,6 +354,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> redirect_response: None, surcharge_details: None, frm_message: None, + payment_link_data: None, }, Some(customer_details), )) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index f93b2e9ff4a..ac15401a334 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -353,6 +353,7 @@ where { let payment_attempt = payment_data.payment_attempt; let payment_intent = payment_data.payment_intent; + let payment_link_data = payment_data.payment_link_data; let currency = payment_attempt .currency @@ -423,6 +424,7 @@ where .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_method_data", })?; + let merchant_decision = payment_intent.merchant_decision.to_owned(); let frm_message = payment_data.frm_message.map(FrmMessage::foreign_from); @@ -679,6 +681,7 @@ where .set_feature_metadata(payment_intent.feature_metadata) .set_connector_metadata(payment_intent.connector_metadata) .set_reference_id(payment_attempt.connector_response_reference_id) + .set_payment_link(payment_link_data) .set_profile_id(payment_intent.profile_id) .set_attempt_count(payment_intent.attempt_count) .to_owned(), @@ -739,6 +742,7 @@ where allowed_payment_method_types: payment_intent.allowed_payment_method_types, reference_id: payment_attempt.connector_response_reference_id, attempt_count: payment_intent.attempt_count, + payment_link: payment_link_data, ..Default::default() }, headers, diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 356c1c6a512..fae242bc6de 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -17,6 +17,7 @@ pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; +pub mod payment_link; pub mod payment_method; pub mod payout_attempt; pub mod payouts; @@ -74,6 +75,7 @@ pub trait StorageInterface: + cards_info::CardsInfoInterface + merchant_key_store::MerchantKeyStoreInterface + MasterKeyInterface + + payment_link::PaymentLinkInterface + RedisConnInterface + business_profile::BusinessProfileInterface + 'static diff --git a/crates/router/src/db/payment_link.rs b/crates/router/src/db/payment_link.rs new file mode 100644 index 00000000000..38b59b1d60d --- /dev/null +++ b/crates/router/src/db/payment_link.rs @@ -0,0 +1,66 @@ +use error_stack::IntoReport; + +use super::{MockDb, Store}; +use crate::{ + connection, + core::errors::{self, CustomResult}, + types::storage, +}; + +#[async_trait::async_trait] +pub trait PaymentLinkInterface { + async fn find_payment_link_by_payment_link_id( + &self, + payment_link_id: &str, + ) -> CustomResult<storage::PaymentLink, errors::StorageError>; + + async fn insert_payment_link( + &self, + _payment_link: storage::PaymentLinkNew, + ) -> CustomResult<storage::PaymentLink, errors::StorageError>; +} + +#[async_trait::async_trait] +impl PaymentLinkInterface for Store { + async fn find_payment_link_by_payment_link_id( + &self, + payment_link_id: &str, + ) -> CustomResult<storage::PaymentLink, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::PaymentLink::find_link_by_payment_link_id(&conn, payment_link_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn insert_payment_link( + &self, + payment_link_object: storage::PaymentLinkNew, + ) -> CustomResult<storage::PaymentLink, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + payment_link_object + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl PaymentLinkInterface for MockDb { + async fn insert_payment_link( + &self, + _payment_link: storage::PaymentLinkNew, + ) -> CustomResult<storage::PaymentLink, errors::StorageError> { + // TODO: Implement function for `MockDb` + Err(errors::StorageError::MockDbError)? + } + + async fn find_payment_link_by_payment_link_id( + &self, + _payment_link_id: &str, + ) -> CustomResult<storage::PaymentLink, errors::StorageError> { + // TODO: Implement function for `MockDb`x + Err(errors::StorageError::MockDbError)? + } +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 738646b2964..008991bb45b 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -127,7 +127,8 @@ pub fn mk_app( server_app = server_app .service(routes::PaymentMethods::server(state.clone())) .service(routes::EphemeralKey::server(state.clone())) - .service(routes::Webhooks::server(state.clone())); + .service(routes::Webhooks::server(state.clone())) + .service(routes::PaymentLink::server(state.clone())); } #[cfg(feature = "olap")] diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index a0f8643be3e..5a36b03e7ae 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -61,6 +61,7 @@ Never share your secret api keys. Keep them guarded and secure. (name = "Disputes", description = "Manage disputes"), // (name = "API Key", description = "Create and manage API Keys"), (name = "Payouts", description = "Create and manage payouts"), + (name = "payment link", description = "Create payment link"), ), paths( crate::routes::refunds::refunds_create, @@ -112,6 +113,7 @@ Never share your secret api keys. Keep them guarded and secure. crate::routes::payouts::payouts_fulfill, crate::routes::payouts::payouts_retrieve, crate::routes::payouts::payouts_update, + crate::routes::payment_link::payment_link_retrieve ), components(schemas( crate::types::api::refunds::RefundRequest, @@ -336,7 +338,12 @@ Never share your secret api keys. Keep them guarded and secure. crate::types::api::api_keys::CreateApiKeyResponse, crate::types::api::api_keys::RetrieveApiKeyResponse, crate::types::api::api_keys::RevokeApiKeyResponse, - crate::types::api::api_keys::UpdateApiKeyRequest + crate::types::api::api_keys::UpdateApiKeyRequest, + api_models::payments::RetrievePaymentLinkRequest, + api_models::payments::PaymentLinkResponse, + api_models::payments::RetrievePaymentLinkResponse, + api_models::payments::PaymentLinkInitiateRequest, + api_models::payments::PaymentLinkObject )), modifiers(&SecurityAddon) )] diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 20357040ce1..307797e8ac9 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -14,6 +14,7 @@ pub mod health; pub mod lock_utils; pub mod mandates; pub mod metrics; +pub mod payment_link; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] @@ -31,8 +32,8 @@ pub use self::app::Payouts; pub use self::app::Verify; pub use self::app::{ ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, Customers, Disputes, EphemeralKey, - Files, Health, Mandates, MerchantAccount, MerchantConnectorAccount, PaymentMethods, Payments, - Refunds, Webhooks, + Files, Health, Mandates, MerchantAccount, MerchantConnectorAccount, PaymentLink, + PaymentMethods, Payments, Refunds, Webhooks, }; #[cfg(feature = "stripe")] pub use super::compatibility::stripe::StripeApis; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 971459dc860..24d7217aefe 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -17,7 +17,7 @@ use super::payouts::*; use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "olap")] use super::{admin::*, api_keys::*, disputes::*, files::*}; -use super::{cache::*, health::*}; +use super::{cache::*, health::*, payment_link::*}; #[cfg(any(feature = "olap", feature = "oltp"))] use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*}; #[cfg(feature = "oltp")] @@ -576,6 +576,22 @@ impl Cache { } } +pub struct PaymentLink; + +impl PaymentLink { + pub fn server(state: AppState) -> Scope { + web::scope("/payment_link") + .app_data(web::Data::new(state)) + .service( + web::resource("/{payment_link_id}").route(web::get().to(payment_link_retrieve)), + ) + .service( + web::resource("{merchant_id}/{payment_id}") + .route(web::get().to(initiate_payment_link)), + ) + } +} + pub struct BusinessProfile; #[cfg(feature = "olap")] diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 80763ab434f..cec510cd0c7 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -21,6 +21,7 @@ pub enum ApiIdentifier { Business, Verification, ApiKeys, + PaymentLink, } impl From<Flow> for ApiIdentifier { @@ -112,6 +113,8 @@ impl From<Flow> for ApiIdentifier { | Flow::BusinessProfileList => Self::Business, Flow::Verification => Self::Verification, + + Flow::PaymentLinkInitiate | Flow::PaymentLinkRetrieve => Self::PaymentLink, } } } diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs index 1f1a9b3e382..30db586b7f9 100644 --- a/crates/router/src/routes/metrics/request.rs +++ b/crates/router/src/routes/metrics/request.rs @@ -60,6 +60,7 @@ pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 { | ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::Form(_) + | ApplicationResponse::PaymenkLinkForm(_) | ApplicationResponse::FileData(_) | ApplicationResponse::JsonWithHeaders(_) => 200, ApplicationResponse::JsonForRedirection(_) => 302, diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs new file mode 100644 index 00000000000..b664ee4429d --- /dev/null +++ b/crates/router/src/routes/payment_link.rs @@ -0,0 +1,82 @@ +use actix_web::{web, Responder}; +use router_env::{instrument, tracing, Flow}; + +use crate::{ + core::{api_locking, payment_link::*}, + services::{api, authentication as auth}, + AppState, +}; + +/// Payments Link - Retrieve +/// +/// To retrieve the properties of a Payment Link. This may be used to get the status of a previously initiated payment or next action for an ongoing payment +#[utoipa::path( + get, + path = "/payment_link/{payment_link_id}", + params( + ("payment_link_id" = String, Path, description = "The identifier for payment link") + ), + request_body=RetrievePaymentLinkRequest, + responses( + (status = 200, description = "Gets details regarding payment link", body = RetrievePaymentLinkResponse), + (status = 404, description = "No payment link found") + ), + tag = "Payments", + operation_id = "Retrieve a Payment Link", + security(("api_key" = []), ("publishable_key" = [])) +)] +#[instrument(skip(state, req), fields(flow = ?Flow::PaymentLinkRetrieve))] + +pub async fn payment_link_retrieve( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + path: web::Path<String>, + json_payload: web::Query<api_models::payments::RetrievePaymentLinkRequest>, +) -> impl Responder { + let flow = Flow::PaymentLinkRetrieve; + let payload = json_payload.into_inner(); + let (auth_type, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { + Ok(auth) => auth, + Err(err) => return api::log_and_return_error_response(error_stack::report!(err)), + }; + api::server_wrap( + flow, + state, + &req, + payload.clone(), + |state, _auth, _| retrieve_payment_link(state, path.clone()), + &*auth_type, + api_locking::LockAction::NotApplicable, + ) + .await +} + +pub async fn initiate_payment_link( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + path: web::Path<(String, String)>, +) -> impl Responder { + let flow = Flow::PaymentLinkInitiate; + let (merchant_id, payment_id) = path.into_inner(); + let payload = api_models::payments::PaymentLinkInitiateRequest { + payment_id, + merchant_id: merchant_id.clone(), + }; + api::server_wrap( + flow, + state, + &req, + payload.clone(), + |state, auth, _| { + intiate_payment_link_flow( + state, + auth.merchant_account, + payload.merchant_id.clone(), + payload.payment_id.clone(), + ) + }, + &crate::services::authentication::MerchantIdAuth(merchant_id), + api_locking::LockAction::NotApplicable, + ) + .await +} diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index def00bb3f2f..b56e55b6c7b 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1,6 +1,5 @@ pub mod client; pub mod request; - use std::{ collections::HashMap, error::Error, @@ -20,6 +19,7 @@ use masking::{ExposeOptionInterface, PeekInterface}; use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag}; use serde::Serialize; use serde_json::json; +use tera::{Context, Tera}; use self::request::{HeaderExt, RequestBuilderExt}; use crate::{ @@ -655,10 +655,17 @@ pub enum ApplicationResponse<R> { TextPlain(String), JsonForRedirection(api::RedirectionResponse), Form(Box<RedirectionFormData>), + PaymenkLinkForm(Box<PaymentLinkFormData>), FileData((Vec<u8>, mime::Mime)), JsonWithHeaders((R, Vec<(String, String)>)), } +#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentLinkFormData { + pub js_script: String, + pub sdk_url: String, +} + #[derive(Debug, Eq, PartialEq)] pub struct RedirectionFormData { pub redirect_form: RedirectForm, @@ -887,6 +894,20 @@ where .respond_to(request) .map_into_boxed_body() } + + Ok(ApplicationResponse::PaymenkLinkForm(payment_link_data)) => { + match build_payment_link_html(*payment_link_data) { + Ok(rendered_html) => http_response_html_data(rendered_html), + Err(_) => http_response_err( + r#"{ + "error": { + "message": "Error while rendering payment link html page" + } + }"#, + ), + } + } + Ok(ApplicationResponse::JsonWithHeaders((response, headers))) => { let request_elapsed_time = request.headers().get(X_HS_LATENCY).and_then(|value| { if value == "true" { @@ -1006,6 +1027,10 @@ pub fn http_response_file_data<T: body::MessageBody + 'static>( HttpResponse::Ok().content_type(content_type).body(res) } +pub fn http_response_html_data<T: body::MessageBody + 'static>(res: T) -> HttpResponse { + HttpResponse::Ok().content_type(mime::TEXT_HTML).body(res) +} + pub fn http_response_ok() -> HttpResponse { HttpResponse::Ok().finish() } @@ -1329,3 +1354,32 @@ mod tests { assert_eq!(mime::APPLICATION_JSON.essence_str(), "application/json"); } } + +pub fn build_payment_link_html( + payment_link_data: PaymentLinkFormData, +) -> CustomResult<String, errors::ApiErrorResponse> { + let html_template = include_str!("../core/payment_link/payment_link.html").to_string(); + + let mut tera = Tera::default(); + + let _ = tera.add_raw_template("payment_link", &html_template); + + let mut context = Context::new(); + context.insert( + "hyperloader_sdk_link", + &get_hyper_loader_sdk(&payment_link_data.sdk_url), + ); + context.insert("payment_details_js_script", &payment_link_data.js_script); + + match tera.render("payment_link", &context) { + Ok(rendered_html) => Ok(rendered_html), + Err(tera_error) => { + crate::logger::warn!("{tera_error}"); + Err(errors::ApiErrorResponse::InternalServerError)? + } + } +} + +fn get_hyper_loader_sdk(sdk_url: &str) -> String { + format!("<script src=\"{sdk_url}\"></script>") +} diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 922d560a4a2..eec872a9f34 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -378,6 +378,12 @@ impl ClientSecretFetch for api_models::payments::PaymentsRetrieveRequest { } } +impl ClientSecretFetch for api_models::payments::RetrievePaymentLinkRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + pub fn get_auth_type_and_flow<A: AppStateInfo + Sync>( headers: &HeaderMap, ) -> RouterResult<( diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 9995f7cce89..623a5f94989 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -19,6 +19,7 @@ pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod payment_attempt; +pub mod payment_link; pub mod payment_method; pub use diesel_models::{ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate}; pub use scheduler::db::process_tracker; @@ -37,8 +38,9 @@ pub use data_models::payments::{ pub use self::{ address::*, api_keys::*, capture::*, cards_info::*, configs::*, connector_response::*, customers::*, dispute::*, ephemeral_key::*, events::*, file::*, locker_mock_up::*, mandate::*, - merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_method::*, - payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*, + merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, + payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*, + reverse_lookup::*, }; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] diff --git a/crates/router/src/types/storage/payment_link.rs b/crates/router/src/types/storage/payment_link.rs new file mode 100644 index 00000000000..1fa2465e513 --- /dev/null +++ b/crates/router/src/types/storage/payment_link.rs @@ -0,0 +1 @@ +pub use diesel_models::payment_link::{PaymentLink, PaymentLinkNew}; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 04334fc201f..2e376b0c218 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -831,6 +831,22 @@ impl } } +impl ForeignFrom<storage::PaymentLink> for api_models::payments::RetrievePaymentLinkResponse { + fn foreign_from(payment_link_object: storage::PaymentLink) -> Self { + Self { + payment_link_id: payment_link_object.payment_link_id, + payment_id: payment_link_object.payment_id, + merchant_id: payment_link_object.merchant_id, + link_to_pay: payment_link_object.link_to_pay, + amount: payment_link_object.amount, + currency: payment_link_object.currency, + created_at: payment_link_object.created_at, + last_modified_at: payment_link_object.last_modified_at, + link_expiry: payment_link_object.fulfilment_time, + } + } +} + impl From<domain::Address> for payments::AddressDetails { fn from(addr: domain::Address) -> Self { Self { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index d633cb4a5ee..e838c5d9d53 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -195,6 +195,10 @@ pub enum Flow { RetrieveDisputeEvidence, /// Invalidate cache flow CacheInvalidate, + /// Payment Link Retrieve flow + PaymentLinkRetrieve, + /// payment Link Initiate flow + PaymentLinkInitiate, /// Create a business profile BusinessProfileCreate, /// Update a business profile diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index e41d7a3aba0..ca043ac587b 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -40,6 +40,7 @@ pub struct MockDb { pub merchant_key_store: Arc<Mutex<Vec<crate::store::merchant_key_store::MerchantKeyStore>>>, pub business_profiles: Arc<Mutex<Vec<crate::store::business_profile::BusinessProfile>>>, pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>, + pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>, } impl MockDb { @@ -72,6 +73,7 @@ impl MockDb { merchant_key_store: Default::default(), business_profiles: Default::default(), reverse_lookups: Default::default(), + payment_link: Default::default(), }) } } diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index 43d7207d452..2dc720b9f5d 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -105,6 +105,7 @@ impl PaymentIntentInterface for MockDb { attempt_count: new.attempt_count, profile_id: new.profile_id, merchant_decision: new.merchant_decision, + payment_link_id: new.payment_link_id, payment_confirm_source: new.payment_confirm_source, }; payment_intents.push(payment_intent.clone()); diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 6814512028b..c4718b34258 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -90,6 +90,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { attempt_count: new.attempt_count, profile_id: new.profile_id.clone(), merchant_decision: new.merchant_decision.clone(), + payment_link_id: new.payment_link_id.clone(), payment_confirm_source: new.payment_confirm_source, }; @@ -697,6 +698,7 @@ impl DataModelExt for PaymentIntentNew { attempt_count: self.attempt_count, profile_id: self.profile_id, merchant_decision: self.merchant_decision, + payment_link_id: self.payment_link_id, payment_confirm_source: self.payment_confirm_source, } } @@ -734,6 +736,7 @@ impl DataModelExt for PaymentIntentNew { attempt_count: storage_model.attempt_count, profile_id: storage_model.profile_id, merchant_decision: storage_model.merchant_decision, + payment_link_id: storage_model.payment_link_id, payment_confirm_source: storage_model.payment_confirm_source, } } @@ -766,9 +769,9 @@ impl DataModelExt for PaymentIntent { setup_future_usage: self.setup_future_usage, off_session: self.off_session, client_secret: self.client_secret, - active_attempt_id: self.active_attempt_id, business_country: self.business_country, business_label: self.business_label, + active_attempt_id: self.active_attempt_id, order_details: self.order_details, allowed_payment_method_types: self.allowed_payment_method_types, connector_metadata: self.connector_metadata, @@ -776,6 +779,7 @@ impl DataModelExt for PaymentIntent { attempt_count: self.attempt_count, profile_id: self.profile_id, merchant_decision: self.merchant_decision, + payment_link_id: self.payment_link_id, payment_confirm_source: self.payment_confirm_source, } } @@ -814,6 +818,7 @@ impl DataModelExt for PaymentIntent { attempt_count: storage_model.attempt_count, profile_id: storage_model.profile_id, merchant_decision: storage_model.merchant_decision, + payment_link_id: storage_model.payment_link_id, payment_confirm_source: storage_model.payment_confirm_source, } } diff --git a/migrations/2023-09-08-101302_add_payment_link/down.sql b/migrations/2023-09-08-101302_add_payment_link/down.sql new file mode 100644 index 00000000000..f2ff37da558 --- /dev/null +++ b/migrations/2023-09-08-101302_add_payment_link/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +drop table payment_link; \ No newline at end of file diff --git a/migrations/2023-09-08-101302_add_payment_link/up.sql b/migrations/2023-09-08-101302_add_payment_link/up.sql new file mode 100644 index 00000000000..565f53d9e5c --- /dev/null +++ b/migrations/2023-09-08-101302_add_payment_link/up.sql @@ -0,0 +1,13 @@ +-- Your SQL goes here +CREATE TABLE payment_link ( + payment_link_id VARCHAR(255) NOT NULL, + payment_id VARCHAR(64) NOT NULL, + link_to_pay VARCHAR(255) NOT NULL, + merchant_id VARCHAR(64) NOT NULL, + amount INT8 NOT NULL, + currency "Currency", + created_at TIMESTAMP NOT NULL, + last_modified_at TIMESTAMP NOT NULL, + fulfilment_time TIMESTAMP, + PRIMARY KEY (payment_link_id) +); diff --git a/migrations/2023-09-08-114828_add_payment_link_id_in_payment_intent/down.sql b/migrations/2023-09-08-114828_add_payment_link_id_in_payment_intent/down.sql new file mode 100644 index 00000000000..6cead956239 --- /dev/null +++ b/migrations/2023-09-08-114828_add_payment_link_id_in_payment_intent/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent DROP COLUMN payment_link_id; diff --git a/migrations/2023-09-08-114828_add_payment_link_id_in_payment_intent/up.sql b/migrations/2023-09-08-114828_add_payment_link_id_in_payment_intent/up.sql new file mode 100644 index 00000000000..9c827740a98 --- /dev/null +++ b/migrations/2023-09-08-114828_add_payment_link_id_in_payment_intent/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD column payment_link_id VARCHAR(255); \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 27b73f1c097..d9fd4055c94 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -794,6 +794,60 @@ ] } }, + "/payment_link/{payment_link_id}": { + "get": { + "tags": [ + "Payments" + ], + "summary": "Payments Link - Retrieve", + "description": "Payments Link - Retrieve\n\nTo retrieve the properties of a Payment Link. This may be used to get the status of a previously initiated payment or next action for an ongoing payment", + "operationId": "Retrieve a Payment Link", + "parameters": [ + { + "name": "payment_link_id", + "in": "path", + "description": "The identifier for payment link", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetrievePaymentLinkRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Gets details regarding payment link", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetrievePaymentLinkResponse" + } + } + } + }, + "404": { + "description": "No payment link found" + } + }, + "security": [ + { + "api_key": [] + }, + { + "publishable_key": [] + } + ] + } + }, "/payment_methods": { "post": { "tags": [ @@ -7710,6 +7764,50 @@ } ] }, + "PaymentLinkInitiateRequest": { + "type": "object", + "required": [ + "merchant_id", + "payment_id" + ], + "properties": { + "merchant_id": { + "type": "string" + }, + "payment_id": { + "type": "string" + } + } + }, + "PaymentLinkObject": { + "type": "object", + "properties": { + "link_expiry": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "merchant_custom_domain_name": { + "type": "string", + "nullable": true + } + } + }, + "PaymentLinkResponse": { + "type": "object", + "required": [ + "link", + "payment_link_id" + ], + "properties": { + "link": { + "type": "string" + }, + "payment_link_id": { + "type": "string" + } + } + }, "PaymentListConstraints": { "type": "object", "properties": { @@ -8769,6 +8867,14 @@ ], "nullable": true }, + "payment_link_object": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkObject" + } + ], + "nullable": true + }, "profile_id": { "type": "string", "description": "The business profile to use for this payment, if not passed the default business profile\nassociated with the merchant account will be used.", @@ -9116,6 +9222,14 @@ ], "nullable": true }, + "payment_link_object": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkObject" + } + ], + "nullable": true + }, "profile_id": { "type": "string", "description": "The business profile to use for this payment, if not passed the default business profile\nassociated with the merchant account will be used.", @@ -9510,6 +9624,14 @@ "example": "993672945374576J", "nullable": true }, + "payment_link": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentLinkResponse" + } + ], + "nullable": true + }, "profile_id": { "type": "string", "description": "The business profile that is associated with this payment", @@ -10573,6 +10695,66 @@ } } }, + "RetrievePaymentLinkRequest": { + "type": "object", + "properties": { + "client_secret": { + "type": "string", + "nullable": true + } + } + }, + "RetrievePaymentLinkResponse": { + "type": "object", + "required": [ + "payment_link_id", + "payment_id", + "merchant_id", + "link_to_pay", + "amount", + "created_at", + "last_modified_at" + ], + "properties": { + "payment_link_id": { + "type": "string" + }, + "payment_id": { + "type": "string" + }, + "merchant_id": { + "type": "string" + }, + "link_to_pay": { + "type": "string" + }, + "amount": { + "type": "integer", + "format": "int64" + }, + "currency": { + "allOf": [ + { + "$ref": "#/components/schemas/Currency" + } + ], + "nullable": true + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "last_modified_at": { + "type": "string", + "format": "date-time" + }, + "link_expiry": { + "type": "string", + "format": "date-time", + "nullable": true + } + } + }, "RetryAction": { "type": "string", "enum": [ @@ -11508,6 +11690,10 @@ { "name": "Payouts", "description": "Create and manage payouts" + }, + { + "name": "payment link", + "description": "Create payment link" } ] } \ No newline at end of file
feat
Add payment link support (#2105)
ba75a3f5a936ec981422bbe3c4fbdd9f12928615
2024-10-10 20:33:12
Shankar Singh C
feat(router): add network transaction id support for mit payments (#6245)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 9a852bb15cc..3f57faaf1d7 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -10093,6 +10093,77 @@ } } }, + "NetworkTransactionIdAndCardDetails": { + "type": "object", + "required": [ + "card_number", + "card_exp_month", + "card_exp_year", + "card_holder_name", + "network_transaction_id" + ], + "properties": { + "card_number": { + "type": "string", + "description": "The card number", + "example": "4242424242424242" + }, + "card_exp_month": { + "type": "string", + "description": "The card's expiry month", + "example": "24" + }, + "card_exp_year": { + "type": "string", + "description": "The card's expiry year", + "example": "24" + }, + "card_holder_name": { + "type": "string", + "description": "The card holder's name", + "example": "John Test" + }, + "card_issuer": { + "type": "string", + "description": "The name of the issuer of card", + "example": "chase", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "example": "CREDIT", + "nullable": true + }, + "card_issuing_country": { + "type": "string", + "example": "INDIA", + "nullable": true + }, + "bank_code": { + "type": "string", + "example": "JP_AMEX", + "nullable": true + }, + "nick_name": { + "type": "string", + "description": "The card holder's nick name", + "example": "John Test", + "nullable": true + }, + "network_transaction_id": { + "type": "string", + "description": "The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction),\nwhere `setup_future_usage` is set to `off_session`." + } + } + }, "NextActionCall": { "type": "string", "enum": [ @@ -17898,6 +17969,24 @@ "$ref": "#/components/schemas/ProcessorPaymentToken" } } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "network_transaction_id_and_card_details" + ] + }, + "data": { + "$ref": "#/components/schemas/NetworkTransactionIdAndCardDetails" + } + } } ], "description": "Details required for recurring payment", diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index c0b8a0d2f0e..4b10cf3299b 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -13737,6 +13737,77 @@ } } }, + "NetworkTransactionIdAndCardDetails": { + "type": "object", + "required": [ + "card_number", + "card_exp_month", + "card_exp_year", + "card_holder_name", + "network_transaction_id" + ], + "properties": { + "card_number": { + "type": "string", + "description": "The card number", + "example": "4242424242424242" + }, + "card_exp_month": { + "type": "string", + "description": "The card's expiry month", + "example": "24" + }, + "card_exp_year": { + "type": "string", + "description": "The card's expiry year", + "example": "24" + }, + "card_holder_name": { + "type": "string", + "description": "The card holder's name", + "example": "John Test" + }, + "card_issuer": { + "type": "string", + "description": "The name of the issuer of card", + "example": "chase", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "example": "CREDIT", + "nullable": true + }, + "card_issuing_country": { + "type": "string", + "example": "INDIA", + "nullable": true + }, + "bank_code": { + "type": "string", + "example": "JP_AMEX", + "nullable": true + }, + "nick_name": { + "type": "string", + "description": "The card holder's nick name", + "example": "John Test", + "nullable": true + }, + "network_transaction_id": { + "type": "string", + "description": "The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction),\nwhere `setup_future_usage` is set to `off_session`." + } + } + }, "NextActionCall": { "type": "string", "enum": [ @@ -21677,6 +21748,24 @@ "$ref": "#/components/schemas/ProcessorPaymentToken" } } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "network_transaction_id_and_card_details" + ] + }, + "data": { + "$ref": "#/components/schemas/NetworkTransactionIdAndCardDetails" + } + } } ], "description": "Details required for recurring payment", diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index fe5b053b180..2d61a630988 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -121,6 +121,10 @@ pub enum RecurringDetails { MandateId(String), PaymentMethodId(String), ProcessorPaymentToken(ProcessorPaymentToken), + + /// Network transaction ID and Card Details for MIT payments when payment_method_data + /// is not stored in the application + NetworkTransactionIdAndCardDetails(NetworkTransactionIdAndCardDetails), } /// Processor payment token for MIT payments where payment_method_data is not available @@ -130,3 +134,54 @@ pub struct ProcessorPaymentToken { #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] +pub struct NetworkTransactionIdAndCardDetails { + /// The card number + #[schema(value_type = String, example = "4242424242424242")] + pub card_number: cards::CardNumber, + + /// The card's expiry month + #[schema(value_type = String, example = "24")] + pub card_exp_month: Secret<String>, + + /// The card's expiry year + #[schema(value_type = String, example = "24")] + pub card_exp_year: Secret<String>, + + /// The card holder's name + #[schema(value_type = String, example = "John Test")] + pub card_holder_name: Option<Secret<String>>, + + /// The name of the issuer of card + #[schema(example = "chase")] + pub card_issuer: Option<String>, + + /// The card network for the card + #[schema(value_type = Option<CardNetwork>, example = "Visa")] + pub card_network: Option<api_enums::CardNetwork>, + + #[schema(example = "CREDIT")] + pub card_type: Option<String>, + + #[schema(example = "INDIA")] + pub card_issuing_country: Option<String>, + + #[schema(example = "JP_AMEX")] + pub bank_code: Option<String>, + + /// The card holder's nick name + #[schema(value_type = Option<String>, example = "John Test")] + pub nick_name: Option<Secret<String>>, + + /// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction), + /// where `setup_future_usage` is set to `off_session`. + #[schema(value_type = String)] + pub network_transaction_id: Secret<String>, +} + +impl RecurringDetails { + pub fn is_network_transaction_id_and_card_details_flow(self) -> bool { + matches!(self, Self::NetworkTransactionIdAndCardDetails(_)) + } +} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9df0eca96d8..cda790b5959 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1133,6 +1133,15 @@ pub struct MandateIds { pub mandate_reference_id: Option<MandateReferenceId>, } +impl MandateIds { + pub fn is_network_transaction_id_flow(&self) -> bool { + matches!( + self.mandate_reference_id, + Some(MandateReferenceId::NetworkMandateId(_)) + ) + } +} + #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector @@ -4969,7 +4978,7 @@ pub struct PazeMetadata { pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption - // will be obtained from the environment variables. + // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } diff --git a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs index b8c75e3c4db..4212f7168db 100644 --- a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs @@ -224,10 +224,13 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("bambora"), - ) - .into()), + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("bambora"), + ) + .into()) + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index 03a585f76bd..4440346db6b 100644 --- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -86,9 +86,12 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("CryptoPay"), - )), + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("CryptoPay"), + )) + } }?; Ok(cryptopay_request) } diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs index 385601294b3..d21fa481579 100644 --- a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs @@ -171,9 +171,12 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - crate::utils::get_unimplemented_payment_method_error_message("Dlocal"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + crate::utils::get_unimplemented_payment_method_error_message("Dlocal"), + ))? + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs index b2cbd570b4f..cdcd82f5b4f 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs @@ -199,7 +199,8 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => { + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("fiserv"), )) diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index c4ca017cec7..c06f0a208e5 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -413,10 +413,13 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::OpenBanking(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("fiuu"), - ) - .into()), + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("fiuu"), + ) + .into()) + } }?; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs index 772f2af209e..2e3919cfc48 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs @@ -101,9 +101,12 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("globepay"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("globepay"), + ))? + } }; let description = item.get_description()?; Ok(Self { diff --git a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs index 90380d02321..a01e2cf918d 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs @@ -181,9 +181,12 @@ impl TryFrom<&SetupMandateRouterData> for HelcimVerifyRequest { | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - crate::utils::get_unimplemented_payment_method_error_message("Helcim"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + crate::utils::get_unimplemented_payment_method_error_message("Helcim"), + ))? + } } } } @@ -275,9 +278,12 @@ impl TryFrom<&HelcimRouterData<&PaymentsAuthorizeRouterData>> for HelcimPayments | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - crate::utils::get_unimplemented_payment_method_error_message("Helcim"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + crate::utils::get_unimplemented_payment_method_error_message("Helcim"), + ))? + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs index 54856d4dba5..1677343fe38 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs @@ -413,9 +413,12 @@ impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaym | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - get_unimplemented_payment_method_error_message("nexixpay"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + get_unimplemented_payment_method_error_message("nexixpay"), + ))? + } } } } @@ -828,7 +831,8 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>> | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => { + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message("nexixpay"), ) diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs index 5ea64f8b958..770688a3468 100644 --- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs @@ -126,11 +126,14 @@ impl TryFrom<&PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest { | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "powertranz", + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "powertranz", + } + .into()) } - .into()), }?; // let billing_address = get_address_details(&item.address.billing, &item.request.email); // let shipping_address = get_address_details(&item.address.shipping, &item.request.email); diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index ad09e7445d4..b2151c524be 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -177,9 +177,12 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { | PaymentMethodData::Voucher(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))? + } } } } @@ -294,9 +297,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { | PaymentMethodData::Voucher(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))? + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs index 686178e9621..0f112566796 100644 --- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs @@ -124,9 +124,12 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme | PaymentMethodData::Upi(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Stax"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))? + } } } } @@ -275,9 +278,12 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { | PaymentMethodData::Upi(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Stax"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))? + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index 8d96058c233..e97cf228729 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -90,9 +90,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("tsys"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("tsys"), + ))? + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 953b6316ff8..e04eae63b4c 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -148,10 +148,13 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Volt"), - ) - .into()), + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Volt"), + ) + .into()) + } } } } diff --git a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs index 33c865c3b5f..09ffac81425 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs @@ -218,38 +218,40 @@ impl &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>, >, ) -> Result<Self, Self::Error> { - let payment_data = match &item.router_data.request.payment_method_data { - PaymentMethodData::Card(card) => { - let card_holder_name = item.router_data.get_optional_billing_full_name(); - WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(make_card_request( - &item.router_data.request, - card, - card_holder_name, - )?)) - } - PaymentMethodData::BankRedirect(bank_redirect) => { - WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new( - make_bank_redirect_request(item.router_data, bank_redirect)?, - )) - } - PaymentMethodData::CardRedirect(_) - | PaymentMethodData::Wallet(_) - | PaymentMethodData::PayLater(_) - | PaymentMethodData::BankDebit(_) - | PaymentMethodData::BankTransfer(_) - | PaymentMethodData::Crypto(_) - | PaymentMethodData::MandatePayment - | PaymentMethodData::Reward - | PaymentMethodData::RealTimePayment(_) - | PaymentMethodData::Upi(_) - | PaymentMethodData::Voucher(_) - | PaymentMethodData::GiftCard(_) - | PaymentMethodData::OpenBanking(_) - | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("worldline"), - ))?, - }; + let payment_data = + match &item.router_data.request.payment_method_data { + PaymentMethodData::Card(card) => { + let card_holder_name = item.router_data.get_optional_billing_full_name(); + WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new( + make_card_request(&item.router_data.request, card, card_holder_name)?, + )) + } + PaymentMethodData::BankRedirect(bank_redirect) => { + WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new( + make_bank_redirect_request(item.router_data, bank_redirect)?, + )) + } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("worldline"), + ))? + } + }; let billing_address = item.router_data.get_billing()?; diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 66b8081b0f2..0134253f2f9 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1861,6 +1861,7 @@ pub enum PaymentMethodDataType { VietQr, OpenBanking, NetworkToken, + NetworkTransactionIdAndCardDetails, } impl From<PaymentMethodData> for PaymentMethodDataType { @@ -1868,6 +1869,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType { match pm_data { PaymentMethodData::Card(_) => Self::Card, PaymentMethodData::NetworkToken(_) => Self::NetworkToken, + PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::NetworkTransactionIdAndCardDetails, PaymentMethodData::CardRedirect(card_redirect_data) => { match card_redirect_data { hyperswitch_domain_models::payment_method_data::CardRedirectData::Knet {} => Self::Knet, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 3ccfabf021c..5c4979ab49d 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -1,4 +1,7 @@ -use api_models::payments::{additional_info as payment_additional_types, ExtendedCardInfo}; +use api_models::{ + mandates, + payments::{additional_info as payment_additional_types, ExtendedCardInfo}, +}; use common_enums::enums as api_enums; use common_utils::{ id_type, @@ -16,6 +19,7 @@ use time::Date; #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] pub enum PaymentMethodData { Card(Card), + CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId), CardRedirect(CardRedirectData), Wallet(WalletData), PayLater(PayLaterData), @@ -43,7 +47,9 @@ pub enum ApplePayFlow { impl PaymentMethodData { pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { match self { - Self::Card(_) | Self::NetworkToken(_) => Some(common_enums::PaymentMethod::Card), + Self::Card(_) | Self::NetworkToken(_) | Self::CardDetailsForNetworkTransactionId(_) => { + Some(common_enums::PaymentMethod::Card) + } Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater), @@ -76,6 +82,62 @@ pub struct Card { pub nick_name: Option<Secret<String>>, } +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] +pub struct CardDetailsForNetworkTransactionId { + pub card_number: cards::CardNumber, + pub card_exp_month: Secret<String>, + pub card_exp_year: Secret<String>, + pub card_issuer: Option<String>, + pub card_network: Option<common_enums::CardNetwork>, + pub card_type: Option<String>, + pub card_issuing_country: Option<String>, + pub bank_code: Option<String>, + pub nick_name: Option<Secret<String>>, +} + +impl CardDetailsForNetworkTransactionId { + pub fn get_nti_and_card_details_for_mit_flow( + recurring_details: mandates::RecurringDetails, + ) -> Option<(api_models::payments::MandateReferenceId, Self)> { + let network_transaction_id_and_card_details = match recurring_details { + mandates::RecurringDetails::NetworkTransactionIdAndCardDetails( + network_transaction_id_and_card_details, + ) => Some(network_transaction_id_and_card_details), + mandates::RecurringDetails::MandateId(_) + | mandates::RecurringDetails::PaymentMethodId(_) + | mandates::RecurringDetails::ProcessorPaymentToken(_) => None, + }?; + + let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId( + network_transaction_id_and_card_details + .network_transaction_id + .peek() + .to_string(), + ); + + Some(( + mandate_reference_id, + network_transaction_id_and_card_details.clone().into(), + )) + } +} + +impl From<mandates::NetworkTransactionIdAndCardDetails> for CardDetailsForNetworkTransactionId { + fn from(card_details_for_nti: mandates::NetworkTransactionIdAndCardDetails) -> Self { + Self { + card_number: card_details_for_nti.card_number, + card_exp_month: card_details_for_nti.card_exp_month, + card_exp_year: card_details_for_nti.card_exp_year, + card_issuer: card_details_for_nti.card_issuer, + card_network: card_details_for_nti.card_network, + card_type: card_details_for_nti.card_type, + card_issuing_country: card_details_for_nti.card_issuing_country, + bank_code: card_details_for_nti.bank_code, + nick_name: card_details_for_nti.nick_name, + } + } +} + #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)] pub enum CardRedirectData { Knet {}, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 24fbadc0a59..27564569c3b 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -494,6 +494,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::mandates::MandateResponse, api_models::mandates::MandateCardDetails, api_models::mandates::RecurringDetails, + api_models::mandates::NetworkTransactionIdAndCardDetails, api_models::mandates::ProcessorPaymentToken, api_models::ephemeral_key::EphemeralKeyCreateResponse, api_models::payments::CustomerDetails, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index bc44068030b..deca42f17e5 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -386,6 +386,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::ApplePayThirdPartySdkData, api_models::payments::GooglePayRedirectData, api_models::payments::GooglePayThirdPartySdk, + api_models::mandates::NetworkTransactionIdAndCardDetails, api_models::payments::GooglePaySessionResponse, api_models::payments::GpayShippingAddressParameters, api_models::payments::GpayBillingAddressParameters, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index abd99fae18c..5e803b593ee 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -440,7 +440,8 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Aci"), ))? diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 4cc392c57bc..ca13e57e401 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1588,7 +1588,8 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), ))? @@ -2581,19 +2582,30 @@ impl<'a> } payments::MandateReferenceId::NetworkMandateId(network_mandate_id) => { match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Card(ref card) => { - let brand = match card.card_network.clone().and_then(get_adyen_card_network) + domain::PaymentMethodData::CardDetailsForNetworkTransactionId( + ref card_details_for_network_transaction_id, + ) => { + let brand = match card_details_for_network_transaction_id + .card_network + .clone() + .and_then(get_adyen_card_network) { Some(card_network) => card_network, - None => CardBrand::try_from(&card.get_card_issuer()?)?, + None => CardBrand::try_from( + &card_details_for_network_transaction_id.get_card_issuer()?, + )?, }; let card_holder_name = item.router_data.get_optional_billing_full_name(); let adyen_card = AdyenCard { payment_type: PaymentType::Scheme, - number: card.card_number.clone(), - expiry_month: card.card_exp_month.clone(), - expiry_year: card.card_exp_year.clone(), + number: card_details_for_network_transaction_id.card_number.clone(), + expiry_month: card_details_for_network_transaction_id + .card_exp_month + .clone(), + expiry_year: card_details_for_network_transaction_id + .card_exp_year + .clone(), cvc: None, holder_name: card_holder_name, brand: Some(brand), @@ -2616,7 +2628,8 @@ impl<'a> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::Card(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), connector: "Adyen", diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 868a4767c31..e38999d495b 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -206,7 +206,8 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), )) diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index e352d8b79bc..903470ae952 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -344,7 +344,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), ))? @@ -530,7 +531,8 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( "authorizedotnet", @@ -590,7 +592,8 @@ impl | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("authorizedotnet"), ))? diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index ab6367eeb6e..ad75328322d 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -324,7 +324,8 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), ))? @@ -1097,7 +1098,8 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message( "Bank of America", diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs index c6f2be9dbfc..6b21014cdd5 100644 --- a/crates/router/src/connector/billwerk/transformers.rs +++ b/crates/router/src/connector/billwerk/transformers.rs @@ -104,7 +104,8 @@ impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest { | domain::payments::PaymentMethodData::GiftCard(_) | domain::payments::PaymentMethodData::OpenBanking(_) | domain::payments::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("billwerk"), ) diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index b156aafb6ef..39be2517e4b 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -229,7 +229,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method via Token flow through bluesnap".to_string(), ) @@ -396,7 +397,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), )) diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index a48e49a10cc..bc9eb4e3722 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -112,7 +112,8 @@ impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPayme | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("boku"), ))? diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 29f741d8bdc..b7515a964bb 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -310,7 +310,8 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("braintree"), ) @@ -1104,7 +1105,8 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("braintree"), ) @@ -1715,7 +1717,8 @@ fn get_braintree_redirect_form( | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => Err( + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err( errors::ConnectorError::NotImplemented("given payment method".to_owned()), )?, }, diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 2950fdb6bd1..3e951b3ac86 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -135,7 +135,8 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), ) @@ -380,7 +381,8 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), )) diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8a6c3c075ff..4db35abec86 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -12,7 +12,6 @@ use common_utils::{ types::SemanticVersion, }; use error_stack::ResultExt; -use josekit::jwt::decode_header; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -251,7 +250,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))? @@ -1245,6 +1245,89 @@ impl } } +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId, + ), + ) -> Result<Self, Self::Error> { + let email = item + .router_data + .get_billing_email() + .or(item.router_data.request.get_email())?; + let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; + let order_information = OrderInformationWithBill::from((item, Some(bill_to))); + + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + + let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: None, + card_type: card_type.clone(), + }, + })); + + let processing_information = ProcessingInformation::try_from((item, None, card_type))?; + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); + + let consumer_authentication_information = item + .router_data + .request + .authentication_data + .as_ref() + .map(|authn_data| { + let (ucaf_authentication_data, cavv) = + if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) { + (Some(Secret::new(authn_data.cavv.clone())), None) + } else { + (None, Some(authn_data.cavv.clone())) + }; + CybersourceConsumerAuthInformation { + ucaf_collection_indicator: None, + cavv, + ucaf_authentication_data, + xid: Some(authn_data.threeds_server_transaction_id.clone()), + directory_server_transaction_id: authn_data + .ds_trans_id + .clone() + .map(Secret::new), + specification_version: None, + pa_specification_version: Some(authn_data.message_version.clone()), + veres_enrolled: Some("Y".to_string()), + } + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information, + merchant_defined_information, + }) + } +} + impl TryFrom<( &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, @@ -1690,9 +1773,10 @@ impl fn get_samsung_pay_fluid_data_value( samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData, ) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> { - let samsung_pay_header = decode_header(samsung_pay_token_data.data.clone().peek()) - .change_context(errors::ConnectorError::RequestEncodingFailed) - .attach_printable("Failed to decode samsung pay header")?; + let samsung_pay_header = + josekit::jwt::decode_header(samsung_pay_token_data.data.clone().peek()) + .change_context(errors::ConnectorError::RequestEncodingFailed) + .attach_printable("Failed to decode samsung pay header")?; let samsung_pay_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str()); @@ -1871,6 +1955,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> domain::PaymentMethodData::NetworkToken(token_data) => { Self::try_from((item, token_data)) } + domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card) => { + Self::try_from((item, card)) + } domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::PayLater(_) | domain::PaymentMethodData::BankRedirect(_) @@ -1995,7 +2082,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) @@ -2718,7 +2806,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), )) @@ -2832,7 +2921,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ) diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs index afc9288b656..b28504a1d83 100644 --- a/crates/router/src/connector/datatrans/transformers.rs +++ b/crates/router/src/connector/datatrans/transformers.rs @@ -189,7 +189,8 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message("Datatrans"), ))? diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index d9407b41011..79b90d685ee 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -135,7 +135,8 @@ impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePay | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Forte"), ))? diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index 4982aaf4d88..c0360a94a51 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -248,7 +248,8 @@ impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Gocardless"), ) @@ -420,7 +421,8 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), )) diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 9f3cb9fe6e8..de92168036c 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -207,7 +207,8 @@ impl | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("iatapay"), ))? diff --git a/crates/router/src/connector/itaubank/transformers.rs b/crates/router/src/connector/itaubank/transformers.rs index 0cd070c2053..41c41408381 100644 --- a/crates/router/src/connector/itaubank/transformers.rs +++ b/crates/router/src/connector/itaubank/transformers.rs @@ -120,7 +120,8 @@ impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for Itaub | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method through itaubank".to_string(), ) diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 2c3d3651284..0c362d26edf 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -654,7 +654,8 @@ impl | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(report!(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message( req.connector.as_str(), diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs index 92b6b45785d..03c63d66795 100644 --- a/crates/router/src/connector/mifinity/transformers.rs +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -197,7 +197,8 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Mifinity"), ) diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index e0146bf2eda..9db1cb3701a 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -610,7 +610,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? @@ -793,7 +794,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))? diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 5bf72133384..6cf35f5d87d 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -628,9 +628,12 @@ fn get_payment_details_and_product( | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("nexinets"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nexinets"), + ))? + } } } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 57b04cdca17..af2a9fe56bb 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -587,7 +587,8 @@ impl | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nmi"), ) diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 99e04018632..5c3de332b70 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -355,7 +355,8 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( conn_utils::get_unimplemented_payment_method_error_message("Noon"), )) diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index d9728174f84..d1d7122f49e 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -999,7 +999,8 @@ where | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) @@ -1203,6 +1204,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)> | Some(domain::PaymentMethodData::OpenBanking(_)) | Some(domain::PaymentMethodData::CardToken(..)) | Some(domain::PaymentMethodData::NetworkToken(..)) + | Some(domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), )), diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index dcb4e201e8b..16a76301ede 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -58,7 +58,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Opayo"), ) diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 8c2ad2ef979..685bf3c0fbb 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -262,7 +262,8 @@ fn get_payment_method_data( | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Payeezy"), ))? diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index b4aa66a1c49..4eac0a6f94d 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -433,7 +433,8 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | PaymentMethodData::Voucher(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => { + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } } @@ -679,9 +680,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("payme"), - ))?, + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("payme"), + ))? + } } } } @@ -744,6 +748,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { | Some(PaymentMethodData::OpenBanking(_)) | Some(PaymentMethodData::CardToken(_)) | Some(PaymentMethodData::NetworkToken(_)) + | Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_)) | None => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } @@ -784,7 +789,8 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest { | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) => { + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 41fd533309e..b51357a42af 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -548,7 +548,8 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Paypal"), ) diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs index 919fe25bdd8..32d651787b6 100644 --- a/crates/router/src/connector/placetopay/transformers.rs +++ b/crates/router/src/connector/placetopay/transformers.rs @@ -143,7 +143,8 @@ impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Placetopay"), ) diff --git a/crates/router/src/connector/razorpay/transformers.rs b/crates/router/src/connector/razorpay/transformers.rs index 621c0969aff..fde72cac100 100644 --- a/crates/router/src/connector/razorpay/transformers.rs +++ b/crates/router/src/connector/razorpay/transformers.rs @@ -400,7 +400,8 @@ impl | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } }?; diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index e206fe0e0ae..2210ab0a361 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -249,7 +249,8 @@ where | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Shift4"), ) @@ -475,6 +476,7 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme | Some(domain::PaymentMethodData::OpenBanking(_)) | Some(domain::PaymentMethodData::CardToken(_)) | Some(domain::PaymentMethodData::NetworkToken(_)) + | Some(domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Shift4"), ) diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 68bab815d65..63720696ef4 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1347,7 +1347,8 @@ fn create_stripe_payment_method( | domain::PaymentMethodData::MandatePayment | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -1724,20 +1725,28 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent }); let payment_data = match item.request.payment_method_data { - domain::payments::PaymentMethodData::Card(ref card) => { - StripePaymentMethodData::Card(StripeCardData { - payment_method_data_type: StripePaymentMethodType::Card, - payment_method_data_card_number: card.card_number.clone(), - payment_method_data_card_exp_month: card.card_exp_month.clone(), - payment_method_data_card_exp_year: card.card_exp_year.clone(), - payment_method_data_card_cvc: None, - payment_method_auth_type: None, - payment_method_data_card_preferred_network: card + domain::payments::PaymentMethodData::CardDetailsForNetworkTransactionId( + ref card_details_for_network_transaction_id, + ) => StripePaymentMethodData::Card(StripeCardData { + payment_method_data_type: StripePaymentMethodType::Card, + payment_method_data_card_number: + card_details_for_network_transaction_id.card_number.clone(), + payment_method_data_card_exp_month: + card_details_for_network_transaction_id + .card_exp_month + .clone(), + payment_method_data_card_exp_year: + card_details_for_network_transaction_id + .card_exp_year + .clone(), + payment_method_data_card_cvc: None, + payment_method_auth_type: None, + payment_method_data_card_preferred_network: + card_details_for_network_transaction_id .card_network .clone() .and_then(get_stripe_card_network), - }) - } + }), domain::payments::PaymentMethodData::CardRedirect(_) | domain::payments::PaymentMethodData::Wallet(_) | domain::payments::PaymentMethodData::PayLater(_) @@ -1753,7 +1762,8 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent | domain::payments::PaymentMethodData::GiftCard(_) | domain::payments::PaymentMethodData::OpenBanking(_) | domain::payments::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::Card(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), connector: "Stripe", @@ -3369,6 +3379,7 @@ impl | Some(domain::PaymentMethodData::OpenBanking(..)) | Some(domain::PaymentMethodData::CardToken(..)) | Some(domain::PaymentMethodData::NetworkToken(..)) + | Some(domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) | None => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -3823,7 +3834,8 @@ impl | domain::PaymentMethodData::Voucher(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ))? diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index d05db4d28ab..fbff19fd0ad 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -435,7 +435,8 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), ) diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 31afb0adf11..ea19acb76da 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1439,6 +1439,81 @@ impl CardData for payouts::CardPayout { } } +impl CardData + for hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId +{ + fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { + let binding = self.card_exp_year.clone(); + let year = binding.peek(); + Ok(Secret::new( + year.get(year.len() - 2..) + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(), + )) + } + fn get_card_issuer(&self) -> Result<CardIssuer, Error> { + get_card_issuer(self.card_number.peek()) + } + fn get_card_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?; + Ok(Secret::new(format!( + "{}{}{}", + self.card_exp_month.peek(), + delimiter, + year.peek() + ))) + } + fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + year.peek(), + delimiter, + self.card_exp_month.peek() + )) + } + fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + self.card_exp_month.peek(), + delimiter, + year.peek() + )) + } + fn get_expiry_year_4_digit(&self) -> Secret<String> { + let mut year = self.card_exp_year.peek().clone(); + if year.len() == 2 { + year = format!("20{}", year); + } + Secret::new(year) + } + fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?.expose(); + let month = self.card_exp_month.clone().expose(); + Ok(Secret::new(format!("{year}{month}"))) + } + fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { + self.card_exp_month + .peek() + .clone() + .parse::<i8>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } + fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { + self.card_exp_year + .peek() + .clone() + .parse::<i32>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } +} + impl CardData for domain::Card { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); @@ -2725,6 +2800,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { match pm_data { domain::payments::PaymentMethodData::Card(_) => Self::Card, domain::payments::PaymentMethodData::NetworkToken(_) => Self::NetworkToken, + domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::Card, domain::payments::PaymentMethodData::CardRedirect(card_redirect_data) => { match card_redirect_data { domain::CardRedirectData::Knet {} => Self::Knet, diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index ee34c26d670..c57306efe31 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -210,7 +210,8 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest { | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ))? @@ -1291,7 +1292,8 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Wellsfargo"), ) diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 467a1cba902..dca6f82adc1 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -111,7 +111,8 @@ fn fetch_payment_instrument( | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldpay"), ) diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 2b2e7e889e2..799753fd52c 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -697,7 +697,8 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment | domain::PaymentMethodData::Upi(_) | domain::PaymentMethodData::OpenBanking(_) | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), ))? diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs index b3e7bfb3bfd..c8758f5322c 100644 --- a/crates/router/src/connector/zsl/transformers.rs +++ b/crates/router/src/connector/zsl/transformers.rs @@ -183,6 +183,7 @@ impl TryFrom<&ZslRouterData<&types::PaymentsAuthorizeRouterData>> for ZslPayment | domain::PaymentMethodData::GiftCard(_) | domain::PaymentMethodData::CardToken(_) | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) | domain::PaymentMethodData::OpenBanking(_) => { Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message( diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d6877fb88dc..c581b104739 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -78,7 +78,9 @@ use crate::{ core::{ errors::{self, CustomResult, RouterResponse, RouterResult}, payment_methods::{cards, network_tokenization}, - payouts, routing as core_routing, utils, + payouts, + routing::{self as core_routing}, + utils::{self as core_utils}, }, db::StorageInterface, logger, @@ -92,8 +94,8 @@ use crate::{ transformers::{ForeignInto, ForeignTryInto}, }, utils::{ - add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode, OptionExt, - ValueExt, + self, add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode, + OptionExt, ValueExt, }, workflows::payment_sync, }; @@ -164,7 +166,7 @@ where &header_payload, ) .await?; - utils::validate_profile_id_from_auth_layer( + core_utils::validate_profile_id_from_auth_layer( profile_id_from_auth_layer, &payment_data.get_payment_intent().clone(), )?; @@ -649,7 +651,7 @@ where ) .await?; - crate::utils::trigger_payments_webhook( + utils::trigger_payments_webhook( merchant_account, business_profile, &key_store, @@ -671,6 +673,206 @@ where )) } +// This function is intended for use when the feature being implemented is not aligned with the +// core payment operations. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] +#[instrument(skip_all, fields(payment_id, merchant_id))] +pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( + state: &SessionState, + req_state: ReqState, + merchant_account: domain::MerchantAccount, + profile_id_from_auth_layer: Option<id_type::ProfileId>, + key_store: domain::MerchantKeyStore, + operation: Op, + req: Req, + call_connector_action: CallConnectorAction, + auth_flow: services::AuthFlow, + + header_payload: HeaderPayload, +) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> +where + F: Send + Clone + Sync, + Req: Authenticate + Clone, + Op: Operation<F, Req, Data = D> + Send + Sync, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + + // To create connector flow specific interface data + D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, + RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, + + // To construct connector flow specific api + dyn api::Connector: + services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, + + // To perform router related operation for PaymentResponse + PaymentResponse: Operation<F, FData, Data = D>, + FData: Send + Sync + Clone, +{ + let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation); + + tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr()); + let (operation, validate_result) = operation + .to_validate_request()? + .validate_request(&req, &merchant_account)?; + + tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); + + let operations::GetTrackerResponse { + operation, + customer_details: _, + mut payment_data, + business_profile, + mandate_type: _, + } = operation + .to_get_tracker()? + .get_trackers( + state, + &validate_result.payment_id, + &req, + &merchant_account, + &key_store, + auth_flow, + &header_payload, + ) + .await?; + + core_utils::validate_profile_id_from_auth_layer( + profile_id_from_auth_layer, + &payment_data.get_payment_intent().clone(), + )?; + + common_utils::fp_utils::when(!should_call_connector(&operation, &payment_data), || { + Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration).attach_printable(format!( + "Nti and card details based mit flow is not support for this {operation:?} payment operation" + )) + })?; + + let connector_choice = operation + .to_domain()? + .get_connector( + &merchant_account, + &state.clone(), + &req, + payment_data.get_payment_intent(), + &key_store, + ) + .await?; + + let connector = set_eligible_connector_for_nti_in_payment_data( + state, + &business_profile, + &key_store, + &mut payment_data, + connector_choice, + ) + .await?; + + let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data); + + let locale = header_payload.locale.clone(); + + let schedule_time = if should_add_task_to_process_tracker { + payment_sync::get_sync_process_schedule_time( + &*state.store, + connector.connector.id(), + merchant_account.get_id(), + 0, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting process schedule time")? + } else { + None + }; + + let (router_data, mca) = proxy_for_call_connector_service( + state, + req_state.clone(), + &merchant_account, + &key_store, + connector.clone(), + &operation, + &mut payment_data, + &None, + call_connector_action.clone(), + &validate_result, + schedule_time, + header_payload.clone(), + &business_profile, + ) + .await?; + + let op_ref = &operation; + let should_trigger_post_processing_flows = is_operation_confirm(&operation); + + let operation = Box::new(PaymentResponse); + + let connector_http_status_code = router_data.connector_http_status_code; + let external_latency = router_data.external_latency; + + add_connector_http_status_code_metrics(connector_http_status_code); + + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] + let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()]) + .map_err(|e| logger::error!(routable_connector_error=?e)) + .unwrap_or_default(); + + let mut payment_data = operation + .to_post_update_tracker()? + .update_tracker( + state, + &validate_result.payment_id, + payment_data, + router_data, + &key_store, + merchant_account.storage_scheme, + &locale, + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] + routable_connectors, + #[cfg(all(feature = "dynamic_routing", feature = "v1"))] + &business_profile, + ) + .await?; + + if should_trigger_post_processing_flows { + complete_postprocessing_steps_if_required( + state, + &merchant_account, + &key_store, + &None, + &mca, + &connector, + &mut payment_data, + op_ref, + Some(header_payload.clone()), + ) + .await?; + } + + let cloned_payment_data = payment_data.clone(); + + utils::trigger_payments_webhook( + merchant_account, + business_profile, + &key_store, + cloned_payment_data, + None, + state, + operation, + ) + .await + .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) + .ok(); + + Ok(( + payment_data, + req, + None, + connector_http_status_code, + external_latency, + )) +} + #[instrument(skip_all)] #[cfg(feature = "v1")] pub async fn call_decision_manager<F, D>( @@ -983,6 +1185,66 @@ where ) } +#[cfg(feature = "v1")] +#[allow(clippy::too_many_arguments)] +pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( + state: SessionState, + req_state: ReqState, + merchant_account: domain::MerchantAccount, + profile_id: Option<id_type::ProfileId>, + key_store: domain::MerchantKeyStore, + operation: Op, + req: Req, + auth_flow: services::AuthFlow, + call_connector_action: CallConnectorAction, + header_payload: HeaderPayload, +) -> RouterResponse<Res> +where + F: Send + Clone + Sync, + FData: Send + Sync + Clone, + Op: Operation<F, Req, Data = D> + Send + Sync + Clone, + Req: Debug + Authenticate + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + Res: transformers::ToResponse<F, D, Op>, + // To create connector flow specific interface data + D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>, + RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>, + + // To construct connector flow specific api + dyn api::Connector: + services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>, + + // To perform router related operation for PaymentResponse + PaymentResponse: Operation<F, FData, Data = D>, +{ + let (payment_data, _req, customer, connector_http_status_code, external_latency) = + proxy_for_payments_operation_core::<_, _, _, _, _>( + &state, + req_state, + merchant_account, + profile_id, + key_store, + operation.clone(), + req, + call_connector_action, + auth_flow, + header_payload.clone(), + ) + .await?; + + Res::generate_response( + payment_data, + customer, + auth_flow, + &state.base_url, + operation, + &state.conf.connector_request_reference_id_config, + connector_http_status_code, + external_latency, + header_payload.x_hs_latency, + ) +} + fn is_start_pay<Op: Debug>(operation: &Op) -> bool { format!("{operation:?}").eq("PaymentStart") } @@ -1403,7 +1665,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { ) .await?; let is_pull_mechanism_enabled = - crate::utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( + utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( authentication_merchant_connector_account .get_metadata() .map(|metadata| metadata.expose()), @@ -1489,8 +1751,8 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { }?; // When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction { - let req_poll_id = utils::get_external_authentication_request_poll_id(&payment_id); - let poll_id = utils::get_poll_id(&merchant_id, req_poll_id.clone()); + let req_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_id); + let poll_id = core_utils::get_poll_id(&merchant_id, req_poll_id.clone()); let redis_conn = state .store .get_redis_conn() @@ -1557,7 +1819,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { connector.clone(), )?; // html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url - let html = utils::get_html_redirect_response_for_external_authentication( + let html = core_utils::get_html_redirect_response_for_external_authentication( redirect_response.return_url_with_query_params, payments_response, payment_id, @@ -1829,6 +2091,179 @@ where Ok((router_data, merchant_connector_account)) } +// This function does not perform the tokenization action, as the payment method is not saved in this flow. +#[allow(clippy::too_many_arguments)] +#[instrument(skip_all)] +pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>( + state: &SessionState, + req_state: ReqState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + connector: api::ConnectorData, + operation: &BoxedOperation<'_, F, ApiRequest, D>, + payment_data: &mut D, + customer: &Option<domain::Customer>, + call_connector_action: CallConnectorAction, + validate_result: &operations::ValidateResult, + schedule_time: Option<time::PrimitiveDateTime>, + header_payload: HeaderPayload, + + business_profile: &domain::Profile, +) -> RouterResult<( + RouterData<F, RouterDReq, router_types::PaymentsResponseData>, + helpers::MerchantConnectorAccountType, +)> +where + F: Send + Clone + Sync, + RouterDReq: Send + Sync, + + // To create connector flow specific interface data + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>, + RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send, + // To construct connector flow specific api + dyn api::Connector: + services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>, +{ + let stime_connector = Instant::now(); + + let merchant_connector_account = construct_profile_id_and_get_mca( + state, + merchant_account, + payment_data, + &connector.connector_name.to_string(), + connector.merchant_connector_id.as_ref(), + key_store, + false, + ) + .await?; + + if payment_data + .get_payment_attempt() + .merchant_connector_id + .is_none() + { + payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id()); + } + + let merchant_recipient_data = None; + + let mut router_data = payment_data + .construct_router_data( + state, + connector.connector.id(), + merchant_account, + key_store, + customer, + &merchant_connector_account, + merchant_recipient_data, + None, + ) + .await?; + + let add_access_token_result = router_data + .add_access_token( + state, + &connector, + merchant_account, + payment_data.get_creds_identifier(), + ) + .await?; + + router_data = router_data.add_session_token(state, &connector).await?; + + let mut should_continue_further = access_token::update_router_data_with_access_token_result( + &add_access_token_result, + &mut router_data, + &call_connector_action, + ); + + (router_data, should_continue_further) = complete_preprocessing_steps_if_required( + state, + &connector, + payment_data, + router_data, + operation, + should_continue_further, + ) + .await?; + + if let Ok(router_types::PaymentsResponseData::PreProcessingResponse { + session_token: Some(session_token), + .. + }) = router_data.response.to_owned() + { + payment_data.push_sessions_token(session_token); + }; + + let (connector_request, should_continue_further) = if should_continue_further { + // Check if the actual flow specific request can be built with available data + router_data + .build_flow_specific_connector_request(state, &connector, call_connector_action.clone()) + .await? + } else { + (None, false) + }; + + if should_add_task_to_process_tracker(payment_data) { + operation + .to_domain()? + .add_task_to_process_tracker( + state, + payment_data.get_payment_attempt(), + validate_result.requeue, + schedule_time, + ) + .await + .map_err(|error| logger::error!(process_tracker_error=?error)) + .ok(); + } + + let updated_customer = None; + let frm_suggestion = None; + + (_, *payment_data) = operation + .to_update_tracker()? + .update_trackers( + state, + req_state, + payment_data.clone(), + customer.clone(), + merchant_account.storage_scheme, + updated_customer, + key_store, + frm_suggestion, + header_payload.clone(), + ) + .await?; + + let router_data = if should_continue_further { + // The status of payment_attempt and intent will be updated in the previous step + // update this in router_data. + // This is added because few connector integrations do not update the status, + // and rely on previous status set in router_data + router_data.status = payment_data.get_payment_attempt().status; + router_data + .decide_flows( + state, + &connector, + call_connector_action, + connector_request, + business_profile, + header_payload.clone(), + ) + .await + } else { + Ok(router_data) + }?; + + let etime_connector = Instant::now(); + let duration_connector = etime_connector.saturating_duration_since(stime_connector); + tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis())); + + Ok((router_data, merchant_connector_account)) +} + pub async fn add_decrypted_payment_method_token<F, D>( tokenization_action: TokenizationAction, payment_data: &D, @@ -2194,7 +2629,7 @@ where #[cfg(feature = "v1")] let label = { - let connector_label = utils::get_connector_label( + let connector_label = core_utils::get_connector_label( payment_data.get_payment_intent().business_country, payment_data.get_payment_intent().business_label.as_ref(), payment_data @@ -3655,6 +4090,120 @@ where Ok(connector) } +async fn get_eligible_connector_for_nti<T: core_routing::GetRoutableConnectorsForChoice, F, D>( + state: &SessionState, + key_store: &domain::MerchantKeyStore, + payment_data: &D, + connector_choice: T, + + business_profile: &domain::Profile, +) -> RouterResult<( + api_models::payments::MandateReferenceId, + hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId, + api::ConnectorData, +)> +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + // Since this flow will only be used in the MIT flow, recurring details are mandatory. + let recurring_payment_details = payment_data + .get_recurring_details() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable("Failed to fetch recurring details for mit")?; + + let (mandate_reference_id, card_details_for_network_transaction_id)= hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(recurring_payment_details.clone()).get_required_value("network transaction id and card details").attach_printable("Failed to fetch network transaction id and card details for mit")?; + + let network_transaction_id_supported_connectors = &state + .conf + .network_transaction_id_supported_connectors + .connector_list + .iter() + .map(|value| value.to_string()) + .collect::<HashSet<_>>(); + + let eligible_connector_data_list = connector_choice + .get_routable_connectors(&*state.store, business_profile) + .await? + .filter_network_transaction_id_flow_supported_connectors( + network_transaction_id_supported_connectors.to_owned(), + ) + .construct_dsl_and_perform_eligibility_analysis( + state, + key_store, + payment_data, + business_profile.get_id(), + ) + .await + .attach_printable("Failed to fetch eligible connector data")?; + + let eligible_connector_data = eligible_connector_data_list + .first() + .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) + .attach_printable( + "No eligible connector found for the network transaction id based mit flow", + )?; + Ok(( + mandate_reference_id, + card_details_for_network_transaction_id, + eligible_connector_data.clone(), + )) +} + +pub async fn set_eligible_connector_for_nti_in_payment_data<F, D>( + state: &SessionState, + business_profile: &domain::Profile, + key_store: &domain::MerchantKeyStore, + payment_data: &mut D, + connector_choice: api::ConnectorChoice, +) -> RouterResult<api::ConnectorData> +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + let (mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data) = + match connector_choice { + api::ConnectorChoice::StraightThrough(straight_through) => { + get_eligible_connector_for_nti( + state, + key_store, + payment_data, + core_routing::StraightThroughAlgorithmTypeSingle(straight_through), + business_profile, + ) + .await? + } + api::ConnectorChoice::Decide => { + get_eligible_connector_for_nti( + state, + key_store, + payment_data, + core_routing::DecideConnector, + business_profile, + ) + .await? + } + api::ConnectorChoice::SessionMultiple(_) => { + Err(errors::ApiErrorResponse::InternalServerError).attach_printable( + "Invalid routing rule configured for nti and card details based mit flow", + )? + } + }; + + // Set `NetworkMandateId` as the MandateId + payment_data.set_mandate_id(payments_api::MandateIds { + mandate_id: None, + mandate_reference_id: Some(mandate_reference_id), + }); + + // Set the card details received in the recurring details within the payment method data. + payment_data.set_payment_method_data(Some( + hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(card_details_for_network_transaction_id), + )); + + Ok(eligible_connector_data) +} + #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn connector_selection<F, D>( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index b159971fdf3..323a5aed473 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -434,6 +434,9 @@ pub async fn get_token_pm_type_mandate_details( match &request.recurring_details { Some(recurring_details) => { match recurring_details { + RecurringDetails::NetworkTransactionIdAndCardDetails(_) => { + (None, request.payment_method, None, None, None, None, None) + } RecurringDetails::ProcessorPaymentToken(processor_payment_token) => { if let Some(mca_id) = &processor_payment_token.merchant_connector_id { let db = &*state.store; @@ -1234,7 +1237,8 @@ fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult .get_required_value("recurring_details")?; match recurring_details { - RecurringDetails::ProcessorPaymentToken(_) => Ok(()), + RecurringDetails::ProcessorPaymentToken(_) + | RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()), _ => { req.customer_id.check_value_present("customer_id")?; @@ -1828,16 +1832,60 @@ pub async fn retrieve_card_with_permanent_token( })?; if !business_profile.is_network_tokenization_enabled { - fetch_card_details_from_locker( - state, - customer_id, - &payment_intent.merchant_id, - locker_id, - card_token_data, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to fetch card information from the permanent locker") + let is_network_transaction_id_flow = mandate_id + .map(|mandate_ids| mandate_ids.is_network_transaction_id_flow()) + .unwrap_or(false); + + if is_network_transaction_id_flow { + let card_details_from_locker = cards::get_card_from_locker( + state, + customer_id, + &payment_intent.merchant_id, + locker_id, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch card details from locker")?; + + let card_network = card_details_from_locker + .card_brand + .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) + .transpose() + .map_err(|e| { + logger::error!("Failed to parse card network {e:?}"); + }) + .ok() + .flatten(); + + let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { + card_number: card_details_from_locker.card_number, + card_exp_month: card_details_from_locker.card_exp_month, + card_exp_year: card_details_from_locker.card_exp_year, + card_issuer: None, + card_network, + card_type: None, + card_issuing_country: None, + bank_code: None, + nick_name: card_details_from_locker.nick_name.map(masking::Secret::new), + }; + + Ok( + domain::PaymentMethodData::CardDetailsForNetworkTransactionId( + card_details_for_network_transaction_id, + ), + ) + } else { + fetch_card_details_from_locker( + state, + customer_id, + &payment_intent.merchant_id, + locker_id, + card_token_data, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch card information from the permanent locker") + } } else { match (payment_method_info, mandate_id) { (None, _) => Err(errors::ApiErrorResponse::InternalServerError) @@ -1934,17 +1982,42 @@ pub async fn retrieve_card_with_permanent_token( } Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { - fetch_card_details_from_locker( + let card_details_from_locker = cards::get_card_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, - card_token_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "failed to fetch card information from the permanent locker", + .attach_printable("failed to fetch card details from locker")?; + + let card_network = card_details_from_locker + .card_brand + .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) + .transpose() + .map_err(|e| { + logger::error!("Failed to parse card network {e:?}"); + }) + .ok() + .flatten(); + + let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { + card_number: card_details_from_locker.card_number, + card_exp_month: card_details_from_locker.card_exp_month, + card_exp_year: card_details_from_locker.card_exp_year, + card_issuer: None, + card_network, + card_type: None, + card_issuing_country: None, + bank_code: None, + nick_name: card_details_from_locker.nick_name.map(masking::Secret::new), + }; + + Ok( + domain::PaymentMethodData::CardDetailsForNetworkTransactionId( + card_details_for_network_transaction_id, + ), ) } @@ -4420,6 +4493,110 @@ pub async fn get_additional_payment_data( details: Some(open_banking.to_owned().into()), }, )), + domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => { + let card_isin = Some(card_data.card_number.get_card_isin()); + let enable_extended_bin =db + .find_config_by_key_unwrap_or( + format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(), + Some("false".to_string())) + .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok(); + + let card_extended_bin = match enable_extended_bin { + Some(config) if config.config == "true" => { + Some(card_data.card_number.get_extended_card_bin()) + } + _ => None, + }; + + let card_network = match card_data + .card_number + .is_cobadged_card() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Card cobadge check failed due to an invalid card network regex", + )? { + true => card_data.card_network.clone(), + false => None, + }; + + let last4 = Some(card_data.card_number.get_last4()); + if card_data.card_issuer.is_some() + && card_network.is_some() + && card_data.card_type.is_some() + && card_data.card_issuing_country.is_some() + && card_data.bank_code.is_some() + { + Ok(Some(api_models::payments::AdditionalPaymentData::Card( + Box::new(api_models::payments::AdditionalCardInfo { + card_issuer: card_data.card_issuer.to_owned(), + card_network, + card_type: card_data.card_type.to_owned(), + card_issuing_country: card_data.card_issuing_country.to_owned(), + bank_code: card_data.bank_code.to_owned(), + card_exp_month: Some(card_data.card_exp_month.clone()), + card_exp_year: Some(card_data.card_exp_year.clone()), + card_holder_name: card_data.nick_name.clone(), //todo! + last4: last4.clone(), + card_isin: card_isin.clone(), + card_extended_bin: card_extended_bin.clone(), + // These are filled after calling the processor / connector + payment_checks: None, + authentication_data: None, + }), + ))) + } else { + let card_info = card_isin + .clone() + .async_and_then(|card_isin| async move { + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::warn!(card_info_error=?error)) + .ok() + }) + .await + .flatten() + .map(|card_info| { + api_models::payments::AdditionalPaymentData::Card(Box::new( + api_models::payments::AdditionalCardInfo { + card_issuer: card_info.card_issuer, + card_network, + bank_code: card_info.bank_code, + card_type: card_info.card_type, + card_issuing_country: card_info.card_issuing_country, + last4: last4.clone(), + card_isin: card_isin.clone(), + card_extended_bin: card_extended_bin.clone(), + card_exp_month: Some(card_data.card_exp_month.clone()), + card_exp_year: Some(card_data.card_exp_year.clone()), + card_holder_name: card_data.nick_name.clone(), //todo! + // These are filled after calling the processor / connector + payment_checks: None, + authentication_data: None, + }, + )) + }); + Ok(Some(card_info.unwrap_or_else(|| { + api_models::payments::AdditionalPaymentData::Card(Box::new( + api_models::payments::AdditionalCardInfo { + card_issuer: None, + card_network: None, + bank_code: None, + card_type: None, + card_issuing_country: None, + last4, + card_isin, + card_extended_bin, + card_exp_month: Some(card_data.card_exp_month.clone()), + card_exp_year: Some(card_data.card_exp_year.clone()), + card_holder_name: card_data.nick_name.clone(), //todo! + // These are filled after calling the processor / connector + payment_checks: None, + authentication_data: None, + }, + )) + }))) + } + } domain::PaymentMethodData::NetworkToken(_) => Ok(None), } } @@ -5133,8 +5310,9 @@ pub fn get_key_params_for_surcharge_details( ob_data.get_payment_method_type(), None, )), - domain::PaymentMethodData::CardToken(_) => None, - domain::PaymentMethodData::NetworkToken(_) => None, + domain::PaymentMethodData::CardToken(_) + | domain::PaymentMethodData::NetworkToken(_) + | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => None, } } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index fd5c544b285..ac400eaf57f 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1097,6 +1097,9 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_) => { payment_data.payment_attempt.payment_method_data.clone() } + hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { + payment_data.payment_attempt.payment_method_data.clone() + } }, None => None, }; diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index c3a7900b434..af540c6dcf6 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -400,6 +400,20 @@ pub fn perform_straight_through_routing( }) } +pub fn perform_routing_for_single_straight_through_algorithm( + algorithm: &routing_types::StraightThroughAlgorithm, +) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { + Ok(match algorithm { + routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()], + + routing_types::StraightThroughAlgorithm::Priority(_) + | routing_types::StraightThroughAlgorithm::VolumeSplit(_) => { + Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) + .attach_printable("Unsupported algorithm received as a result of static routing")? + } + }) +} + fn execute_dsl_and_get_connector_v1( backend_input: dsl_inputs::BackendInput, interpreter: &backend::VirInterpreterBackend<ConnectorSelection>, @@ -646,7 +660,7 @@ pub async fn refresh_cgraph_cache<'a>( } #[allow(clippy::too_many_arguments)] -async fn perform_cgraph_filtering( +pub async fn perform_cgraph_filtering( state: &SessionState, key_store: &domain::MerchantKeyStore, chosen: Vec<routing_types::RoutableConnectorChoice>, diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index b7b1c13ea80..926b30081bf 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -1,10 +1,12 @@ pub mod helpers; pub mod transformers; +use std::collections::HashSet; use api_models::{ enums, mandates as mandates_api, routing, routing::{self as routing_types, RoutingRetrieveQuery}, }; +use async_trait::async_trait; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; use hyperswitch_domain_models::{mandates, payment_address}; @@ -17,22 +19,27 @@ use storage_impl::redis::cache; #[cfg(feature = "payouts")] use super::payouts; +use super::{ + errors::RouterResult, + payments::{ + routing::{self as payments_routing}, + OperationSessionGetters, + }, +}; #[cfg(feature = "v1")] use crate::utils::ValueExt; #[cfg(feature = "v2")] -use crate::{ - core::{admin, errors::RouterResult}, - db::StorageInterface, -}; +use crate::{core::admin, utils::ValueExt}; use crate::{ core::{ - errors::{self, RouterResponse, StorageErrorExt}, + errors::{self, CustomResult, RouterResponse, StorageErrorExt}, metrics, utils as core_utils, }, + db::StorageInterface, routes::SessionState, services::api as service_api, types::{ - domain, + api, domain, storage::{self, enums as storage_enums}, transformers::{ForeignInto, ForeignTryFrom}, }, @@ -1383,3 +1390,141 @@ pub async fn success_based_routing_update_configs( ); Ok(service_api::ApplicationResponse::Json(new_record)) } + +#[async_trait] +pub trait GetRoutableConnectorsForChoice { + async fn get_routable_connectors( + &self, + db: &dyn StorageInterface, + business_profile: &domain::Profile, + ) -> RouterResult<RoutableConnectors>; +} + +pub struct StraightThroughAlgorithmTypeSingle(pub serde_json::Value); + +#[async_trait] +impl GetRoutableConnectorsForChoice for StraightThroughAlgorithmTypeSingle { + async fn get_routable_connectors( + &self, + _db: &dyn StorageInterface, + _business_profile: &domain::Profile, + ) -> RouterResult<RoutableConnectors> { + let straight_through_routing_algorithm = self + .0 + .clone() + .parse_value::<api::routing::StraightThroughAlgorithm>("RoutingAlgorithm") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse the straight through routing algorithm")?; + let routable_connector = match straight_through_routing_algorithm { + api::routing::StraightThroughAlgorithm::Single(connector) => { + vec![*connector] + } + + api::routing::StraightThroughAlgorithm::Priority(_) + | api::routing::StraightThroughAlgorithm::VolumeSplit(_) => { + Err(errors::RoutingError::DslIncorrectSelectionAlgorithm) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Unsupported algorithm received as a result of static routing", + )? + } + }; + Ok(RoutableConnectors(routable_connector)) + } +} + +pub struct DecideConnector; + +#[async_trait] +impl GetRoutableConnectorsForChoice for DecideConnector { + async fn get_routable_connectors( + &self, + db: &dyn StorageInterface, + business_profile: &domain::Profile, + ) -> RouterResult<RoutableConnectors> { + let fallback_config = helpers::get_merchant_default_config( + db, + business_profile.get_id().get_string_repr(), + &common_enums::TransactionType::Payment, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + Ok(RoutableConnectors(fallback_config)) + } +} + +pub struct RoutableConnectors(Vec<routing_types::RoutableConnectorChoice>); + +impl RoutableConnectors { + pub fn filter_network_transaction_id_flow_supported_connectors( + self, + nit_connectors: HashSet<String>, + ) -> Self { + let connectors = self + .0 + .into_iter() + .filter(|routable_connector_choice| { + nit_connectors.contains(&routable_connector_choice.connector.to_string()) + }) + .collect(); + Self(connectors) + } + + pub async fn construct_dsl_and_perform_eligibility_analysis<F, D>( + self, + state: &SessionState, + key_store: &domain::MerchantKeyStore, + payment_data: &D, + + profile_id: &common_utils::id_type::ProfileId, + ) -> RouterResult<Vec<api::ConnectorData>> + where + F: Send + Clone, + D: OperationSessionGetters<F>, + { + let payments_dsl_input = PaymentsDslInput::new( + payment_data.get_setup_mandate(), + payment_data.get_payment_attempt(), + payment_data.get_payment_intent(), + payment_data.get_payment_method_data(), + payment_data.get_address(), + payment_data.get_recurring_details(), + payment_data.get_currency(), + ); + + let routable_connector_choice = self.0.clone(); + + let backend_input = payments_routing::make_dsl_input(&payments_dsl_input) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to construct dsl input")?; + + let connectors = payments_routing::perform_cgraph_filtering( + state, + key_store, + routable_connector_choice, + backend_input, + None, + profile_id, + &common_enums::TransactionType::Payment, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Eligibility analysis failed for routable connectors")?; + + let connector_data = connectors + .into_iter() + .map(|conn| { + api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &conn.connector.to_string(), + api::GetToken::Connector, + conn.merchant_connector_id.clone(), + ) + }) + .collect::<CustomResult<Vec<_>, _>>() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid connector name received")?; + + Ok(connector_data) + } +} diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 5e0c19e3da9..3972adeb116 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1258,55 +1258,87 @@ where // the operation are flow agnostic, and the flow is only required in the post_update_tracker // Thus the flow can be generated just before calling the connector instead of explicitly passing it here. - let eligible_connectors = req.connector.clone(); - match req.payment_type.unwrap_or_default() { - api_models::enums::PaymentType::Normal - | api_models::enums::PaymentType::RecurringMandate - | api_models::enums::PaymentType::NewMandate => { - payments::payments_core::< - api_types::Authorize, - payment_types::PaymentsResponse, - _, - _, - _, - payments::PaymentData<api_types::Authorize>, - >( - state, - req_state, - merchant_account, - profile_id, - key_store, - operation, - req, - auth_flow, - payments::CallConnectorAction::Trigger, - eligible_connectors, - header_payload, - ) - .await - } - api_models::enums::PaymentType::SetupMandate => { - payments::payments_core::< - api_types::SetupMandate, - payment_types::PaymentsResponse, - _, - _, - _, - payments::PaymentData<api_types::SetupMandate>, - >( - state, - req_state, - merchant_account, - profile_id, - key_store, - operation, - req, - auth_flow, - payments::CallConnectorAction::Trigger, - eligible_connectors, - header_payload, - ) - .await + let is_recurring_details_type_nti_and_card_details = req + .recurring_details + .clone() + .map(|recurring_details| { + recurring_details.is_network_transaction_id_and_card_details_flow() + }) + .unwrap_or(false); + if is_recurring_details_type_nti_and_card_details { + // no list of eligible connectors will be passed in the confirm call + logger::debug!("Authorize call for NTI and Card Details flow"); + payments::proxy_for_payments_core::< + api_types::Authorize, + payment_types::PaymentsResponse, + _, + _, + _, + payments::PaymentData<api_types::Authorize>, + >( + state, + req_state, + merchant_account, + profile_id, + key_store, + operation, + req, + auth_flow, + payments::CallConnectorAction::Trigger, + header_payload, + ) + .await + } else { + let eligible_connectors = req.connector.clone(); + match req.payment_type.unwrap_or_default() { + api_models::enums::PaymentType::Normal + | api_models::enums::PaymentType::RecurringMandate + | api_models::enums::PaymentType::NewMandate => { + payments::payments_core::< + api_types::Authorize, + payment_types::PaymentsResponse, + _, + _, + _, + payments::PaymentData<api_types::Authorize>, + >( + state, + req_state, + merchant_account, + profile_id, + key_store, + operation, + req, + auth_flow, + payments::CallConnectorAction::Trigger, + eligible_connectors, + header_payload, + ) + .await + } + api_models::enums::PaymentType::SetupMandate => { + payments::payments_core::< + api_types::SetupMandate, + payment_types::PaymentsResponse, + _, + _, + _, + payments::PaymentData<api_types::SetupMandate>, + >( + state, + req_state, + merchant_account, + profile_id, + key_store, + operation, + req, + auth_flow, + payments::CallConnectorAction::Trigger, + eligible_connectors, + header_payload, + ) + .await + } } } }
feat
add network transaction id support for mit payments (#6245)
2ac5b2cd764c0aad53ac7c672dfcc9132fa5668f
2023-12-01 13:29:14
Amisha Prabhat
fix(wasm): fix wasm function to return the categories for keys with their description respectively (#3023)
false
diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index cab82f8ce41..78c7677fe75 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -254,12 +254,25 @@ pub fn add_two(n1: i64, n2: i64) -> i64 { } #[wasm_bindgen(js_name = getDescriptionCategory)] -pub fn get_description_category(key: &str) -> JsResult { - let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; +pub fn get_description_category() -> JsResult { + let keys = dir::DirKeyKind::VARIANTS + .iter() + .copied() + .filter(|s| s != &"Connector") + .collect::<Vec<&'static str>>(); + let mut category: HashMap<Option<&str>, Vec<types::Details<'_>>> = HashMap::new(); + for key in keys { + let dir_key = + dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; + let details = types::Details { + description: dir_key.get_detailed_message(), + kind: dir_key.clone(), + }; + category + .entry(dir_key.get_str("Category")) + .and_modify(|val| val.push(details.clone())) + .or_insert(vec![details]); + } - let result = types::Details { - description: key.get_detailed_message(), - category: key.get_str("Category"), - }; - Ok(serde_wasm_bindgen::to_value(&result)?) + Ok(serde_wasm_bindgen::to_value(&category)?) } diff --git a/crates/euclid_wasm/src/types.rs b/crates/euclid_wasm/src/types.rs index ea40449971b..6353d9009c3 100644 --- a/crates/euclid_wasm/src/types.rs +++ b/crates/euclid_wasm/src/types.rs @@ -1,7 +1,8 @@ +use euclid::frontend::dir::DirKeyKind; use serde::Serialize; #[derive(Serialize, Clone)] pub struct Details<'a> { pub description: Option<&'a str>, - pub category: Option<&'a str>, + pub kind: DirKeyKind, }
fix
fix wasm function to return the categories for keys with their description respectively (#3023)
2162716426ad780f60e8d9bd918b4ac52596f20d
2023-06-08 12:34:11
Pa1NarK
fix(docs): Update command for getting app version (#1380)
false
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index f33acc41194..1036b27fd4a 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -72,7 +72,7 @@ body: If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` - 3. App version (output of `cargo r -- --version`): `` + 3. App version (output of `cargo r --features vergen -- --version`): `` validations: required: true
fix
Update command for getting app version (#1380)
5305a7b2f849fc29a786968ba02b9522d82164e4
2023-06-28 16:57:20
Arjun Karthik
feat(connector): [Payme] Add template code for Payme connector (#1486)
false
diff --git a/config/config.example.toml b/config/config.example.toml index ae626090d34..0b1031cdf2b 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -177,6 +177,7 @@ noon.base_url = "https://api-test.noonpayments.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" +payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" diff --git a/config/development.toml b/config/development.toml index 532af8931b9..34300667409 100644 --- a/config/development.toml +++ b/config/development.toml @@ -80,6 +80,7 @@ cards = [ "nuvei", "opennode", "payeezy", + "payme", "paypal", "payu", "shift4", @@ -132,6 +133,7 @@ noon.base_url = "https://api-test.noonpayments.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" +payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 3e7b9d98a41..58055da2411 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -98,6 +98,7 @@ noon.base_url = "https://api-test.noonpayments.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" +payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" @@ -140,6 +141,7 @@ cards = [ "nuvei", "opennode", "payeezy", + "payme", "paypal", "payu", "shift4", diff --git a/connector-template/test.rs b/connector-template/test.rs index 9885ccf67c7..42a72e249cb 100644 --- a/connector-template/test.rs +++ b/connector-template/test.rs @@ -280,28 +280,6 @@ async fn should_sync_refund() { } // Cards Negative scenerios -// Creates a payment with incorrect card number. -#[actix_web::test] -async fn should_fail_payment_for_incorrect_card_number() { - let response = CONNECTOR - .make_payment( - Some(types::PaymentsAuthorizeData { - payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_number: Secret::new("1234567891011".to_string()), - ..utils::CCardType::default().0 - }), - ..utils::PaymentAuthorizeType::default().0 - }), - get_default_payment_info(), - ) - .await - .unwrap(); - assert_eq!( - response.response.unwrap_err().message, - "Your card number is incorrect.".to_string(), - ); -} - // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs index dcf9dbcc2ed..d86c74856f3 100644 --- a/connector-template/transformers.rs +++ b/connector-template/transformers.rs @@ -97,6 +97,7 @@ impl<F,T> TryFrom<types::ResponseRouterData<F, {{project-name | downcase | pasca redirection_data: None, mandate_reference: None, connector_metadata: None, + network_txn_id: None }), ..item.data }) diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index be50be7db92..909334e6bf3 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -627,6 +627,7 @@ pub enum Connector { Noon, Nuvei, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage + Payme, Paypal, Payu, Rapyd, @@ -712,6 +713,7 @@ pub enum RoutableConnectors { Nuvei, Opennode, // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage + Payme, Paypal, Payu, Rapyd, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index f22d5e4be5c..4fb2eae7ff9 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -405,6 +405,7 @@ pub struct Connectors { pub nuvei: ConnectorParams, pub opennode: ConnectorParams, pub payeezy: ConnectorParams, + pub payme: ConnectorParams, pub paypal: ConnectorParams, pub payu: ConnectorParams, pub rapyd: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index fa6001e713a..a6f8aec9cc5 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -26,6 +26,7 @@ pub mod noon; pub mod nuvei; pub mod opennode; pub mod payeezy; +pub mod payme; pub mod paypal; pub mod payu; pub mod rapyd; @@ -45,7 +46,7 @@ pub use self::{ cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte, globalpay::Globalpay, iatapay::Iatapay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay, nexinets::Nexinets, nmi::Nmi, - noon::Noon, nuvei::Nuvei, opennode::Opennode, payeezy::Payeezy, paypal::Paypal, payu::Payu, - rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay, worldline::Worldline, - worldpay::Worldpay, zen::Zen, + noon::Noon, nuvei::Nuvei, opennode::Opennode, payeezy::Payeezy, payme::Payme, paypal::Paypal, + payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay, + worldline::Worldline, worldpay::Worldpay, zen::Zen, }; diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs new file mode 100644 index 00000000000..e18f4be06b5 --- /dev/null +++ b/crates/router/src/connector/payme.rs @@ -0,0 +1,514 @@ +mod transformers; + +use std::fmt::Debug; + +use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; +use transformers as payme; + +use crate::{ + configs::settings, + core::errors::{self, CustomResult}, + headers, + services::{ + self, + request::{self, Mask}, + ConnectorIntegration, + }, + types::{ + self, + api::{self, ConnectorCommon, ConnectorCommonExt}, + ErrorResponse, Response, + }, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Payme; + +impl api::Payment for Payme {} +impl api::PaymentSession for Payme {} +impl api::ConnectorAccessToken for Payme {} +impl api::PreVerify for Payme {} +impl api::PaymentAuthorize for Payme {} +impl api::PaymentSync for Payme {} +impl api::PaymentCapture for Payme {} +impl api::PaymentVoid for Payme {} +impl api::Refund for Payme {} +impl api::RefundExecute for Payme {} +impl api::RefundSync for Payme {} +impl api::PaymentToken for Payme {} + +impl + ConnectorIntegration< + api::PaymentMethodToken, + types::PaymentMethodTokenizationData, + types::PaymentsResponseData, + > for Payme +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payme +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &types::RouterData<Flow, Request, Response>, + _connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self) + .to_string() + .into(), + )]; + let mut api_key = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut api_key); + Ok(header) + } +} + +impl ConnectorCommon for Payme { + fn id(&self) -> &'static str { + "payme" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.payme.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + let auth = payme::PaymeAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + Ok(vec![( + headers::AUTHORIZATION.to_string(), + auth.api_key.peek().to_string().into_masked(), + )]) + } + + fn build_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: payme::PaymeErrorResponse = + res.response + .parse_struct("PaymeErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + Ok(ErrorResponse { + status_code: res.status_code, + code: response.code, + message: response.message, + reason: response.reason, + }) + } +} + +impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> + for Payme +{ + //TODO: implement sessions flow +} + +impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> + for Payme +{ +} + +impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData> + for Payme +{ +} + +impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> + for Payme +{ + fn get_headers( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let req_obj = payme::PaymePaymentsRequest::try_from(req)?; + let payme_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<payme::PaymePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(payme_req)) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsAuthorizeType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: payme::PaymePaymentsResponse = res + .response + .parse_struct("Payme PaymentsAuthorizeResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Payme +{ + fn get_headers( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::PaymentsSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsSyncRouterData, + res: Response, + ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + let response: payme::PaymePaymentsResponse = res + .response + .parse_struct("payme PaymentsSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> + for Payme +{ + fn get_headers( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + _req: &types::PaymentsCaptureRouterData, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsCaptureType::get_headers( + self, req, connectors, + )?) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCaptureRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + let response: payme::PaymePaymentsResponse = res + .response + .parse_struct("Payme PaymentsCaptureResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> + for Payme +{ +} + +impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Payme { + fn get_headers( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::RefundsRouterData<api::Execute>, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn get_request_body( + &self, + req: &types::RefundsRouterData<api::Execute>, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let req_obj = payme::PaymeRefundRequest::try_from(req)?; + let payme_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<payme::PaymeRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(payme_req)) + } + + fn build_request( + &self, + req: &types::RefundsRouterData<api::Execute>, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::RefundExecuteType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundExecuteType::get_headers( + self, req, connectors, + )?) + .body(types::RefundExecuteType::get_request_body(self, req)?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::RefundsRouterData<api::Execute>, + res: Response, + ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + let response: payme::RefundResponse = res + .response + .parse_struct("payme RefundResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payme { + fn get_headers( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::RefundSyncRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + } + + fn build_request( + &self, + req: &types::RefundSyncRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Get) + .url(&types::RefundSyncType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::RefundSyncType::get_headers(self, req, connectors)?) + .body(types::RefundSyncType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::RefundSyncRouterData, + res: Response, + ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + let response: payme::RefundResponse = res + .response + .parse_struct("payme RefundSyncResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Payme { + fn get_webhook_object_reference_id( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_event_type( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } + + fn get_webhook_resource_object( + &self, + _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + } +} diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs new file mode 100644 index 00000000000..6a5c9fd4be9 --- /dev/null +++ b/crates/router/src/connector/payme/transformers.rs @@ -0,0 +1,204 @@ +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + connector::utils::PaymentsAuthorizeRequestData, + core::errors, + types::{self, api, storage::enums}, +}; + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PaymePaymentsRequest { + amount: i64, + card: PaymeCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PaymeCard { + name: Secret<String>, + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymePaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data.clone() { + api::PaymentMethodData::Card(req_card) => { + let card = PaymeCard { + name: req_card.card_holder_name, + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.request.amount, + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct PaymeAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for PaymeAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { + api_key: Secret::new(api_key.to_string()), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} +// PaymentsResponse +//TODO: Append the remaining status flags +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum PaymePaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<PaymePaymentStatus> for enums::AttemptStatus { + fn from(item: PaymePaymentStatus) -> Self { + match item { + PaymePaymentStatus::Succeeded => Self::Charged, + PaymePaymentStatus::Failed => Self::Failure, + PaymePaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct PaymePaymentsResponse { + status: PaymePaymentStatus, + id: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PaymePaymentsResponse, T, types::PaymentsResponseData>> + for types::RouterData<F, T, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PaymePaymentsResponse, T, types::PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: enums::AttemptStatus::from(item.response.status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct PaymeRefundRequest { + pub amount: i64, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for PaymeRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + amount: item.request.refund_amount, + }) + } +} + +// Type definition for Refund Response + +#[allow(dead_code)] +#[derive(Debug, Serialize, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + RefundStatus::Succeeded => Self::Success, + RefundStatus::Failed => Self::Failure, + RefundStatus::Processing => Self::Pending, + //TODO: Review mapping + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct RefundResponse { + id: String, + status: RefundStatus, +} + +impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> + for types::RefundsRouterData<api::Execute> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id.to_string(), + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +pub struct PaymeErrorResponse { + pub status_code: u16, + pub code: String, + pub message: String, + pub reason: Option<String>, +} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index f01513f99b4..71ac1e609b2 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -157,6 +157,7 @@ default_imp_for_complete_authorize!( connector::Noon, connector::Opennode, connector::Payeezy, + connector::Payme, connector::Payu, connector::Rapyd, connector::Stripe, @@ -220,6 +221,7 @@ default_imp_for_create_customer!( connector::Opennode, connector::Payeezy, connector::Paypal, + connector::Payme, connector::Payu, connector::Rapyd, connector::Shift4, @@ -277,6 +279,7 @@ default_imp_for_connector_redirect_response!( connector::Nmi, connector::Opennode, connector::Payeezy, + connector::Payme, connector::Payu, connector::Rapyd, connector::Shift4, @@ -321,6 +324,7 @@ default_imp_for_connector_request_id!( connector::Nuvei, connector::Opennode, connector::Payeezy, + connector::Payme, connector::Payu, connector::Rapyd, connector::Shift4, @@ -387,6 +391,7 @@ default_imp_for_accept_dispute!( connector::Nuvei, connector::Payeezy, connector::Paypal, + connector::Payme, connector::Payu, connector::Rapyd, connector::Shift4, @@ -473,6 +478,7 @@ default_imp_for_file_upload!( connector::Nuvei, connector::Payeezy, connector::Paypal, + connector::Payme, connector::Payu, connector::Rapyd, connector::Shift4, @@ -536,6 +542,7 @@ default_imp_for_submit_evidence!( connector::Nuvei, connector::Payeezy, connector::Paypal, + connector::Payme, connector::Payu, connector::Rapyd, connector::Shift4, @@ -599,6 +606,7 @@ default_imp_for_defend_dispute!( connector::Nuvei, connector::Payeezy, connector::Paypal, + connector::Payme, connector::Payu, connector::Rapyd, connector::Stripe, @@ -665,6 +673,7 @@ default_imp_for_pre_processing_steps!( connector::Opennode, connector::Payeezy, connector::Paypal, + connector::Payme, connector::Payu, connector::Rapyd, connector::Shift4, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 5afe9cd368f..e9fe23c828f 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -231,6 +231,7 @@ impl ConnectorData { enums::Connector::Nuvei => Ok(Box::new(&connector::Nuvei)), enums::Connector::Opennode => Ok(Box::new(&connector::Opennode)), // "payeezy" => Ok(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage + enums::Connector::Payme => Ok(Box::new(&connector::Payme)), enums::Connector::Payu => Ok(Box::new(&connector::Payu)), enums::Connector::Rapyd => Ok(Box::new(&connector::Rapyd)), enums::Connector::Shift4 => Ok(Box::new(&connector::Shift4)), diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index e0299ce3a57..a28bd237446 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -32,6 +32,7 @@ pub struct ConnectorAuthentication { pub nuvei: Option<SignatureKey>, pub opennode: Option<HeaderKey>, pub payeezy: Option<SignatureKey>, + pub payme: Option<HeaderKey>, pub paypal: Option<BodyKey>, pub payu: Option<BodyKey>, pub rapyd: Option<BodyKey>, diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 62b39494afc..8aec668749e 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -34,6 +34,7 @@ mod nuvei; mod nuvei_ui; mod opennode; mod payeezy; +mod payme; mod paypal; mod payu; mod payu_ui; diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs new file mode 100644 index 00000000000..6c0e0cac92d --- /dev/null +++ b/crates/router/tests/connectors/payme.rs @@ -0,0 +1,420 @@ +use masking::Secret; +use router::types::{self, api, storage::enums}; + +use crate::{ + connector_auth, + utils::{self, ConnectorActions}, +}; + +#[derive(Clone, Copy)] +struct PaymeTest; +impl ConnectorActions for PaymeTest {} +impl utils::Connector for PaymeTest { + fn get_data(&self) -> types::api::ConnectorData { + use router::connector::Payme; + types::api::ConnectorData { + connector: Box::new(&Payme), + connector_name: types::Connector::Payme, + get_token: types::api::GetToken::Connector, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + types::ConnectorAuthType::from( + connector_auth::ConnectorAuthentication::new() + .payme + .expect("Missing connector authentication configuration"), + ) + } + + fn get_name(&self) -> String { + "payme".to_string() + } +} + +static CONNECTOR: PaymeTest = PaymeTest {}; + +fn get_default_payment_info() -> Option<utils::PaymentInfo> { + None +} + +fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { + None +} + +// Cards Positive Tests +// Creates a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_only_authorize_payment() { + let response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized); +} + +// Captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Partially captures a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_capture_authorized_payment() { + let response = CONNECTOR + .authorize_and_capture_payment( + payment_method_details(), + Some(types::PaymentsCaptureData { + amount_to_capture: 50, + ..utils::PaymentCaptureType::default().0 + }), + get_default_payment_info(), + ) + .await + .expect("Capture payment response"); + assert_eq!(response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_authorized_payment() { + let authorize_response = CONNECTOR + .authorize_payment(payment_method_details(), get_default_payment_info()) + .await + .expect("Authorize payment response"); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Authorized, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("PSync response"); + assert_eq!(response.status, enums::AttemptStatus::Authorized,); +} + +// Voids a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_void_authorized_payment() { + let response = CONNECTOR + .authorize_and_void_payment( + payment_method_details(), + Some(types::PaymentsCancelData { + connector_transaction_id: String::from(""), + cancellation_reason: Some("requested_by_customer".to_string()), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .expect("Void payment response"); + assert_eq!(response.status, enums::AttemptStatus::Voided); +} + +// Refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_manually_captured_payment() { + let response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Synchronizes a refund using the manual capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_manually_captured_refund() { + let refund_response = CONNECTOR + .capture_payment_and_refund( + payment_method_details(), + None, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_make_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); +} + +// Synchronizes a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_auto_captured_payment() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let response = CONNECTOR + .psync_retry_till_status_matches( + enums::AttemptStatus::Charged, + Some(types::PaymentsSyncData { + connector_transaction_id: router::types::ResponseId::ConnectorTransactionId( + txn_id.unwrap(), + ), + capture_method: Some(enums::CaptureMethod::Automatic), + ..Default::default() + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!(response.status, enums::AttemptStatus::Charged,); +} + +// Refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_auto_captured_payment() { + let response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Partially refunds a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_partially_refund_succeeded_payment() { + let refund_response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + refund_response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_refund_succeeded_payment_multiple_times() { + CONNECTOR + .make_payment_and_multiple_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 50, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await; +} + +// Synchronizes a refund using the automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_sync_refund() { + let refund_response = CONNECTOR + .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) + .await + .unwrap(); + let response = CONNECTOR + .rsync_retry_till_status_matches( + enums::RefundStatus::Success, + refund_response.response.unwrap().connector_refund_id, + None, + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap().refund_status, + enums::RefundStatus::Success, + ); +} + +// Cards Negative scenerios +// Creates a payment with incorrect CVC. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_cvc() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_cvc: Secret::new("12345".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's security code is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry month. +#[actix_web::test] +async fn should_fail_payment_for_invalid_exp_month() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_exp_month: Secret::new("20".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration month is invalid.".to_string(), + ); +} + +// Creates a payment with incorrect expiry year. +#[actix_web::test] +async fn should_fail_payment_for_incorrect_expiry_year() { + let response = CONNECTOR + .make_payment( + Some(types::PaymentsAuthorizeData { + payment_method_data: types::api::PaymentMethodData::Card(api::Card { + card_exp_year: Secret::new("2000".to_string()), + ..utils::CCardType::default().0 + }), + ..utils::PaymentAuthorizeType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Your card's expiration year is invalid.".to_string(), + ); +} + +// Voids a payment using automatic capture flow (Non 3DS). +#[actix_web::test] +async fn should_fail_void_payment_for_auto_capture() { + let authorize_response = CONNECTOR + .make_payment(payment_method_details(), get_default_payment_info()) + .await + .unwrap(); + assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + let txn_id = utils::get_connector_transaction_id(authorize_response.response); + assert_ne!(txn_id, None, "Empty connector transaction id"); + let void_response = CONNECTOR + .void_payment(txn_id.unwrap(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + void_response.response.unwrap_err().message, + "You cannot cancel this PaymentIntent because it has a status of succeeded." + ); +} + +// Captures a payment using invalid connector payment id. +#[actix_web::test] +async fn should_fail_capture_for_invalid_payment() { + let capture_response = CONNECTOR + .capture_payment("123456789".to_string(), None, get_default_payment_info()) + .await + .unwrap(); + assert_eq!( + capture_response.response.unwrap_err().message, + String::from("No such payment_intent: '123456789'") + ); +} + +// Refunds a payment with refund amount higher than payment amount. +#[actix_web::test] +async fn should_fail_for_refund_amount_higher_than_payment_amount() { + let response = CONNECTOR + .make_payment_and_refund( + payment_method_details(), + Some(types::RefundsData { + refund_amount: 150, + ..utils::PaymentRefundType::default().0 + }), + get_default_payment_info(), + ) + .await + .unwrap(); + assert_eq!( + response.response.unwrap_err().message, + "Refund amount (₹1.50) is greater than charge amount (₹1.00)", + ); +} + +// Connector dependent test cases goes here + +// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 18d1e225704..4248bff252f 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -127,6 +127,9 @@ pypl_pass="" gmail_email="" gmail_pass="" +[payme] +api_key="API Key" + [cashtocode] api_key="Classic PMT API Key" -key1 = "Evoucher PMT API Key" \ No newline at end of file +key1 = "Evoucher PMT API Key" diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 6e87c6c307f..c5d43ae1416 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -85,6 +85,7 @@ noon.base_url = "https://api-test.noonpayments.com/" nuvei.base_url = "https://ppp-test.nuvei.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" +payme.base_url = "https://sandbox.payme.io/" paypal.base_url = "https://www.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" rapyd.base_url = "https://sandboxapi.rapyd.net" @@ -126,6 +127,7 @@ cards = [ "nuvei", "opennode", "payeezy", + "payme", "paypal", "payu", "shift4", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index de14e410491..2f50ad148ce 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -4,7 +4,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # add new connector to existing list and sort it - connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree cashtocode checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay iatapay klarna mollie multisafepay nexinets noon nuvei opennode payeezy paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1") + connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree cashtocode checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay iatapay klarna mollie multisafepay nexinets noon nuvei opennode payeezy payme paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
feat
[Payme] Add template code for Payme connector (#1486)
15987cc81ecba3c1d0de4fa0a12424066a8842eb
2023-12-21 18:26:32
Shankar Singh C
feat(router): make the billing country for apple pay as optional field (#3188)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5efebb14f81..d2df44a9b21 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3004,7 +3004,7 @@ pub struct SecretInfoToInitiateSdk { pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] - pub country_code: api_enums::CountryAlpha2, + pub country_code: Option<api_enums::CountryAlpha2>, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 3a980aee819..17cdf3b519b 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -529,7 +529,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons session_response, ), payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { - country_code: item.data.get_billing_country()?, + country_code: item.data.request.country, currency_code: item.data.request.currency, total: api_models::payments::AmountInfo { label: payment_request_data.label, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index e3d54881f1f..a865b8fec3a 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -545,6 +545,13 @@ impl<F> } _ => { let currency_code = item.data.request.get_currency()?; + let country_code = item + .data + .address + .billing + .as_ref() + .and_then(|billing| billing.address.as_ref()) + .and_then(|address| address.country); let amount = item.data.request.get_amount()?; let amount_in_base_unit = utils::to_currency_base_unit(amount, currency_code)?; let pmd = item.data.request.payment_method_data.to_owned(); @@ -559,7 +566,7 @@ impl<F> api_models::payments::ApplePaySessionResponse::NoSessionResponse, payment_request_data: Some( api_models::payments::ApplePayPaymentRequest { - country_code: item.data.get_billing_country()?, + country_code, currency_code, total: api_models::payments::AmountInfo { label: "Apple Pay".to_string(), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index cca0c2d9893..8ae12622fb0 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1181,7 +1181,7 @@ pub fn get_apple_pay_session<F, T>( }, ), payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { - country_code: apple_pay_init_result.country_code, + country_code: Some(apple_pay_init_result.country_code), currency_code: apple_pay_init_result.currency_code, supported_networks: Some(apple_pay_init_result.supported_networks.clone()), merchant_capabilities: Some( diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 91513019179..de697e02f78 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -371,13 +371,7 @@ fn get_apple_pay_payment_request( merchant_identifier: &str, ) -> RouterResult<payment_types::ApplePayPaymentRequest> { let applepay_payment_request = payment_types::ApplePayPaymentRequest { - country_code: session_data - .country - .to_owned() - .get_required_value("country_code") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "country_code", - })?, + country_code: session_data.country, currency_code: session_data.currency, total: amount_info, merchant_capabilities: Some(payment_request_data.merchant_capabilities),
feat
make the billing country for apple pay as optional field (#3188)
56f14b935d5e9742a894408a714033318ecb6f2a
2024-04-24 12:59:31
James M
docs(try_local_system): update WSL setup guide to address a memory issue (#4431)
false
diff --git a/docs/try_local_system.md b/docs/try_local_system.md index a9cd080f26d..a13d04ade83 100644 --- a/docs/try_local_system.md +++ b/docs/try_local_system.md @@ -222,6 +222,7 @@ Once you're done with setting up the dependencies, proceed with [postgresql-install]: https://www.postgresql.org/download/ [redis-install]: https://redis.io/docs/getting-started/installation/ +[wsl-config]: https://learn.microsoft.com/en-us/windows/wsl/wsl-config/ ### Set up dependencies on Windows (Ubuntu on WSL2) @@ -241,6 +242,8 @@ packages for your distribution and follow along. The following steps assume that you are running the commands within the WSL shell environment. + > Note that a `SIGKILL` error may occur when compiling certain crates if WSL is unable to use sufficient memory. It may be necessary to allow up to 24GB of memory, but your mileage may vary. You may increase the amount of memory WSL can use via a `.wslconfig` file in your Windows user folder, or by creating a swap file in WSL itself. Refer to the [WSL configuration documentation][wsl-config] for more information. + 2. Install the stable Rust toolchain using `rustup`: ```shell
docs
update WSL setup guide to address a memory issue (#4431)
c42b436abe1ed980d9b861dd4ba56324c8361a5a
2023-06-15 15:40:30
Nishant Joshi
fix(stripe): fix logs on stripe connector integration (#1448)
false
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 04d0c3884e9..2baae6dbfb4 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -479,8 +479,9 @@ impl &self, req: &types::PaymentsCaptureRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { - router_env::logger::info!(connector_request=?req); - let stripe_req = utils::Encode::<stripe::CaptureRequest>::convert_and_url_encode(req) + let connector_request = stripe::CaptureRequest::try_from(req)?; + router_env::logger::info!(?connector_request); + let stripe_req = utils::Encode::<stripe::CaptureRequest>::url_encode(&connector_request) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -866,8 +867,9 @@ impl &self, req: &types::PaymentsCancelRouterData, ) -> CustomResult<Option<String>, errors::ConnectorError> { - router_env::logger::info!(connector_request=?req); - let stripe_req = utils::Encode::<stripe::CancelRequest>::convert_and_url_encode(req) + let connector_request = stripe::CancelRequest::try_from(req)?; + router_env::logger::info!(?connector_request); + let stripe_req = utils::Encode::<stripe::CancelRequest>::url_encode(&connector_request) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -1095,8 +1097,9 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<String>, errors::ConnectorError> { - router_env::logger::info!(connector_request=?req); - let stripe_req = utils::Encode::<stripe::RefundRequest>::convert_and_url_encode(req) + let connector_request = stripe::RefundRequest::try_from(req)?; + router_env::logger::info!(?connector_request); + let stripe_req = utils::Encode::<stripe::RefundRequest>::url_encode(&connector_request) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) }
fix
fix logs on stripe connector integration (#1448)
6f841458f73cec8ce43a34b1b50abbc74baa2ef7
2024-12-10 16:09:46
Swangi Kumari
refactor(payment_methods): Add new field_type UserBsbNumber, UserBankSortCode and UserBankRoutingNumber for payment_connector_required_fields (#6758)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 64949c3812b..2cd5467f06e 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -8583,6 +8583,24 @@ "user_iban" ] }, + { + "type": "string", + "enum": [ + "user_bsb_number" + ] + }, + { + "type": "string", + "enum": [ + "user_bank_sort_code" + ] + }, + { + "type": "string", + "enum": [ + "user_bank_routing_number" + ] + }, { "type": "string", "enum": [ diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 2dced0998e9..937dc7ab2d9 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -10925,6 +10925,24 @@ "user_iban" ] }, + { + "type": "string", + "enum": [ + "user_bsb_number" + ] + }, + { + "type": "string", + "enum": [ + "user_bank_sort_code" + ] + }, + { + "type": "string", + "enum": [ + "user_bank_routing_number" + ] + }, { "type": "string", "enum": [ diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 4af3f855d77..4275b10fd81 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -223,6 +223,9 @@ pub enum FieldType { UserCpf, UserCnpj, UserIban, + UserBsbNumber, + UserBankSortCode, + UserBankRoutingNumber, UserMsisdn, UserClientIdentifier, OrderDetailsProductName, diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index c759b724414..0954ac51c7d 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -11634,7 +11634,7 @@ impl Default for settings::RequiredFields { RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), display_name: "bank_routing_number".to_string(), - field_type: enums::FieldType::Text, + field_type: enums::FieldType::UserBankRoutingNumber, value: None, } ) @@ -11676,7 +11676,7 @@ impl Default for settings::RequiredFields { RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), display_name: "bank_routing_number".to_string(), - field_type: enums::FieldType::Text, + field_type: enums::FieldType::UserBankRoutingNumber, value: None, } ) @@ -11845,7 +11845,7 @@ impl Default for settings::RequiredFields { RequiredFieldInfo { required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), - field_type: enums::FieldType::Text, + field_type: enums::FieldType::UserBankSortCode, value: None, } ), @@ -11917,7 +11917,7 @@ impl Default for settings::RequiredFields { RequiredFieldInfo { required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), - field_type: enums::FieldType::Text, + field_type: enums::FieldType::UserBankSortCode, value: None, } ) @@ -11967,7 +11967,7 @@ impl Default for settings::RequiredFields { RequiredFieldInfo { required_field: "payment_method_data.bank_debit.becs_bank_debit.bsb_number".to_string(), display_name: "bsb_number".to_string(), - field_type: enums::FieldType::Text, + field_type: enums::FieldType::UserBsbNumber, value: None, } ), @@ -12019,7 +12019,7 @@ impl Default for settings::RequiredFields { RequiredFieldInfo { required_field: "payment_method_data.bank_debit.becs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), - field_type: enums::FieldType::Text, + field_type: enums::FieldType::UserBankSortCode, value: None, } )
refactor
Add new field_type UserBsbNumber, UserBankSortCode and UserBankRoutingNumber for payment_connector_required_fields (#6758)
158431391d560be4a79160ccea7bf5feaa4b52db
2023-10-19 19:47:48
Saikiran Patil
refactor(connector): [Dlocal] remove default case handling (#2624)
false
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 87562fa3344..5146dd0ea03 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -157,7 +157,20 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP }; Ok(payment_request) } - _ => Err(errors::ConnectorError::NotImplemented("Payment Method".to_string()).into()), + api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + crate::connector::utils::get_unimplemented_payment_method_error_message("Dlocal"), + ))?, } } }
refactor
[Dlocal] remove default case handling (#2624)
e79cdaa9d94a66bb2696929fd94af18cd252d5e7
2023-01-18 20:53:14
Jagan
fix(connector): fix rsync for shift4 (#410)
false
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 3f76f0aef61..64c715c2263 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -21,7 +21,7 @@ use crate::{ api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, - utils::{self, BytesExt}, + utils::{self, BytesExt, OptionExt}, }; #[derive(Debug, Clone)] @@ -433,10 +433,21 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - _req: &types::RefundSyncRouterData, + req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}refunds", self.base_url(connectors),)) + let refund_id = req + .response + .clone() + .ok() + .get_required_value("response") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + .connector_refund_id; + Ok(format!( + "{}refunds/{}", + self.base_url(connectors), + refund_id + )) } fn build_request(
fix
fix rsync for shift4 (#410)
396a64f3bbad6e75d4b263286a7ef6a2f09b180e
2023-12-19 23:34:57
Kashif Soofi
feat(db): Implement `AuthorizationInterface` for `MockDb` (#3151)
false
diff --git a/crates/diesel_models/src/authorization.rs b/crates/diesel_models/src/authorization.rs index 64fd1c65187..b6f75bbb9b7 100644 --- a/crates/diesel_models/src/authorization.rs +++ b/crates/diesel_models/src/authorization.rs @@ -57,6 +57,21 @@ pub struct AuthorizationUpdateInternal { pub connector_authorization_id: Option<String>, } +impl AuthorizationUpdateInternal { + pub fn create_authorization(self, source: Authorization) -> Authorization { + Authorization { + status: self.status.unwrap_or(source.status), + error_code: self.error_code.or(source.error_code), + error_message: self.error_message.or(source.error_message), + modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()), + connector_authorization_id: self + .connector_authorization_id + .or(source.connector_authorization_id), + ..source + } + } +} + impl From<AuthorizationUpdate> for AuthorizationUpdateInternal { fn from(authorization_child_update: AuthorizationUpdate) -> Self { let now = Some(common_utils::date_time::now()); diff --git a/crates/router/src/db/authorization.rs b/crates/router/src/db/authorization.rs index f24daaf718a..d167d177537 100644 --- a/crates/router/src/db/authorization.rs +++ b/crates/router/src/db/authorization.rs @@ -1,3 +1,4 @@ +use diesel_models::authorization::AuthorizationUpdateInternal; use error_stack::IntoReport; use super::{MockDb, Store}; @@ -77,28 +78,71 @@ impl AuthorizationInterface for Store { impl AuthorizationInterface for MockDb { async fn insert_authorization( &self, - _authorization: storage::AuthorizationNew, + authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut authorizations = self.authorizations.lock().await; + if authorizations.iter().any(|authorization_inner| { + authorization_inner.authorization_id == authorization.authorization_id + }) { + Err(errors::StorageError::DuplicateValue { + entity: "authorization_id", + key: None, + })? + } + let authorization = storage::Authorization { + authorization_id: authorization.authorization_id, + merchant_id: authorization.merchant_id, + payment_id: authorization.payment_id, + amount: authorization.amount, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + status: authorization.status, + error_code: authorization.error_code, + error_message: authorization.error_message, + connector_authorization_id: authorization.connector_authorization_id, + previously_authorized_amount: authorization.previously_authorized_amount, + }; + authorizations.push(authorization.clone()); + Ok(authorization) } async fn find_all_authorizations_by_merchant_id_payment_id( &self, - _merchant_id: &str, - _payment_id: &str, + merchant_id: &str, + payment_id: &str, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let authorizations = self.authorizations.lock().await; + let authorizations_found: Vec<storage::Authorization> = authorizations + .iter() + .filter(|a| a.merchant_id == merchant_id && a.payment_id == payment_id) + .cloned() + .collect(); + + Ok(authorizations_found) } async fn update_authorization_by_merchant_id_authorization_id( &self, - _merchant_id: String, - _authorization_id: String, - _authorization: storage::AuthorizationUpdate, + merchant_id: String, + authorization_id: String, + authorization_update: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut authorizations = self.authorizations.lock().await; + authorizations + .iter_mut() + .find(|authorization| authorization.authorization_id == authorization_id && authorization.merchant_id == merchant_id) + .map(|authorization| { + let authorization_updated = + AuthorizationUpdateInternal::from(authorization_update) + .create_authorization(authorization.clone()); + *authorization = authorization_updated.clone(); + authorization_updated + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id}" + )) + .into(), + ) } } diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index e22d39ce70c..a6ba763bd91 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -43,6 +43,7 @@ pub struct MockDb { pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>, pub users: Arc<Mutex<Vec<store::user::User>>>, pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, + pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, } @@ -79,6 +80,7 @@ impl MockDb { organizations: Default::default(), users: Default::default(), user_roles: Default::default(), + authorizations: Default::default(), dashboard_metadata: Default::default(), }) }
feat
Implement `AuthorizationInterface` for `MockDb` (#3151)
a3c2694943a985d27b5bc8b0371884d17a6ca34d
2024-10-04 05:54:58
github-actions
chore(version): 2024.10.04.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d44b83b81c..a1aa83c5fa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.10.04.0 + +### Features + +- **connector:** [Digital Virgo] template for integration ([#6145](https://github.com/juspay/hyperswitch/pull/6145)) ([`be3cf2c`](https://github.com/juspay/hyperswitch/commit/be3cf2c8693f4725e8c8ebd59412385dd4dcb7a1)) +- **router:** Add profile level auto retries config support ([#6200](https://github.com/juspay/hyperswitch/pull/6200)) ([`5648977`](https://github.com/juspay/hyperswitch/commit/56489771e403864602adff5f954d1f59c65764c3)) + +### Bug Fixes + +- **bug:** [IATAPAY] Fix PCM value for UPI_COLLECT ([#6207](https://github.com/juspay/hyperswitch/pull/6207)) ([`81e3d9d`](https://github.com/juspay/hyperswitch/commit/81e3d9df901d1b874dcbd5cd01f0b5532ae981a1)) +- **payment_intent:** Batch encrypt and decrypt payment intent ([#6164](https://github.com/juspay/hyperswitch/pull/6164)) ([`369939a`](https://github.com/juspay/hyperswitch/commit/369939a37385fe85fd3430d9be0b7b0698962625)) + +**Full Changelog:** [`2024.10.03.0...2024.10.04.0`](https://github.com/juspay/hyperswitch/compare/2024.10.03.0...2024.10.04.0) + +- - - + ## 2024.10.03.0 ### Features
chore
2024.10.04.0
7f4f55b63af86cab11421f8ed2979a4ec90b8a44
2024-11-12 12:15:44
Pa1NarK
fix: trustpay `eps` redirection in cypress (#6529)
false
diff --git a/cypress-tests/cypress/support/redirectionHandler.js b/cypress-tests/cypress/support/redirectionHandler.js index b3eb89868f0..5e05ad27911 100644 --- a/cypress-tests/cypress/support/redirectionHandler.js +++ b/cypress-tests/cypress/support/redirectionHandler.js @@ -225,19 +225,10 @@ function bankRedirectRedirection( case "trustpay": switch (payment_method_type) { case "eps": - cy.get("._transactionId__header__iXVd_").should( - "contain.text", - "Bank suchen ‑ mit eps zahlen." - ); - cy.get(".BankSearch_searchInput__uX_9l").type( - "Allgemeine Sparkasse Oberösterreich Bank AG{enter}" - ); - cy.get(".BankSearch_searchResultItem__lbcKm").click(); - cy.get("._transactionId__primaryButton__nCa0r").click(); - cy.get("#loginTitle").should( - "contain.text", - "eps Online-Überweisung Login" + cy.get("#bankname").type( + "Allgemeine Sparkasse Oberösterreich Bank AG (ASPKAT2LXXX / 20320)" ); + cy.get("#selectionSubmit").click(); cy.get("#user") .should("be.visible") .should("be.enabled")
fix
trustpay `eps` redirection in cypress (#6529)
18f912def7e2a879bc6d994955514d2f80ad14b9
2024-08-29 21:16:56
AkshayaFoiger
refactor(router): revert [Stripe/Itau/Paypal/Bambora/Cybs] prevent partial submission of billing address and add required fields for all payment methods (#5745)
false
diff --git a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs index b47c741c8d5..8499aecaed7 100644 --- a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs @@ -1,9 +1,6 @@ use base64::Engine; use common_enums::enums; -use common_utils::{ - ext_traits::ValueExt, - pii::{Email, IpAddress}, -}; +use common_utils::{ext_traits::ValueExt, pii::IpAddress}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, @@ -89,7 +86,6 @@ pub struct BamboraPaymentsRequest { customer_ip: Option<Secret<String, IpAddress>>, term_url: Option<String>, card: BamboraCard, - billing: AddressData, } #[derive(Default, Debug, Serialize)] @@ -177,29 +173,6 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora complete: item.router_data.request.is_auto_capture()?, }; - let province = item - .router_data - .get_optional_billing_state() - .and_then(|state| { - if state.clone().expose().len() > 2 { - None - } else { - Some(state) - } - }); - - let billing = AddressData { - name: item.router_data.get_optional_billing_full_name(), - address_line1: item.router_data.get_optional_billing_line1(), - address_line2: item.router_data.get_optional_billing_line2(), - city: item.router_data.get_optional_billing_city(), - province, - country: item.router_data.get_optional_billing_country(), - postal_code: item.router_data.get_optional_billing_zip(), - phone_number: item.router_data.get_optional_billing_phone_number(), - email_address: item.router_data.get_optional_billing_email(), - }; - Ok(Self { order_number: item.router_data.connector_request_reference_id.clone(), amount: item.amount, @@ -207,7 +180,6 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora card, customer_ip, term_url: item.router_data.request.complete_authorize_url.clone(), - billing, }) } PaymentMethodData::CardRedirect(_) @@ -370,15 +342,15 @@ pub struct AvsObject { #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct AddressData { - name: Option<Secret<String>>, - address_line1: Option<Secret<String>>, - address_line2: Option<Secret<String>>, - city: Option<String>, - province: Option<Secret<String>>, - country: Option<enums::CountryAlpha2>, - postal_code: Option<Secret<String>>, - phone_number: Option<Secret<String>>, - email_address: Option<Email>, + name: Secret<String>, + address_line1: Secret<String>, + address_line2: Secret<String>, + city: String, + province: String, + country: String, + postal_code: Secret<String>, + phone_number: Secret<String>, + email_address: Secret<String>, } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 3031b8c002e..9a2af153ee6 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -527,15 +527,6 @@ impl Default for super::settings::RequiredFields { value: None, } ), - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ) ] ), common: HashMap::new(), @@ -1008,9 +999,9 @@ impl Default for super::settings::RequiredFields { } ), ( - "billing.email".to_string(), + "email".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), + required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, @@ -3352,15 +3343,6 @@ impl Default for super::settings::RequiredFields { value: None, } ), - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ) ] ), common: HashMap::new(), @@ -3833,9 +3815,9 @@ impl Default for super::settings::RequiredFields { } ), ( - "billing.email".to_string(), + "email".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), + required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, @@ -6145,17 +6127,7 @@ impl Default for super::settings::RequiredFields { enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::from([ - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ) - ]), + non_mandate: HashMap::new(), common: HashMap::new(), } )]), @@ -6176,7 +6148,9 @@ impl Default for super::settings::RequiredFields { ( enums::Connector::Stripe, RequiredFieldFinal { - mandate: HashMap::from([ + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { @@ -6185,10 +6159,7 @@ impl Default for super::settings::RequiredFields { field_type: enums::FieldType::UserEmailAddress, value: None, } - ) - ]), - non_mandate: HashMap::new(), - common: HashMap::from([ + ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { @@ -7008,10 +6979,27 @@ impl Default for super::settings::RequiredFields { field_type: enums::FieldType::UserEmailAddress, value: None, } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.first_name".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.last_name".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } ) ]), - non_mandate : HashMap::new(), - common: HashMap::from([ + non_mandate : HashMap::from([ ("billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), @@ -7027,25 +7015,10 @@ impl Default for super::settings::RequiredFields { }, value: None, } - ), - ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.first_name".to_string(), - display_name: "account_holder_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "account_holder_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } )]), + common: HashMap::new( + + ), } ), ( @@ -7617,9 +7590,9 @@ impl Default for super::settings::RequiredFields { non_mandate: HashMap::from( [ ( - "billing.email".to_string(), + "email".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), + required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, @@ -8101,9 +8074,9 @@ impl Default for super::settings::RequiredFields { non_mandate: HashMap::from( [ ( - "billing.email".to_string(), + "email".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), + required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, @@ -8431,21 +8404,6 @@ impl Default for super::settings::RequiredFields { ]), }, ), - ( - enums::PaymentMethodType::Cashapp, - ConnectorFields { - fields: HashMap::from([ - ( - enums::Connector::Stripe, - RequiredFieldFinal { - mandate: HashMap::new(), - non_mandate: HashMap::new(), - common: HashMap::new(), - } - ) - ]), - }, - ), ( enums::PaymentMethodType::MbWay, ConnectorFields { @@ -8637,7 +8595,8 @@ impl Default for super::settings::RequiredFields { enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::new(), + non_mandate: HashMap::new( + ), common: HashMap::new(), } ), @@ -8850,153 +8809,20 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate : HashMap::new(), non_mandate: HashMap::from([ - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ), - ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.first_name".to_string(), - display_name: "billing_first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "billing_last_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "billing.address.line1".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressLine1, - value: None, - } - ), - ( - "billing.address.city".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserAddressCity, - value: None, - } - ), - ( - "billing.address.zip".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, - value: None, - } - ), - ( - "billing.address.country".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserAddressCountry{ - options: vec![ - "GB".to_string(), - "AU".to_string(), - "CA".to_string(), - "US".to_string(), - "NZ".to_string(), - ] - }, - value: None, - } - ), - ( - "billing.address.state".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.state".to_string(), - display_name: "state".to_string(), - field_type: enums::FieldType::UserAddressState, - value: None, - } - ), - ( - "shipping.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "shipping.address.first_name".to_string(), - display_name: "shipping_first_name".to_string(), - field_type: enums::FieldType::UserShippingName, - value: None, - } - ), - ( - "shipping.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "shipping.address.last_name".to_string(), - display_name: "shipping_last_name".to_string(), - field_type: enums::FieldType::UserShippingName, - value: None, - } - ), - ( - "shipping.address.city".to_string(), - RequiredFieldInfo { - required_field: "shipping.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserShippingAddressCity, - value: None, - } - ), - ( - "shipping.address.state".to_string(), - RequiredFieldInfo { - required_field: "shipping.address.state".to_string(), - display_name: "state".to_string(), - field_type: enums::FieldType::UserShippingAddressState, - value: None, - } - ), - ( - "shipping.address.zip".to_string(), - RequiredFieldInfo { - required_field: "shipping.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserShippingAddressPincode, - value: None, - } - ), - ( - "shipping.address.country".to_string(), - RequiredFieldInfo { - required_field: "shipping.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserShippingAddressCountry{ - options: vec![ - "ALL".to_string(), - ] - }, - value: None, - } - ), - ( - "shipping.address.line1".to_string(), + ( "name".to_string(), RequiredFieldInfo { - required_field: "shipping.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserShippingAddressLine1, - value: None, - } - ), + required_field: "name".to_string(), + display_name: "cust_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + }), + ("payment_method_data.pay_later.afterpay_clearpay_redirect.billing_email".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.pay_later.afterpay_clearpay_redirect.billing_email".to_string(), + display_name: "billing_email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + }) ]), common : HashMap::new(), } @@ -9169,30 +8995,8 @@ impl Default for super::settings::RequiredFields { required_field: "payment_method_data.pay_later.klarna.billing_country".to_string(), display_name: "billing_country".to_string(), field_type: enums::FieldType::UserAddressCountry{ - options: vec![ - "AU".to_string(), - "AT".to_string(), - "BE".to_string(), - "CA".to_string(), - "CZ".to_string(), - "DK".to_string(), - "FI".to_string(), - "FR".to_string(), - "GR".to_string(), - "DE".to_string(), - "IE".to_string(), - "IT".to_string(), - "NL".to_string(), - "NZ".to_string(), - "NO".to_string(), - "PL".to_string(), - "PT".to_string(), - "RO".to_string(), - "ES".to_string(), - "SE".to_string(), - "CH".to_string(), - "GB".to_string(), - "US".to_string(), + options: vec![ + "ALL".to_string(), ] }, value: None, @@ -10458,7 +10262,7 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::from([( + common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), @@ -10466,35 +10270,7 @@ impl Default for super::settings::RequiredFields { field_type: enums::FieldType::UserBillingName, value: None, } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "owner_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "payment_method_data.bank_debit.ach.account_number".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.ach.account_number".to_string(), - display_name: "bank_account_number".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ), - ( - "payment_method_data.bank_debit.ach.routing_number".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.ach.routing_number".to_string(), - display_name: "bank_routing_number".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ) - ]), + )]), }), ( enums::Connector::Adyen, @@ -10558,35 +10334,7 @@ impl Default for super::settings::RequiredFields { field_type: enums::FieldType::UserBillingName, value: None, } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "owner_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "payment_method_data.bank_debit.sepa.iban".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.iban".to_string(), - display_name: "bank_account_number".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ), - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ) - ]), + )]), } ), ( @@ -10642,157 +10390,7 @@ impl Default for super::settings::RequiredFields { field_type: enums::FieldType::UserBillingName, value: None, } - ), - ( - "payment_method_data.bank_debit.bacs.account_number".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.account_number".to_string(), - display_name: "bank_account_number".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ), - ( - "payment_method_data.bank_debit.bacs.sort_code".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.sort_code".to_string(), - display_name: "bank_sort_code".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ), - ( - "billing.address.country".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserAddressCountry { - options: vec!["UK".to_string()], - }, - value: None, - }, - ), - ( - "billing.address.zip".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, - value: None, - }, - ), - ( - "billing.address.line1".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.line1".to_string(), - display_name: "line1".to_string(), - field_type: enums::FieldType::UserAddressLine1, - value: None, - }, - ) - ]), - } - ), - ( - enums::Connector::Adyen, - RequiredFieldFinal { - mandate: HashMap::new(), - non_mandate: HashMap::new(), - common: HashMap::from([ ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.first_name".to_string(), - display_name: "owner_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - }), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "owner_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "payment_method_data.bank_debit.bacs.account_number".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.account_number".to_string(), - display_name: "bank_account_number".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ), - ( - "payment_method_data.bank_debit.bacs.sort_code".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.sort_code".to_string(), - display_name: "bank_sort_code".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ) - ]), - }) - ]), - }, - ), - ( - enums::PaymentMethodType::Becs, - ConnectorFields { - fields: HashMap::from([ - ( - enums::Connector::Stripe, - RequiredFieldFinal { - mandate: HashMap::new(), - non_mandate: HashMap::new(), - common: HashMap::from([ ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.first_name".to_string(), - display_name: "billing_first_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "owner_name".to_string(), - field_type: enums::FieldType::UserBillingName, - value: None, - } - ), - ( - "payment_method_data.bank_debit.becs.account_number".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.becs.account_number".to_string(), - display_name: "bank_account_number".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ), - ( - "payment_method_data.bank_debit.becs.bsb_number".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.becs.bsb_number".to_string(), - display_name: "bsb_number".to_string(), - field_type: enums::FieldType::Text, - value: None, - } - ), - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ) - ]), + )]), } ), ( @@ -10839,8 +10437,7 @@ impl Default for super::settings::RequiredFields { }) ]), }, - ), - ]))), + )]))), ( enums::PaymentMethod::BankTransfer, PaymentMethodType(HashMap::from([( @@ -10851,17 +10448,7 @@ impl Default for super::settings::RequiredFields { enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::from([ - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ) - ]), + non_mandate: HashMap::new(), common: HashMap::new(), } ), @@ -10885,17 +10472,7 @@ impl Default for super::settings::RequiredFields { }, value: None, } - ), - ( - "billing.address.city".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.city".to_string(), - display_name: "city".to_string(), - field_type: enums::FieldType::UserAddressCity, - value: None, - }, - ), - ]), + )]), common: HashMap::new(), } ), @@ -10908,17 +10485,7 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::from([ - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ) - ]) + common: HashMap::new(), } ), ])}), @@ -10959,24 +10526,6 @@ impl Default for super::settings::RequiredFields { value: None, } ), - ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.first_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - value: None, - } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - value: None, - } - ), ] ), } @@ -11291,140 +10840,6 @@ impl Default for super::settings::RequiredFields { ]), }, ), - ( - enums::PaymentMethodType::Sepa, - ConnectorFields { - fields: HashMap::from([ - ( - enums::Connector::Stripe, - RequiredFieldFinal { - mandate : HashMap::new(), - non_mandate : HashMap::new(), - common : HashMap::from([ - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ), - ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.first_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - value: None, - } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - value: None, - } - ), - ( - "billing.address.country".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.country".to_string(), - display_name: "country".to_string(), - field_type: enums::FieldType::UserAddressCountry { - options: vec![ - "AT".to_string(), - "BE".to_string(), - "BG".to_string(), - "HR".to_string(), - "CY".to_string(), - "CZ".to_string(), - "DK".to_string(), - "EE".to_string(), - "FI".to_string(), - "FR".to_string(), - "DE".to_string(), - "GR".to_string(), - "HU".to_string(), - "IE".to_string(), - "IT".to_string(), - "LV".to_string(), - "LT".to_string(), - "LU".to_string(), - "MT".to_string(), - "NL".to_string(), - "PL".to_string(), - "PT".to_string(), - "RO".to_string(), - "SI".to_string(), - "SK".to_string(), - "ES".to_string(), - "SE".to_string(), - "AD".to_string(), - "IS".to_string(), - "LI".to_string(), - "MC".to_string(), - "NO".to_string(), - "SM".to_string(), - "CH".to_string(), - "GB".to_string(), - "VA".to_string(), - ], - }, - value: None, - }, - ), - ]), - } - ) - ]), - }, - ), - ( - enums::PaymentMethodType::Bacs, - ConnectorFields { - fields: HashMap::from([ - ( - enums::Connector::Stripe, - RequiredFieldFinal { - mandate : HashMap::new(), - non_mandate : HashMap::new(), - common : HashMap::from([ - ( - "billing.email".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.email".to_string(), - display_name: "email".to_string(), - field_type: enums::FieldType::UserEmailAddress, - value: None, - } - ), - ( - "billing.address.first_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.first_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - value: None, - } - ), - ( - "billing.address.last_name".to_string(), - RequiredFieldInfo { - required_field: "payment_method_data.billing.address.last_name".to_string(), - display_name: "card_holder_name".to_string(), - field_type: enums::FieldType::UserFullName, - value: None, - } - ) - ]), - } - ) - ]), - }, - ), ]))), ( enums::PaymentMethod::GiftCard, @@ -11472,7 +10887,7 @@ impl Default for super::settings::RequiredFields { value: None, } ), - ]), + ]), common: HashMap::new(), } ), diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 9239a94ad82..2375dd578b3 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -17,8 +17,8 @@ use crate::connector::utils::PayoutsData; use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSyncRequestData, - RecurringMandateData, RouterData, + PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, + PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData, }, consts, core::errors, @@ -83,7 +83,7 @@ pub struct CybersourceZeroMandateRequest { impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { - let email = item.get_billing_email()?; + let email = item.request.get_email()?; let bill_to = build_bill_to(item.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { @@ -1033,7 +1033,7 @@ impl domain::Card, ), ) -> Result<Self, Self::Error> { - let email = item.router_data.get_billing_email()?; + let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); @@ -1113,7 +1113,7 @@ impl domain::Card, ), ) -> Result<Self, Self::Error> { - let email = item.router_data.get_billing_email()?; + let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); @@ -1196,7 +1196,7 @@ impl domain::ApplePayWalletData, ), ) -> Result<Self, Self::Error> { - let email = item.router_data.get_billing_email()?; + let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); let processing_information = ProcessingInformation::try_from(( @@ -1265,7 +1265,7 @@ impl domain::GooglePayWalletData, ), ) -> Result<Self, Self::Error> { - let email = item.router_data.get_billing_email()?; + let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); @@ -1327,7 +1327,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> } }, None => { - let email = item.router_data.get_billing_email()?; + let email = item.router_data.request.get_email()?; let bill_to = build_bill_to( item.router_data.get_optional_billing(), email, @@ -1479,10 +1479,10 @@ impl let payment_instrument = CybersoucrePaymentInstrument { id: connector_mandate_id.into(), }; - let bill_to = item - .router_data - .get_optional_billing_email() - .and_then(|email| build_bill_to(item.router_data.get_optional_billing(), email).ok()); + let bill_to = + item.router_data.request.get_email().ok().and_then(|email| { + build_bill_to(item.router_data.get_optional_billing(), email).ok() + }); let order_information = OrderInformationWithBill::from((item, bill_to)); let payment_information = PaymentInformation::MandatePayment(Box::new(MandatePaymentInformation { @@ -2310,7 +2310,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> })? .1 .to_string(); - let email = item.router_data.get_billing_email()?; + let email = item.router_data.request.get_email()?; let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill { amount_details, diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index fd2b262c7e9..24b2f2b88e9 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -150,10 +150,14 @@ pub struct ShippingAddress { name: Option<ShippingName>, } -impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ShippingAddress { - fn from(item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>) -> Self { - Self { - address: get_address_info(item.router_data.get_optional_shipping()), +impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ShippingAddress { + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: &PaypalRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + address: get_address_info(item.router_data.get_optional_shipping())?, name: Some(ShippingName { full_name: item .router_data @@ -161,7 +165,7 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ShippingAd .and_then(|inner_data| inner_data.address.as_ref()) .and_then(|inner_data| inner_data.first_name.clone()), }), - } + }) } } @@ -248,17 +252,20 @@ pub struct PaypalPaymentsRequest { payment_source: Option<PaymentSourceItem>, } -fn get_address_info(payment_address: Option<&api_models::payments::Address>) -> Option<Address> { +fn get_address_info( + payment_address: Option<&api_models::payments::Address>, +) -> Result<Option<Address>, error_stack::Report<errors::ConnectorError>> { let address = payment_address.and_then(|payment_address| payment_address.address.as_ref()); - match address { - Some(address) => address.get_optional_country().map(|country| Address { - country_code: country.to_owned(), + let address = match address { + Some(address) => Some(Address { + country_code: address.get_country()?.to_owned(), address_line_1: address.line1.clone(), postal_code: address.zip.clone(), admin_area_2: address.city.clone(), }), None => None, - } + }; + Ok(address) } fn get_payment_source( item: &types::PaymentsAuthorizeRouterData, @@ -272,7 +279,7 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), - shipping_preference: if item.get_optional_shipping_country().is_some() { + shipping_preference: if item.get_optional_shipping().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile @@ -288,7 +295,7 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), - shipping_preference: if item.get_optional_shipping_country().is_some() { + shipping_preference: if item.get_optional_shipping().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile @@ -304,7 +311,7 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), - shipping_preference: if item.get_optional_shipping_country().is_some() { + shipping_preference: if item.get_optional_shipping().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile @@ -321,7 +328,7 @@ fn get_payment_source( experience_context: ContextStruct { return_url: item.request.complete_authorize_url.clone(), cancel_url: item.request.complete_authorize_url.clone(), - shipping_preference: if item.get_optional_shipping_country().is_some() { + shipping_preference: if item.get_optional_shipping().is_some() { ShippingPreference::SetProvidedAddress } else { ShippingPreference::GetFromFile @@ -385,7 +392,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP let connector_request_reference_id = item.router_data.connector_request_reference_id.clone(); - let shipping_address = ShippingAddress::from(item); + let shipping_address = ShippingAddress::try_from(item)?; let item_details = vec![ItemDetails::from(item)]; let purchase_units = vec![PurchaseUnitRequest { @@ -413,7 +420,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP }; let payment_source = Some(PaymentSourceItem::Card(CardRequest { - billing_address: get_address_info(item.router_data.get_optional_billing()), + billing_address: get_address_info(item.router_data.get_optional_billing())?, expiry, name: item .router_data @@ -439,7 +446,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP cancel_url: item.router_data.request.complete_authorize_url.clone(), shipping_preference: if item .router_data - .get_optional_shipping_country() + .get_optional_shipping() .is_some() { ShippingPreference::SetProvidedAddress diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 2af38249e94..82ed9577a83 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -157,8 +157,6 @@ impl ConnectorValidation for Stripe { PaymentMethodDataType::ApplePay, PaymentMethodDataType::GooglePay, PaymentMethodDataType::AchBankDebit, - PaymentMethodDataType::BacsBankDebit, - PaymentMethodDataType::BecsBankDebit, PaymentMethodDataType::SepaBankDebit, PaymentMethodDataType::Sofort, PaymentMethodDataType::Ideal, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 0aed983fba5..6b26818c292 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -22,7 +22,9 @@ pub mod connect; pub use self::connect::*; use crate::{ collect_missing_value_keys, - connector::utils::{self as connector_util, ApplePay, ApplePayDecrypt, RouterData}, + connector::utils::{ + self as connector_util, ApplePay, ApplePayDecrypt, PaymentsPreProcessingData, RouterData, + }, consts, core::errors, services, @@ -1091,7 +1093,7 @@ fn get_bank_debit_data( (StripePaymentMethodType::Ach, ach_data) } domain::BankDebitData::SepaBankDebit { iban, .. } => { - let sepa_data: BankDebitData = BankDebitData::Sepa { + let sepa_data = BankDebitData::Sepa { iban: iban.to_owned(), }; (StripePaymentMethodType::Sepa, sepa_data) @@ -1592,36 +1594,35 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent let shipping_address = match item.get_optional_shipping() { Some(shipping_details) => { let shipping_address = shipping_details.address.as_ref(); - shipping_address.and_then(|shipping_detail| { - shipping_detail - .first_name - .as_ref() - .map(|first_name| StripeShippingAddress { - city: shipping_address.and_then(|a| a.city.clone()), - country: shipping_address.and_then(|a| a.country), - line1: shipping_address.and_then(|a| a.line1.clone()), - line2: shipping_address.and_then(|a| a.line2.clone()), - zip: shipping_address.and_then(|a| a.zip.clone()), - state: shipping_address.and_then(|a| a.state.clone()), - name: format!( - "{} {}", - first_name.clone().expose(), - shipping_detail - .last_name - .clone() - .expose_option() - .unwrap_or_default() - ) - .into(), - phone: shipping_details.phone.as_ref().map(|p| { + Some(StripeShippingAddress { + city: shipping_address.and_then(|a| a.city.clone()), + country: shipping_address.and_then(|a| a.country), + line1: shipping_address.and_then(|a| a.line1.clone()), + line2: shipping_address.and_then(|a| a.line2.clone()), + zip: shipping_address.and_then(|a| a.zip.clone()), + state: shipping_address.and_then(|a| a.state.clone()), + name: shipping_address + .and_then(|a| { + a.first_name.as_ref().map(|first_name| { format!( - "{}{}", - p.country_code.clone().unwrap_or_default(), - p.number.clone().expose_option().unwrap_or_default() + "{} {}", + first_name.clone().expose(), + a.last_name.clone().expose_option().unwrap_or_default() ) .into() - }), + }) }) + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "shipping_address.first_name", + })?, + phone: shipping_details.phone.as_ref().map(|p| { + format!( + "{}{}", + p.country_code.clone().unwrap_or_default(), + p.number.clone().expose_option().unwrap_or_default() + ) + .into() + }), }) } None => None, @@ -1784,60 +1785,67 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent _ => payment_data, }; - let customer_acceptance = item.request.customer_acceptance.clone().or(item + let setup_mandate_details = item .request .setup_mandate_details .as_ref() - .and_then(|mandate_details| mandate_details.customer_acceptance.clone())); - - let setup_mandate_details = customer_acceptance - .as_ref() - .map(|customer_acceptance| { - Ok::<_, error_stack::Report<errors::ConnectorError>>( - match customer_acceptance.acceptance_type { - AcceptanceType::Online => { - let online_mandate = customer_acceptance - .online - .clone() - .get_required_value("online") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "online", - })?; - StripeMandateRequest { - mandate_type: StripeMandateType::Online { - ip_address: online_mandate - .ip_address - .get_required_value("ip_address") + .and_then(|mandate_details| { + mandate_details + .customer_acceptance + .as_ref() + .map(|customer_acceptance| { + Ok::<_, error_stack::Report<errors::ConnectorError>>( + match customer_acceptance.acceptance_type { + AcceptanceType::Online => { + let online_mandate = customer_acceptance + .online + .clone() + .get_required_value("online") .change_context( errors::ConnectorError::MissingRequiredField { - field_name: "ip_address", + field_name: "online", }, - )?, - user_agent: online_mandate.user_agent, + )?; + StripeMandateRequest { + mandate_type: StripeMandateType::Online { + ip_address: online_mandate + .ip_address + .get_required_value("ip_address") + .change_context( + errors::ConnectorError::MissingRequiredField { + field_name: "ip_address", + }, + )?, + user_agent: online_mandate.user_agent, + }, + } + } + AcceptanceType::Offline => StripeMandateRequest { + mandate_type: StripeMandateType::Offline, }, - } - } - AcceptanceType::Offline => StripeMandateRequest { - mandate_type: StripeMandateType::Offline, - }, - }, - ) + }, + ) + }) }) .transpose()? - .or({ + .or_else(|| { //stripe requires us to send mandate_data while making recurring payment through saved bank debit - //check if payment is done through saved payment method - match &payment_method_types { - //check if payment method is bank debit - Some( - StripePaymentMethodType::Ach - | StripePaymentMethodType::Sepa - | StripePaymentMethodType::Becs - | StripePaymentMethodType::Bacs, - ) => Some(StripeMandateRequest { - mandate_type: StripeMandateType::Offline, - }), - _ => None, + if payment_method.is_some() { + //check if payment is done through saved payment method + match &payment_method_types { + //check if payment method is bank debit + Some( + StripePaymentMethodType::Ach + | StripePaymentMethodType::Sepa + | StripePaymentMethodType::Becs + | StripePaymentMethodType::Bacs, + ) => Some(StripeMandateRequest { + mandate_type: StripeMandateType::Offline, + }), + _ => None, + } + } else { + None } }); @@ -3244,7 +3252,7 @@ impl transfer_type: StripeCreditTransferTypes::Multibanco, currency, payment_method_data: MultibancoTransferData { - email: item.get_billing_email()?, + email: item.request.get_email()?, }, amount: Some(amount), return_url: Some(item.get_return_url()?), @@ -3254,7 +3262,7 @@ impl Ok(Self::AchBankTansfer(AchCreditTransferSourceRequest { transfer_type: StripeCreditTransferTypes::AchCreditTransfer, payment_method_data: AchTransferData { - email: item.get_billing_email()?, + email: item.request.get_email()?, }, currency, })) diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 6604058a0ae..d5c01503ed8 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1649,7 +1649,6 @@ pub trait AddressDetailsData { fn to_state_code(&self) -> Result<Secret<String>, Error>; fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error>; fn get_optional_line2(&self) -> Option<Secret<String>>; - fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2>; } impl AddressDetailsData for api::AddressDetails { @@ -1749,9 +1748,6 @@ impl AddressDetailsData for api::AddressDetails { fn get_optional_line2(&self) -> Option<Secret<String>> { self.line2.clone() } - fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2> { - self.country - } } pub trait MandateData {
refactor
revert [Stripe/Itau/Paypal/Bambora/Cybs] prevent partial submission of billing address and add required fields for all payment methods (#5745)
f4e5784f6ce57b4a205c164889242bfa1bc1fde2
2024-04-19 12:14:52
Amisha Prabhat
fix(core): fix 3DS mandates, for the connector _mandate_details to be stored in the payment_methods table (#4323)
false
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 6e8e4e11fdd..48a6d411780 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -417,6 +417,7 @@ pub async fn get_token_pm_type_mandate_details( mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, + payment_method_id: Option<String>, ) -> RouterResult<MandateGenericData> { let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from); let ( @@ -529,15 +530,27 @@ pub async fn get_token_pm_type_mandate_details( } } } - None => ( - request.payment_token.to_owned(), - request.payment_method, - request.payment_method_type, - mandate_data, - None, - None, - None, - ), + None => { + let payment_method_info = payment_method_id + .async_map(|payment_method_id| async move { + state + .store + .find_payment_method(&payment_method_id, merchant_account.storage_scheme) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound) + }) + .await + .transpose()?; + ( + request.payment_token.to_owned(), + request.payment_method, + request.payment_method_type, + mandate_data, + None, + None, + payment_method_info, + ) + } }; Ok(MandateGenericData { token: payment_token, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index e9e0ec36a73..89bdd0b84cc 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -119,6 +119,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_type.to_owned(), merchant_account, key_store, + payment_attempt.payment_method_id.clone(), ) .await?; let token = token.or_else(|| payment_attempt.payment_token.clone()); diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 7af7e13b9fc..de0e6604098 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -484,6 +484,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> m_mandate_type, &m_merchant_account, &m_key_store, + None, ) .await } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 99a387fc8d1..5d510f2afd4 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -134,6 +134,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_type.clone(), merchant_account, merchant_key_store, + None, ) .await?; diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 9bb8119d40c..b96cf483236 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -17,7 +17,7 @@ use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, mandate, - payment_methods::PaymentMethodRetrieve, + payment_methods::{self, PaymentMethodRetrieve}, payments::{ self, helpers::{ @@ -886,6 +886,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .in_current_span(), ); + // When connector requires redirection for mandate creation it can update the connector mandate_id in payment_methods during Psync and CompleteAuthorize + let flow_name = core_utils::get_flow_name::<F>()?; if flow_name == "PSync" || flow_name == "CompleteAuthorize" { let connector_mandate_id = match router_data.response.clone() { @@ -904,23 +906,31 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }, Err(_) => None, }; - if let Some(ref payment_method) = payment_data.payment_method_info { - payments::tokenization::update_connector_mandate_details_in_payment_method( + if let Some(payment_method) = payment_data.payment_method_info.clone() { + let connector_mandate_details = + payments::tokenization::update_connector_mandate_details_in_payment_method( + payment_method.clone(), + payment_method.payment_method_type, + Some(payment_data.payment_attempt.amount), + payment_data.payment_attempt.currency, + payment_data.payment_attempt.merchant_connector_id.clone(), + connector_mandate_id, + )?; + payment_methods::cards::update_payment_method_connector_mandate_details( + &*state.store, payment_method.clone(), - payment_method.payment_method_type, - Some(payment_data.payment_attempt.amount), - payment_data.payment_attempt.currency, - payment_data.payment_attempt.merchant_connector_id.clone(), - connector_mandate_id, + connector_mandate_details, + storage_scheme, ) - .await?; + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment method in db")? } } - // When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize let m_db = state.clone().store; - let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); let m_router_data_merchant_id = router_data.merchant_id.clone(); + let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone(); let m_payment_data_mandate_id = payment_data .payment_attempt diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index bfd056e8f97..b201453068b 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -146,6 +146,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> mandate_type.to_owned(), merchant_account, key_store, + None, ) .await?; helpers::validate_amount_to_capture_and_capture_method(Some(&payment_attempt), request)?; diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index c6f6a23d0a2..62acfb449eb 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -282,8 +282,7 @@ where currency, connector.merchant_connector_id.clone(), connector_mandate_id.clone(), - ) - .await?; + )?; payment_methods::cards::update_payment_method_connector_mandate_details(db, pm, connector_mandate_details, merchant_account.storage_scheme).await.change_context( errors::ApiErrorResponse::InternalServerError, @@ -373,8 +372,7 @@ where currency, connector.merchant_connector_id.clone(), connector_mandate_id.clone(), - ) - .await?; + )?; payment_methods::cards::update_payment_method_connector_mandate_details(db, pm.clone(), connector_mandate_details, merchant_account.storage_scheme).await.change_context( errors::ApiErrorResponse::InternalServerError, @@ -809,7 +807,7 @@ pub fn add_connector_mandate_details_in_payment_method( } } -pub async fn update_connector_mandate_details_in_payment_method( +pub fn update_connector_mandate_details_in_payment_method( payment_method: diesel_models::PaymentMethod, payment_method_type: Option<storage_enums::PaymentMethodType>, authorized_amount: Option<i64>, @@ -866,5 +864,6 @@ pub async fn update_connector_mandate_details_in_payment_method( .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; + Ok(connector_mandate_details) }
fix
fix 3DS mandates, for the connector _mandate_details to be stored in the payment_methods table (#4323)
00f8ceceb92d1741b4c94ef8ad6886ff72259aed
2024-07-29 05:48:21
github-actions
chore(version): 2024.07.29.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index a10a7d9d0a6..6b72f61905d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,33 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.07.29.0 + +### Features + +- **connector:** + - [FISERV] Move connector to hyperswitch_connectors ([#5441](https://github.com/juspay/hyperswitch/pull/5441)) ([`2bee694`](https://github.com/juspay/hyperswitch/commit/2bee694d5bb7393c11817bbee26b459609f6dd8c)) + - [Bambora APAC] add mandate flow ([#5376](https://github.com/juspay/hyperswitch/pull/5376)) ([`dbfa006`](https://github.com/juspay/hyperswitch/commit/dbfa006b475736bf415588680d7fc1a16bf16891)) +- **payments:** Support sort criteria in payments list ([#5389](https://github.com/juspay/hyperswitch/pull/5389)) ([`043ea6d`](https://github.com/juspay/hyperswitch/commit/043ea6d8dc9fe8108e0b7eb8113217bc37fa488a)) + +### Bug Fixes + +- Added created at and modified at keys in PaymentAttemptResponse ([#5412](https://github.com/juspay/hyperswitch/pull/5412)) ([`9795397`](https://github.com/juspay/hyperswitch/commit/979539702190363c67045d509be04498efd9a1fa)) + +### Refactors + +- **connector:** Add amount conversion framework to placetopay ([#4988](https://github.com/juspay/hyperswitch/pull/4988)) ([`08334da`](https://github.com/juspay/hyperswitch/commit/08334dae82145e1fd699e0008fedcbd8bb7b23c7)) +- **merchant_account_v2:** Recreate id for `merchant_account` v2 ([#5439](https://github.com/juspay/hyperswitch/pull/5439)) ([`93976db`](https://github.com/juspay/hyperswitch/commit/93976db30a91b3e67d854681fb4b9db8eea7e295)) +- **opensearch:** Add Error Handling for Empty Query and Filters in Request ([#5432](https://github.com/juspay/hyperswitch/pull/5432)) ([`b60933e`](https://github.com/juspay/hyperswitch/commit/b60933e310abb4ee56355f28dfb56d9c60083f04)) + +### Miscellaneous Tasks + +- Address Rust 1.80 clippy lints ([#5447](https://github.com/juspay/hyperswitch/pull/5447)) ([`074e90c`](https://github.com/juspay/hyperswitch/commit/074e90c9f9fbc26255ed27400a6a781aa6958339)) + +**Full Changelog:** [`2024.07.26.0...2024.07.29.0`](https://github.com/juspay/hyperswitch/compare/2024.07.26.0...2024.07.29.0) + +- - - + ## 2024.07.26.0 ### Features
chore
2024.07.29.0
897250ebc3ee57392aae7e2e926d8c635ac9fc4f
2023-04-25 20:15:03
SamraatBansal
feat(connector): [Bluesnap] add GooglePay, ApplePay support (#985)
false
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 12107835b85..d091ccaa27b 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -1,10 +1,14 @@ +use base64::Engine; +use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use crate::{ connector::utils, + consts, core::errors, pii::{self, Secret}, types::{self, api, storage::enums, transformers::ForeignTryFrom}, + utils::Encode, }; #[derive(Debug, Serialize, PartialEq)] @@ -21,6 +25,7 @@ pub struct BluesnapPaymentsRequest { #[serde(rename_all = "camelCase")] pub enum PaymentMethodDetails { CreditCard(Card), + Wallet(BluesnapWallet), } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -32,6 +37,32 @@ pub struct Card { security_code: Secret<String>, } +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapWallet { + wallet_type: BluesnapWalletTypes, + encoded_payment_token: String, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapGooglePayObject { + payment_method_data: api_models::payments::GooglePayWalletData, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BluesnapApplePayObject { + token: api_models::payments::ApplePayWalletData, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum BluesnapWalletTypes { + GooglePay, + ApplePay, +} + impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { @@ -46,6 +77,36 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest { expiration_year: ccard.card_exp_year.clone(), security_code: ccard.card_cvc, })), + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + api_models::payments::WalletData::GooglePay(payment_method_data) => { + let gpay_object = Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( + &BluesnapGooglePayObject { + payment_method_data, + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::GooglePay, + encoded_payment_token: consts::BASE64_ENGINE.encode(gpay_object), + })) + } + api_models::payments::WalletData::ApplePay(payment_method_data) => { + let apple_pay_object = + Encode::<BluesnapApplePayObject>::encode_to_string_of_json( + &BluesnapApplePayObject { + token: payment_method_data, + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::ApplePay, + encoded_payment_token: consts::BASE64_ENGINE.encode(apple_pay_object), + })) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Wallets".to_string(), + )), + }, _ => Err(errors::ConnectorError::NotImplemented( "payment method".to_string(), )),
feat
[Bluesnap] add GooglePay, ApplePay support (#985)
a2c0d7f09522a105f0037de5cbd4ed602e5cfdc6
2024-07-05 15:41:30
Sampras Lopes
fix(refunds): Add aliases on refund status for backwards compatibility (#5216)
false
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 36cc0bcb11c..87b436ca922 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1574,11 +1574,16 @@ pub enum PaymentType { #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundStatus { + #[serde(alias = "Failure")] Failure, + #[serde(alias = "ManualReview")] ManualReview, #[default] + #[serde(alias = "Pending")] Pending, + #[serde(alias = "Success")] Success, + #[serde(alias = "TransactionFailure")] TransactionFailure, }
fix
Add aliases on refund status for backwards compatibility (#5216)
aca6ad1bd1f43758b22638a7a2e7e4a99b66e5ff
2024-05-30 16:22:26
Apoorv Dixit
feat(users): add support to reset totp (#4821)
false
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 0da381bd493..9db47b74dc5 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1634,7 +1634,39 @@ pub async fn begin_totp( let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; let secret = totp.get_secret_base32().into(); + tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; + + Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { + secret: Some(user_api::TotpSecret { + secret, + totp_url: totp.get_url().into(), + }), + })) +} + +pub async fn reset_totp( + state: AppState, + user_token: auth::UserFromToken, +) -> UserResponse<user_api::BeginTotpResponse> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + if user_from_db.get_totp_status() != TotpStatus::Set { + return Err(UserErrors::TotpNotSetup.into()); + } + if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? + && !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await? + { + return Err(UserErrors::TwoFactorAuthRequired.into()); + } + + let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?; + let secret = totp.get_secret_base32().into(); tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?; Ok(ApplicationResponse::Json(user_api::BeginTotpResponse { diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 141e9f53af4..a7d17e602d5 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1218,6 +1218,7 @@ impl User { .service( web::scope("/totp") .service(web::resource("/begin").route(web::get().to(totp_begin))) + .service(web::resource("/reset").route(web::get().to(totp_reset))) .service( web::resource("/verify") .route(web::post().to(totp_verify)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 417a4360c51..b4b9658a7e0 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -214,6 +214,7 @@ impl From<Flow> for ApiIdentifier { | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails | Flow::TotpBegin + | Flow::TotpReset | Flow::TotpVerify | Flow::TotpUpdate | Flow::RecoveryCodeVerify diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index f22e4aac521..e5cc7e4e294 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -648,6 +648,20 @@ pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpRes .await } +pub async fn totp_reset(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::TotpReset; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user, _, _| user_core::reset_totp(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn totp_verify( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 728f2ed206e..110532f524d 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -404,6 +404,8 @@ pub enum Flow { UserFromEmail, /// Begin TOTP TotpBegin, + // Reset TOTP + TotpReset, /// Verify TOTP TotpVerify, /// Update TOTP secret
feat
add support to reset totp (#4821)
39540015fde476ad8492a9142c2c1bfda8444a27
2023-11-20 17:35:07
Sai Harsha Vardhan
feat(router): add unified_code, unified_message in payments response (#2918)
false
diff --git a/crates/api_models/src/gsm.rs b/crates/api_models/src/gsm.rs index 254981b1f8f..81798d05178 100644 --- a/crates/api_models/src/gsm.rs +++ b/crates/api_models/src/gsm.rs @@ -13,6 +13,8 @@ pub struct GsmCreateRequest { pub router_error: Option<String>, pub decision: GsmDecision, pub step_up_possible: bool, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -57,6 +59,8 @@ pub struct GsmUpdateRequest { pub router_error: Option<String>, pub decision: Option<GsmDecision>, pub step_up_possible: Option<bool>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -88,4 +92,6 @@ pub struct GsmResponse { pub router_error: Option<String>, pub decision: String, pub step_up_possible: bool, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b479f4442ba..9f4f151c222 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -391,6 +391,10 @@ pub struct PaymentAttemptResponse { /// reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, + /// error code unified across the connectors is received here if there was an error while calling connector + pub unified_code: Option<String>, + /// error message unified across the connectors is received here if there was an error while calling connector + pub unified_message: Option<String>, } #[derive( @@ -2089,6 +2093,12 @@ pub struct PaymentsResponse { #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, + /// error code unified across the connectors is received here if there was an error while calling connector + pub unified_code: Option<String>, + + /// error message unified across the connectors is received here if there was an error while calling connector + pub unified_message: Option<String>, + /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs index 88fc7b3b524..1b43177feb5 100644 --- a/crates/data_models/src/payments/payment_attempt.rs +++ b/crates/data_models/src/payments/payment_attempt.rs @@ -145,6 +145,8 @@ pub struct PaymentAttempt { pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub merchant_connector_id: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -207,6 +209,8 @@ pub struct PaymentAttemptNew { pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub merchant_connector_id: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -292,6 +296,8 @@ pub enum PaymentAttemptUpdate { updated_by: String, authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, @@ -316,6 +322,8 @@ pub enum PaymentAttemptUpdate { error_reason: Option<Option<String>>, amount_capturable: Option<i64>, updated_by: String, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, }, MultipleCaptureCountUpdate { multiple_capture_count: i16, diff --git a/crates/diesel_models/src/gsm.rs b/crates/diesel_models/src/gsm.rs index 2e824758aa5..39bd880cd6c 100644 --- a/crates/diesel_models/src/gsm.rs +++ b/crates/diesel_models/src/gsm.rs @@ -34,6 +34,8 @@ pub struct GatewayStatusMap { #[serde(with = "custom_serde::iso8601")] pub last_modified: PrimitiveDateTime, pub step_up_possible: bool, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable)] @@ -48,6 +50,8 @@ pub struct GatewayStatusMappingNew { pub router_error: Option<String>, pub decision: String, pub step_up_possible: bool, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive( @@ -71,6 +75,8 @@ pub struct GatewayStatusMapperUpdateInternal { pub router_error: Option<Option<String>>, pub decision: Option<String>, pub step_up_possible: Option<bool>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Debug)] @@ -79,6 +85,8 @@ pub struct GatewayStatusMappingUpdate { pub router_error: Option<Option<String>>, pub decision: Option<String>, pub step_up_possible: Option<bool>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { @@ -88,12 +96,16 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { status, router_error, step_up_possible, + unified_code, + unified_message, } = value; Self { status, router_error, decision, step_up_possible, + unified_code, + unified_message, ..Default::default() } } diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index cd976b9e19d..bb8f2b60bbb 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -61,6 +61,8 @@ pub struct PaymentAttempt { pub merchant_connector_id: Option<String>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Queryable, Serialize, Deserialize)] @@ -124,6 +126,8 @@ pub struct PaymentAttemptNew { pub merchant_connector_id: Option<String>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -209,6 +213,8 @@ pub enum PaymentAttemptUpdate { updated_by: String, authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, }, UnresolvedResponseUpdate { status: storage_enums::AttemptStatus, @@ -233,6 +239,8 @@ pub enum PaymentAttemptUpdate { error_reason: Option<Option<String>>, amount_capturable: Option<i64>, updated_by: String, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, }, MultipleCaptureCountUpdate { multiple_capture_count: i16, @@ -298,6 +306,8 @@ pub struct PaymentAttemptUpdateInternal { merchant_connector_id: Option<String>, authentication_data: Option<serde_json::Value>, encoded_data: Option<String>, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, } impl PaymentAttemptUpdate { @@ -352,6 +362,8 @@ impl PaymentAttemptUpdate { merchant_connector_id: pa_update.merchant_connector_id, authentication_data: pa_update.authentication_data.or(source.authentication_data), encoded_data: pa_update.encoded_data.or(source.encoded_data), + unified_code: pa_update.unified_code.unwrap_or(source.unified_code), + unified_message: pa_update.unified_message.unwrap_or(source.unified_message), ..source } } @@ -488,6 +500,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, authentication_data, encoded_data, + unified_code, + unified_message, } => Self { status: Some(status), connector, @@ -508,6 +522,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { tax_amount, authentication_data, encoded_data, + unified_code, + unified_message, ..Default::default() }, PaymentAttemptUpdate::ErrorUpdate { @@ -518,6 +534,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { error_reason, amount_capturable, updated_by, + unified_code, + unified_message, } => Self { connector, status: Some(status), @@ -527,6 +545,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { error_reason, amount_capturable, updated_by, + unified_code, + unified_message, ..Default::default() }, PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 190a123185e..ce974e409a2 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -331,6 +331,10 @@ diesel::table! { created_at -> Timestamp, last_modified -> Timestamp, step_up_possible -> Bool, + #[max_length = 255] + unified_code -> Nullable<Varchar>, + #[max_length = 1024] + unified_message -> Nullable<Varchar>, } } @@ -585,6 +589,10 @@ diesel::table! { merchant_connector_id -> Nullable<Varchar>, authentication_data -> Nullable<Json>, encoded_data -> Nullable<Text>, + #[max_length = 255] + unified_code -> Nullable<Varchar>, + #[max_length = 1024] + unified_message -> Nullable<Varchar>, } } diff --git a/crates/router/src/core/gsm.rs b/crates/router/src/core/gsm.rs index ed72275a73a..611a35d6363 100644 --- a/crates/router/src/core/gsm.rs +++ b/crates/router/src/core/gsm.rs @@ -65,6 +65,8 @@ pub async fn update_gsm_rule( status, router_error, step_up_possible, + unified_code, + unified_message, } = gsm_request; GsmInterface::update_gsm_rule( db, @@ -78,6 +80,8 @@ pub async fn update_gsm_rule( status, router_error: Some(router_error), step_up_possible, + unified_code, + unified_message, }, ) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index fb74006a067..ae729ff8fa2 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3026,6 +3026,8 @@ impl AttemptType { authentication_data: None, encoded_data: None, merchant_connector_id: None, + unified_code: None, + unified_message: None, } } @@ -3516,3 +3518,46 @@ pub fn validate_payment_link_request( } Ok(()) } + +pub async fn get_gsm_record( + state: &AppState, + error_code: Option<String>, + error_message: Option<String>, + connector_name: String, + flow: String, +) -> Option<storage::gsm::GatewayStatusMap> { + let get_gsm = || async { + state.store.find_gsm_rule( + connector_name.clone(), + flow.clone(), + "sub_flow".to_string(), + error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response + error_message.clone().unwrap_or_default(), + ) + .await + .map_err(|err| { + if err.current_context().is_db_not_found() { + logger::warn!( + "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}", + connector_name, + flow, + error_code, + error_message + ); + metrics::AUTO_RETRY_GSM_MISS_COUNT.add(&metrics::CONTEXT, 1, &[]); + } else { + metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add(&metrics::CONTEXT, 1, &[]); + }; + err.change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch decision from gsm") + }) + }; + get_gsm() + .await + .map_err(|err| { + // warn log should suffice here because we are not propagating this error + logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision"); + err + }) + .ok() +} diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 1cfc37efa44..083d1bb030d 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -16,7 +16,7 @@ use crate::{ errors::{self, RouterResult, StorageErrorExt}, mandate, payment_methods::PaymentMethodRetrieve, - payments::{types::MultipleCaptureData, PaymentData}, + payments::{helpers as payments_helpers, types::MultipleCaptureData, PaymentData}, utils as core_utils, }, routes::{metrics, AppState}, @@ -331,7 +331,16 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( (Some((multiple_capture_data, capture_update_list)), None) } None => { + let connector_name = router_data.connector.to_string(); let flow_name = core_utils::get_flow_name::<F>()?; + let option_gsm = payments_helpers::get_gsm_record( + state, + Some(err.code.clone()), + Some(err.message.clone()), + connector_name, + flow_name.clone(), + ) + .await; let status = // mark previous attempt status for technical failures in PSync flow if flow_name == "PSync" { @@ -364,6 +373,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( None }, updated_by: storage_scheme.to_string(), + unified_code: option_gsm.clone().map(|gsm| gsm.unified_code), + unified_message: option_gsm.map(|gsm| gsm.unified_message), }), ) } @@ -470,7 +481,9 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( payment_token: None, error_code: error_status.clone(), error_message: error_status.clone(), - error_reason: error_status, + error_reason: error_status.clone(), + unified_code: error_status.clone(), + unified_message: error_status, connector_response_reference_id, amount_capturable: if router_data.status.is_terminal_status() || router_data diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 788e83b05e3..3c0106206e1 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -55,7 +55,7 @@ where metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(&metrics::CONTEXT, 1, &[]); - let mut initial_gsm = get_gsm(state, &router_data).await; + let mut initial_gsm = get_gsm(state, &router_data).await?; //Check if step-up to threeDS is possible and merchant has enabled let step_up_possible = initial_gsm @@ -99,7 +99,7 @@ where // Use initial_gsm for first time alone let gsm = match initial_gsm.as_ref() { Some(gsm) => Some(gsm.clone()), - None => get_gsm(state, &router_data).await, + None => get_gsm(state, &router_data).await?, }; match get_gsm_decision(gsm) { @@ -214,46 +214,16 @@ pub async fn get_retries( pub async fn get_gsm<F, FData>( state: &app::AppState, router_data: &types::RouterData<F, FData, types::PaymentsResponseData>, -) -> Option<storage::gsm::GatewayStatusMap> { +) -> RouterResult<Option<storage::gsm::GatewayStatusMap>> { let error_response = router_data.response.as_ref().err(); let error_code = error_response.map(|err| err.code.to_owned()); let error_message = error_response.map(|err| err.message.to_owned()); - let get_gsm = || async { - let connector_name = router_data.connector.to_string(); - let flow = get_flow_name::<F>()?; - state.store.find_gsm_rule( - connector_name.clone(), - flow.clone(), - "sub_flow".to_string(), - error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response - error_message.clone().unwrap_or_default(), - ) - .await - .map_err(|err| { - if err.current_context().is_db_not_found() { - logger::warn!( - "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}", - connector_name, - flow, - error_code, - error_message - ); - metrics::AUTO_RETRY_GSM_MISS_COUNT.add(&metrics::CONTEXT, 1, &[]); - } else { - metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add(&metrics::CONTEXT, 1, &[]); - }; - err.change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to fetch decision from gsm") - }) - }; - get_gsm() - .await - .map_err(|err| { - // warn log should suffice here because we are not propagating this error - logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision"); - err - }) - .ok() + let connector_name = router_data.connector.to_string(); + let flow = get_flow_name::<F>()?; + Ok( + payments::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow) + .await, + ) } #[instrument(skip_all)] @@ -417,6 +387,8 @@ where updated_by: storage_scheme.to_string(), authentication_data, encoded_data, + unified_code: None, + unified_message: None, }, storage_scheme, ) @@ -427,17 +399,20 @@ where logger::error!("unexpected response: this response was not expected in Retry flow"); return Ok(()); } - Err(error_response) => { + Err(ref error_response) => { + let option_gsm = get_gsm(state, &router_data).await?; db.update_payment_attempt_with_attempt_id( payment_data.payment_attempt.clone(), storage::PaymentAttemptUpdate::ErrorUpdate { connector: None, - error_code: Some(Some(error_response.code)), - error_message: Some(Some(error_response.message)), + error_code: Some(Some(error_response.code.clone())), + error_message: Some(Some(error_response.message.clone())), status: storage_enums::AttemptStatus::Failure, - error_reason: Some(error_response.reason), + error_reason: Some(error_response.reason.clone()), amount_capturable: Some(0), updated_by: storage_scheme.to_string(), + unified_code: option_gsm.clone().map(|gsm| gsm.unified_code), + unified_message: option_gsm.map(|gsm| gsm.unified_message), }, storage_scheme, ) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 6c6b4ae9339..f395c023128 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -685,6 +685,8 @@ where .set_profile_id(payment_intent.profile_id) .set_attempt_count(payment_intent.attempt_count) .set_merchant_connector_id(payment_attempt.merchant_connector_id) + .set_unified_code(payment_attempt.unified_code) + .set_unified_message(payment_attempt.unified_message) .to_owned(), headers, )) @@ -745,6 +747,8 @@ where attempt_count: payment_intent.attempt_count, payment_link: payment_link_data, surcharge_details, + unified_code: payment_attempt.unified_code, + unified_message: payment_attempt.unified_message, ..Default::default() }, headers, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 2b7ea86cf51..b73ba0964fb 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -878,6 +878,8 @@ impl ForeignFrom<storage::PaymentAttempt> for api_models::payments::PaymentAttem payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, reference_id: payment_attempt.connector_response_reference_id, + unified_code: payment_attempt.unified_code, + unified_message: payment_attempt.unified_message, } } } @@ -1055,6 +1057,8 @@ impl ForeignFrom<gsm_api_types::GsmCreateRequest> for storage::GatewayStatusMapp status: value.status, router_error: value.router_error, step_up_possible: value.step_up_possible, + unified_code: value.unified_code, + unified_message: value.unified_message, } } } @@ -1071,6 +1075,8 @@ impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { status: value.status, router_error: value.router_error, step_up_possible: value.step_up_possible, + unified_code: value.unified_code, + unified_message: value.unified_message, } } } diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 00e7357d896..43e327559a0 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -136,6 +136,8 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow { )), amount_capturable: Some(0), updated_by: merchant_account.storage_scheme.to_string(), + unified_code: None, + unified_message: None, }; payment_data.payment_attempt = db diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index cb2f81daa79..fe244b10325 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -144,6 +144,8 @@ impl PaymentAttemptInterface for MockDb { authentication_data: payment_attempt.authentication_data, encoded_data: payment_attempt.encoded_data, merchant_connector_id: payment_attempt.merchant_connector_id, + unified_code: payment_attempt.unified_code, + unified_message: payment_attempt.unified_message, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 3d00e2f2bf7..cb74c981ea7 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -364,6 +364,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { authentication_data: payment_attempt.authentication_data.clone(), encoded_data: payment_attempt.encoded_data.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + unified_code: payment_attempt.unified_code.clone(), + unified_message: payment_attempt.unified_message.clone(), }; let field = format!("pa_{}", created_attempt.attempt_id); @@ -966,6 +968,8 @@ impl DataModelExt for PaymentAttempt { authentication_data: self.authentication_data, encoded_data: self.encoded_data, merchant_connector_id: self.merchant_connector_id, + unified_code: self.unified_code, + unified_message: self.unified_message, } } @@ -1018,6 +1022,8 @@ impl DataModelExt for PaymentAttempt { authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, merchant_connector_id: storage_model.merchant_connector_id, + unified_code: storage_model.unified_code, + unified_message: storage_model.unified_message, } } } @@ -1070,6 +1076,8 @@ impl DataModelExt for PaymentAttemptNew { authentication_data: self.authentication_data, encoded_data: self.encoded_data, merchant_connector_id: self.merchant_connector_id, + unified_code: self.unified_code, + unified_message: self.unified_message, } } @@ -1120,6 +1128,8 @@ impl DataModelExt for PaymentAttemptNew { authentication_data: storage_model.authentication_data, encoded_data: storage_model.encoded_data, merchant_connector_id: storage_model.merchant_connector_id, + unified_code: storage_model.unified_code, + unified_message: storage_model.unified_message, } } } @@ -1255,6 +1265,8 @@ impl DataModelExt for PaymentAttemptUpdate { tax_amount, authentication_data, encoded_data, + unified_code, + unified_message, } => DieselPaymentAttemptUpdate::ResponseUpdate { status, connector, @@ -1274,6 +1286,8 @@ impl DataModelExt for PaymentAttemptUpdate { tax_amount, authentication_data, encoded_data, + unified_code, + unified_message, }, Self::UnresolvedResponseUpdate { status, @@ -1307,6 +1321,8 @@ impl DataModelExt for PaymentAttemptUpdate { error_reason, amount_capturable, updated_by, + unified_code, + unified_message, } => DieselPaymentAttemptUpdate::ErrorUpdate { connector, status, @@ -1315,6 +1331,8 @@ impl DataModelExt for PaymentAttemptUpdate { error_reason, amount_capturable, updated_by, + unified_code, + unified_message, }, Self::MultipleCaptureCountUpdate { multiple_capture_count, @@ -1504,6 +1522,8 @@ impl DataModelExt for PaymentAttemptUpdate { tax_amount, authentication_data, encoded_data, + unified_code, + unified_message, } => Self::ResponseUpdate { status, connector, @@ -1523,6 +1543,8 @@ impl DataModelExt for PaymentAttemptUpdate { tax_amount, authentication_data, encoded_data, + unified_code, + unified_message, }, DieselPaymentAttemptUpdate::UnresolvedResponseUpdate { status, @@ -1556,6 +1578,8 @@ impl DataModelExt for PaymentAttemptUpdate { error_reason, amount_capturable, updated_by, + unified_code, + unified_message, } => Self::ErrorUpdate { connector, status, @@ -1564,6 +1588,8 @@ impl DataModelExt for PaymentAttemptUpdate { error_reason, amount_capturable, updated_by, + unified_code, + unified_message, }, DieselPaymentAttemptUpdate::MultipleCaptureCountUpdate { multiple_capture_count, diff --git a/migrations/2023-11-17-061003_add-unified-error-code-mssg-gsm/down.sql b/migrations/2023-11-17-061003_add-unified-error-code-mssg-gsm/down.sql new file mode 100644 index 00000000000..9561c8509b6 --- /dev/null +++ b/migrations/2023-11-17-061003_add-unified-error-code-mssg-gsm/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE gateway_status_map DROP COLUMN IF EXISTS unified_code; +ALTER TABLE gateway_status_map DROP COLUMN IF EXISTS unified_message; \ No newline at end of file diff --git a/migrations/2023-11-17-061003_add-unified-error-code-mssg-gsm/up.sql b/migrations/2023-11-17-061003_add-unified-error-code-mssg-gsm/up.sql new file mode 100644 index 00000000000..a4b1250a032 --- /dev/null +++ b/migrations/2023-11-17-061003_add-unified-error-code-mssg-gsm/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE gateway_status_map ADD COLUMN IF NOT EXISTS unified_code VARCHAR(255); +ALTER TABLE gateway_status_map ADD COLUMN IF NOT EXISTS unified_message VARCHAR(1024); \ No newline at end of file diff --git a/migrations/2023-11-17-084413_add-unified-error-code-mssg-payment-attempt/down.sql b/migrations/2023-11-17-084413_add-unified-error-code-mssg-payment-attempt/down.sql new file mode 100644 index 00000000000..83609093e13 --- /dev/null +++ b/migrations/2023-11-17-084413_add-unified-error-code-mssg-payment-attempt/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS unified_code; +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS unified_message; \ No newline at end of file diff --git a/migrations/2023-11-17-084413_add-unified-error-code-mssg-payment-attempt/up.sql b/migrations/2023-11-17-084413_add-unified-error-code-mssg-payment-attempt/up.sql new file mode 100644 index 00000000000..5e390d51f76 --- /dev/null +++ b/migrations/2023-11-17-084413_add-unified-error-code-mssg-payment-attempt/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS unified_code VARCHAR(255); +ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS unified_message VARCHAR(1024); \ No newline at end of file diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7d94f13dd12..65280c18714 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5934,6 +5934,14 @@ }, "step_up_possible": { "type": "boolean" + }, + "unified_code": { + "type": "string", + "nullable": true + }, + "unified_message": { + "type": "string", + "nullable": true } } }, @@ -6039,6 +6047,14 @@ }, "step_up_possible": { "type": "boolean" + }, + "unified_code": { + "type": "string", + "nullable": true + }, + "unified_message": { + "type": "string", + "nullable": true } } }, @@ -6113,6 +6129,14 @@ "step_up_possible": { "type": "boolean", "nullable": true + }, + "unified_code": { + "type": "string", + "nullable": true + }, + "unified_message": { + "type": "string", + "nullable": true } } }, @@ -8155,6 +8179,16 @@ "description": "reference to the payment at connector side", "example": "993672945374576J", "nullable": true + }, + "unified_code": { + "type": "string", + "description": "error code unified across the connectors is received here if there was an error while calling connector", + "nullable": true + }, + "unified_message": { + "type": "string", + "description": "error message unified across the connectors is received here if there was an error while calling connector", + "nullable": true } } }, @@ -10041,6 +10075,16 @@ "example": "Failed while verifying the card", "nullable": true }, + "unified_code": { + "type": "string", + "description": "error code unified across the connectors is received here if there was an error while calling connector", + "nullable": true + }, + "unified_message": { + "type": "string", + "description": "error message unified across the connectors is received here if there was an error while calling connector", + "nullable": true + }, "payment_experience": { "allOf": [ {
feat
add unified_code, unified_message in payments response (#2918)
5247a3c6512d39d5468188419cf22d362118ee7b
2025-02-05 05:56:52
github-actions
chore(version): 2025.02.05.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d3abbda850..a6cc3a151af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2025.02.05.0 + +### Features + +- **router:** Add card_discovery in payment_attempt ([#7039](https://github.com/juspay/hyperswitch/pull/7039)) ([`b9aa3ab`](https://github.com/juspay/hyperswitch/commit/b9aa3ab445e7966dad3f7c09f27e644d5628f61f)) + +### Bug Fixes + +- **connector:** + - [novalnet] Remove first name, last name as required fields for Applepay, Googlepay, Paypal ([#7152](https://github.com/juspay/hyperswitch/pull/7152)) ([`f0b443e`](https://github.com/juspay/hyperswitch/commit/f0b443eda53bfb7b56679277e6077a8d55974763)) + - Fix Paybox 3DS failing issue ([#7153](https://github.com/juspay/hyperswitch/pull/7153)) ([`a614c20`](https://github.com/juspay/hyperswitch/commit/a614c200498e6859ac5a936916bc80abeed73f12)) +- **router:** + - [Cybersource] add flag to indicate final capture ([#7085](https://github.com/juspay/hyperswitch/pull/7085)) ([`55bb284`](https://github.com/juspay/hyperswitch/commit/55bb284ba063dc84e80b4f0d83c82ec7c30ad4c5)) + - Add dynamic fields support for `samsung_pay` ([#7090](https://github.com/juspay/hyperswitch/pull/7090)) ([`e2ddcc2`](https://github.com/juspay/hyperswitch/commit/e2ddcc26b84e4ddcd69005080e19d211b1604827)) +- Invalidate surcharge cache during update ([#6907](https://github.com/juspay/hyperswitch/pull/6907)) ([`8ac1b83`](https://github.com/juspay/hyperswitch/commit/8ac1b83985dbae33afc3b53d46b85a374ff3c1e9)) + +**Full Changelog:** [`2025.02.04.0...2025.02.05.0`](https://github.com/juspay/hyperswitch/compare/2025.02.04.0...2025.02.05.0) + +- - - + ## 2025.02.04.0 ### Features
chore
2025.02.05.0
ecdac814d802cfc260a956a77a99f22c5d899ba3
2024-05-10 05:44:38
github-actions
chore(version): 2024.05.10.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index c7e012a84cb..95b343bfe37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,31 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.05.10.0 + +### Features + +- **connector:** [Payone] add connector template code ([#4469](https://github.com/juspay/hyperswitch/pull/4469)) ([`f386f42`](https://github.com/juspay/hyperswitch/commit/f386f423c0e5fac55a24756d7ee7a3ce1c20fb13)) +- **users:** + - Create API to Verify TOTP ([#4597](https://github.com/juspay/hyperswitch/pull/4597)) ([`9135423`](https://github.com/juspay/hyperswitch/commit/91354232e03a8dbd9ad9eccc8620eac321765dd7)) + - New routes to accept invite and list merchants ([#4591](https://github.com/juspay/hyperswitch/pull/4591)) ([`e70d58a`](https://github.com/juspay/hyperswitch/commit/e70d58afc941d436aae0aaa683c2e8b5db2ade33)) + +### Bug Fixes + +- **connector:** + - [iatapay]handle empty error response in case of 401 ([#4291](https://github.com/juspay/hyperswitch/pull/4291)) ([`d1404d9`](https://github.com/juspay/hyperswitch/commit/d1404d9aff2aea513a2ffd422c7e10e760b7382c)) + - [BAMBORA] Audit Fixes for Bambora ([#4604](https://github.com/juspay/hyperswitch/pull/4604)) ([`366596f`](https://github.com/juspay/hyperswitch/commit/366596f14d6c874a8e2d418a99beb90046c5b040)) +- **router:** [NETCETERA] skip sending browser_information in authentication request for app device_channel ([#4613](https://github.com/juspay/hyperswitch/pull/4613)) ([`d2a496c`](https://github.com/juspay/hyperswitch/commit/d2a496cf4ddab94efa5ad1127a94687d45bed027)) +- **users:** Fix bugs caused by the new token only flows ([#4607](https://github.com/juspay/hyperswitch/pull/4607)) ([`a0f11d7`](https://github.com/juspay/hyperswitch/commit/a0f11d79add17e0bc19d8677c90f8a35d6c99c97)) + +### Refactors + +- **billing:** Store `payment_method_data_billing` for recurring payments ([#4513](https://github.com/juspay/hyperswitch/pull/4513)) ([`55ae0fc`](https://github.com/juspay/hyperswitch/commit/55ae0fc5f704d8b35815fcd2170befb4a726ea8d)) + +**Full Changelog:** [`2024.05.09.0...2024.05.10.0`](https://github.com/juspay/hyperswitch/compare/2024.05.09.0...2024.05.10.0) + +- - - + ## 2024.05.09.0 ### Features
chore
2024.05.10.0
abcaa539eccdae86c7a68fd4ce60ab9889f9fb43
2024-11-29 15:16:16
Sandeep Kumar
fix(analytics): fix first_attempt filter value parsing for Payments (#6667)
false
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index e80f762c41b..caa112ec175 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -459,7 +459,8 @@ impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId { impl<T: AnalyticsDataSource> ToSql<T> for bool { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { - Ok(self.to_string().to_owned()) + let flag = *self; + Ok(i8::from(flag).to_string()) } }
fix
fix first_attempt filter value parsing for Payments (#6667)
cd0cf40fe29358700f92c1520475934752bb4b30
2023-05-29 19:28:38
ItsMeShashank
fix(router/webhooks): use api error response for returning errors from webhooks core (#1305)
false
diff --git a/Cargo.lock b/Cargo.lock index fd55c2dc31b..3690b937999 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3058,7 +3058,7 @@ dependencies = [ [[package]] name = "opentelemetry" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -3067,7 +3067,7 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "futures", @@ -3084,7 +3084,7 @@ dependencies = [ [[package]] name = "opentelemetry-proto" version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "futures", "futures-util", @@ -3096,7 +3096,7 @@ dependencies = [ [[package]] name = "opentelemetry_api" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "fnv", "futures-channel", @@ -3111,7 +3111,7 @@ dependencies = [ [[package]] name = "opentelemetry_sdk" version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" dependencies = [ "async-trait", "crossbeam-channel", diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 760bd84bfd0..4445ec4ce46 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -199,6 +199,8 @@ pub enum StripeErrorCode { FileNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")] FileNotAvailable, + #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")] + WebhookProcessingError, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes @@ -498,6 +500,10 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { Self::MerchantConnectorAccountDisabled } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, + errors::ApiErrorResponse::WebhookBadRequest + | errors::ApiErrorResponse::WebhookResourceNotFound + | errors::ApiErrorResponse::WebhookProcessingFailure + | errors::ApiErrorResponse::WebhookAuthenticationFailed => Self::WebhookProcessingError, } } } @@ -557,7 +563,8 @@ impl actix_web::ResponseError for StripeErrorCode { Self::RefundFailed | Self::InternalServerError | Self::MandateActive - | Self::CustomerRedacted => StatusCode::INTERNAL_SERVER_ERROR, + | Self::CustomerRedacted + | Self::WebhookProcessingError => StatusCode::INTERNAL_SERVER_ERROR, Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index ce543fcee70..35b599717ea 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -678,34 +678,59 @@ impl From<CheckoutRedirectResponseStatus> for enums::AttemptStatus { } } -pub fn is_refund_event(event_code: &CheckoutTransactionType) -> bool { +pub fn is_refund_event(event_code: &CheckoutWebhookEventType) -> bool { matches!( event_code, - CheckoutTransactionType::PaymentRefunded | CheckoutTransactionType::PaymentRefundDeclined + CheckoutWebhookEventType::PaymentRefunded | CheckoutWebhookEventType::PaymentRefundDeclined ) } -pub fn is_chargeback_event(event_code: &CheckoutTransactionType) -> bool { +pub fn is_chargeback_event(event_code: &CheckoutWebhookEventType) -> bool { matches!( event_code, - CheckoutTransactionType::DisputeReceived - | CheckoutTransactionType::DisputeExpired - | CheckoutTransactionType::DisputeAccepted - | CheckoutTransactionType::DisputeCanceled - | CheckoutTransactionType::DisputeEvidenceSubmitted - | CheckoutTransactionType::DisputeEvidenceAcknowledgedByScheme - | CheckoutTransactionType::DisputeEvidenceRequired - | CheckoutTransactionType::DisputeArbitrationLost - | CheckoutTransactionType::DisputeArbitrationWon - | CheckoutTransactionType::DisputeWon - | CheckoutTransactionType::DisputeLost + CheckoutWebhookEventType::DisputeReceived + | CheckoutWebhookEventType::DisputeExpired + | CheckoutWebhookEventType::DisputeAccepted + | CheckoutWebhookEventType::DisputeCanceled + | CheckoutWebhookEventType::DisputeEvidenceSubmitted + | CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme + | CheckoutWebhookEventType::DisputeEvidenceRequired + | CheckoutWebhookEventType::DisputeArbitrationLost + | CheckoutWebhookEventType::DisputeArbitrationWon + | CheckoutWebhookEventType::DisputeWon + | CheckoutWebhookEventType::DisputeLost ) } +#[derive(Debug, Deserialize, strum::Display, Clone)] +#[serde(rename_all = "snake_case")] +pub enum CheckoutWebhookEventType { + AuthenticationStarted, + AuthenticationApproved, + PaymentApproved, + PaymentCaptured, + PaymentDeclined, + PaymentRefunded, + PaymentRefundDeclined, + DisputeReceived, + DisputeExpired, + DisputeAccepted, + DisputeCanceled, + DisputeEvidenceSubmitted, + DisputeEvidenceAcknowledgedByScheme, + DisputeEvidenceRequired, + DisputeArbitrationLost, + DisputeArbitrationWon, + DisputeWon, + DisputeLost, + #[serde(other)] + Unknown, +} + #[derive(Debug, Deserialize)] pub struct CheckoutWebhookEventTypeBody { #[serde(rename = "type")] - pub transaction_type: CheckoutTransactionType, + pub transaction_type: CheckoutWebhookEventType, } #[derive(Debug, Deserialize)] @@ -720,7 +745,7 @@ pub struct CheckoutWebhookData { #[derive(Debug, Deserialize)] pub struct CheckoutWebhookBody { #[serde(rename = "type")] - pub transaction_type: CheckoutTransactionType, + pub transaction_type: CheckoutWebhookEventType, pub data: CheckoutWebhookData, } @@ -768,29 +793,30 @@ pub enum CheckoutTransactionType { DisputeLost, } -impl From<CheckoutTransactionType> for api::IncomingWebhookEvent { - fn from(transaction_type: CheckoutTransactionType) -> Self { +impl From<CheckoutWebhookEventType> for api::IncomingWebhookEvent { + fn from(transaction_type: CheckoutWebhookEventType) -> Self { match transaction_type { - CheckoutTransactionType::AuthenticationStarted => Self::EventNotSupported, - CheckoutTransactionType::AuthenticationApproved => Self::EventNotSupported, - CheckoutTransactionType::PaymentApproved => Self::EventNotSupported, - CheckoutTransactionType::PaymentCaptured => Self::PaymentIntentSuccess, - CheckoutTransactionType::PaymentDeclined => Self::PaymentIntentFailure, - CheckoutTransactionType::PaymentRefunded => Self::RefundSuccess, - CheckoutTransactionType::PaymentRefundDeclined => Self::RefundFailure, - CheckoutTransactionType::DisputeReceived - | CheckoutTransactionType::DisputeEvidenceRequired => Self::DisputeOpened, - CheckoutTransactionType::DisputeExpired => Self::DisputeExpired, - CheckoutTransactionType::DisputeAccepted => Self::DisputeAccepted, - CheckoutTransactionType::DisputeCanceled => Self::DisputeCancelled, - CheckoutTransactionType::DisputeEvidenceSubmitted - | CheckoutTransactionType::DisputeEvidenceAcknowledgedByScheme => { + CheckoutWebhookEventType::AuthenticationStarted => Self::EventNotSupported, + CheckoutWebhookEventType::AuthenticationApproved => Self::EventNotSupported, + CheckoutWebhookEventType::PaymentApproved => Self::EventNotSupported, + CheckoutWebhookEventType::PaymentCaptured => Self::PaymentIntentSuccess, + CheckoutWebhookEventType::PaymentDeclined => Self::PaymentIntentFailure, + CheckoutWebhookEventType::PaymentRefunded => Self::RefundSuccess, + CheckoutWebhookEventType::PaymentRefundDeclined => Self::RefundFailure, + CheckoutWebhookEventType::DisputeReceived + | CheckoutWebhookEventType::DisputeEvidenceRequired => Self::DisputeOpened, + CheckoutWebhookEventType::DisputeExpired => Self::DisputeExpired, + CheckoutWebhookEventType::DisputeAccepted => Self::DisputeAccepted, + CheckoutWebhookEventType::DisputeCanceled => Self::DisputeCancelled, + CheckoutWebhookEventType::DisputeEvidenceSubmitted + | CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme => { Self::DisputeChallenged } - CheckoutTransactionType::DisputeWon - | CheckoutTransactionType::DisputeArbitrationWon => Self::DisputeWon, - CheckoutTransactionType::DisputeLost - | CheckoutTransactionType::DisputeArbitrationLost => Self::DisputeLost, + CheckoutWebhookEventType::DisputeWon + | CheckoutWebhookEventType::DisputeArbitrationWon => Self::DisputeWon, + CheckoutWebhookEventType::DisputeLost + | CheckoutWebhookEventType::DisputeArbitrationLost => Self::DisputeLost, + CheckoutWebhookEventType::Unknown => Self::EventNotSupported, } } } diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 9529f0def14..20b585fb0ae 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -184,6 +184,14 @@ pub enum ApiErrorResponse { MissingFilePurpose, #[error(error_type = ErrorType::InvalidRequestError, code = "HE_04", message = "File content type not found / valid")] MissingFileContentType, + #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] + WebhookAuthenticationFailed, + #[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")] + WebhookResourceNotFound, + #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")] + WebhookBadRequest, + #[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")] + WebhookProcessingFailure, } #[derive(Clone)] @@ -222,12 +230,13 @@ impl actix_web::ResponseError for ApiErrorResponse { Self::Unauthorized | Self::InvalidEphemeralKey | Self::InvalidJwtToken - | Self::GenericUnauthorized { .. } => StatusCode::UNAUTHORIZED, // 401 + | Self::GenericUnauthorized { .. } + | Self::WebhookAuthenticationFailed => StatusCode::UNAUTHORIZED, // 401 Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) } - Self::InvalidRequestUrl => StatusCode::NOT_FOUND, // 404 - Self::InvalidHttpMethod => StatusCode::METHOD_NOT_ALLOWED, // 405 + Self::InvalidRequestUrl | Self::WebhookResourceNotFound => StatusCode::NOT_FOUND, // 404 + Self::InvalidHttpMethod => StatusCode::METHOD_NOT_ALLOWED, // 405 Self::MissingRequiredField { .. } | Self::InvalidDataValue { .. } | Self::InvalidCardIin @@ -235,9 +244,9 @@ impl actix_web::ResponseError for ApiErrorResponse { Self::InvalidDataFormat { .. } | Self::InvalidRequestData { .. } => { StatusCode::UNPROCESSABLE_ENTITY } // 422 - Self::RefundAmountExceedsPaymentAmount => StatusCode::BAD_REQUEST, // 400 - Self::MaximumRefundCount => StatusCode::BAD_REQUEST, // 400 - Self::PreconditionFailed { .. } => StatusCode::BAD_REQUEST, // 400 + Self::RefundAmountExceedsPaymentAmount => StatusCode::BAD_REQUEST, // 400 + Self::MaximumRefundCount => StatusCode::BAD_REQUEST, // 400 + Self::PreconditionFailed { .. } => StatusCode::BAD_REQUEST, // 400 Self::PaymentAuthorizationFailed { .. } | Self::PaymentAuthenticationFailed { .. } @@ -250,9 +259,9 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::PaymentUnexpectedState { .. } | Self::MandateValidationFailed { .. } => StatusCode::BAD_REQUEST, // 400 - Self::MandateUpdateFailed | Self::InternalServerError => { - StatusCode::INTERNAL_SERVER_ERROR - } // 500 + Self::MandateUpdateFailed + | Self::InternalServerError + | Self::WebhookProcessingFailure => StatusCode::INTERNAL_SERVER_ERROR, // 500 Self::DuplicateRefundRequest | Self::DuplicatePayment { .. } => StatusCode::BAD_REQUEST, // 400 Self::RefundNotFound | Self::CustomerNotFound @@ -275,7 +284,8 @@ impl actix_web::ResponseError for ApiErrorResponse { | Self::NotSupported { .. } | Self::FlowNotSupported { .. } | Self::ApiKeyNotFound - | Self::DisputeStatusValidationFailed { .. } => StatusCode::BAD_REQUEST, // 400 + | Self::DisputeStatusValidationFailed { .. } + | Self::WebhookBadRequest => StatusCode::BAD_REQUEST, // 400 Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod @@ -510,6 +520,18 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::MissingDisputeId => { AER::BadRequest(ApiError::new("HE", 2, "Dispute id not found in the request", None)) } + Self::WebhookAuthenticationFailed => { + AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) + } + Self::WebhookResourceNotFound => { + AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None)) + } + Self::WebhookBadRequest => { + AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None)) + } + Self::WebhookProcessingFailure => { + AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None)) + } } } } diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index f316b2af565..8db1408f77d 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -5,8 +5,9 @@ use common_utils::{crypto::SignMessage, ext_traits}; use error_stack::{report, IntoReport, ResultExt}; use masking::ExposeInterface; use router_env::{instrument, tracing}; +use utils::WebhookApiErrorSwitch; -use super::metrics; +use super::{errors::StorageErrorExt, metrics}; use crate::{ consts, core::{ @@ -32,7 +33,7 @@ pub async fn payments_incoming_webhook_flow<W: api::OutgoingWebhookType>( merchant_account: storage::MerchantAccount, webhook_details: api::IncomingWebhookDetails, source_verified: bool, -) -> CustomResult<(), errors::WebhooksFlowError> { +) -> CustomResult<(), errors::ApiErrorResponse> { let consume_or_trigger_flow = if source_verified { payments::CallConnectorAction::HandleResponse(webhook_details.resource_object) } else { @@ -56,10 +57,13 @@ pub async fn payments_incoming_webhook_flow<W: api::OutgoingWebhookType>( services::AuthFlow::Merchant, consume_or_trigger_flow, ) - .await - .change_context(errors::WebhooksFlowError::PaymentsCoreFailed)? + .await? } - _ => Err(errors::WebhooksFlowError::PaymentsCoreFailed).into_report()?, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .into_report() + .attach_printable( + "Did not get payment id as object reference id in webhook payments flow", + )?, }; match payments_response { @@ -68,13 +72,15 @@ pub async fn payments_incoming_webhook_flow<W: api::OutgoingWebhookType>( .payment_id .clone() .get_required_value("payment_id") - .change_context(errors::WebhooksFlowError::PaymentsCoreFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("payment id not received from payments core")?; let event_type: enums::EventType = payments_response .status .foreign_try_into() .into_report() - .change_context(errors::WebhooksFlowError::PaymentsCoreFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("payment event type mapping failed")?; create_event_and_trigger_outgoing_webhook::<W>( state, @@ -89,7 +95,9 @@ pub async fn payments_incoming_webhook_flow<W: api::OutgoingWebhookType>( .await?; } - _ => Err(errors::WebhooksFlowError::PaymentsCoreFailed).into_report()?, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .into_report() + .attach_printable("received non-json response from payments core")?, } Ok(()) @@ -103,7 +111,7 @@ pub async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( connector_name: &str, source_verified: bool, event_type: api_models::webhooks::IncomingWebhookEvent, -) -> CustomResult<(), errors::WebhooksFlowError> { +) -> CustomResult<(), errors::ApiErrorResponse> { let db = &*state.store; //find refund by connector refund id let refund = match webhook_details.object_reference_id { @@ -117,7 +125,7 @@ pub async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( merchant_account.storage_scheme, ) .await - .change_context(errors::WebhooksFlowError::ResourceNotFound) + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable_lazy(|| "Failed fetching the refund")?, api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::RefundId(id), @@ -128,9 +136,11 @@ pub async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( merchant_account.storage_scheme, ) .await - .change_context(errors::WebhooksFlowError::ResourceNotFound) + .change_context(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable_lazy(|| "Failed fetching the refund")?, - _ => Err(errors::WebhooksFlowError::RefundsCoreFailed).into_report()?, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .into_report() + .attach_printable("received a non-refund id when processing refund webhooks")?, }; let refund_id = refund.refund_id.to_owned(); //if source verified then update refund status else trigger refund sync @@ -141,7 +151,8 @@ pub async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( refund_status: event_type .foreign_try_into() .into_report() - .change_context(errors::WebhooksFlowError::RefundsCoreFailed)?, + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("failed refund status mapping from event type")?, }; state .store @@ -151,7 +162,7 @@ pub async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( merchant_account.storage_scheme, ) .await - .change_context(errors::WebhooksFlowError::RefundsCoreFailed) + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", @@ -169,7 +180,6 @@ pub async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( }, ) .await - .change_context(errors::WebhooksFlowError::RefundsCoreFailed) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", @@ -181,7 +191,8 @@ pub async fn refunds_incoming_webhook_flow<W: api::OutgoingWebhookType>( .refund_status .foreign_try_into() .into_report() - .change_context(errors::WebhooksFlowError::RefundsCoreFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("refund status to event type mapping failed")?; let refund_response: api_models::refunds::RefundResponse = updated_refund.foreign_into(); create_event_and_trigger_outgoing_webhook::<W>( state, @@ -201,7 +212,7 @@ pub async fn get_payment_attempt_from_object_reference_id( state: &AppState, object_reference_id: api_models::webhooks::ObjectReferenceId, merchant_account: &storage::MerchantAccount, -) -> CustomResult<storage_models::payment_attempt::PaymentAttempt, errors::WebhooksFlowError> { +) -> CustomResult<storage_models::payment_attempt::PaymentAttempt, errors::ApiErrorResponse> { let db = &*state.store; match object_reference_id { api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db @@ -211,7 +222,7 @@ pub async fn get_payment_attempt_from_object_reference_id( merchant_account.storage_scheme, ) .await - .change_context(errors::WebhooksFlowError::ResourceNotFound), + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db .find_payment_attempt_by_attempt_id_merchant_id( id, @@ -219,7 +230,7 @@ pub async fn get_payment_attempt_from_object_reference_id( merchant_account.storage_scheme, ) .await - .change_context(errors::WebhooksFlowError::ResourceNotFound), + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db .find_payment_attempt_by_preprocessing_id_merchant_id( id, @@ -227,8 +238,10 @@ pub async fn get_payment_attempt_from_object_reference_id( merchant_account.storage_scheme, ) .await - .change_context(errors::WebhooksFlowError::ResourceNotFound), - _ => Err(errors::WebhooksFlowError::ResourceNotFound).into_report(), + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound), + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .into_report() + .attach_printable("received a non-payment id for retrieving payment")?, } } @@ -240,7 +253,7 @@ pub async fn get_or_update_dispute_object( payment_attempt: &storage_models::payment_attempt::PaymentAttempt, event_type: api_models::webhooks::IncomingWebhookEvent, connector_name: &str, -) -> CustomResult<storage_models::dispute::Dispute, errors::WebhooksFlowError> { +) -> CustomResult<storage_models::dispute::Dispute, errors::ApiErrorResponse> { let db = &*state.store; match option_dispute { None => { @@ -254,7 +267,8 @@ pub async fn get_or_update_dispute_object( dispute_status: event_type .foreign_try_into() .into_report() - .change_context(errors::WebhooksFlowError::DisputeCoreFailed)?, + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("event type to dispute status mapping failed")?, payment_id: payment_attempt.payment_id.to_owned(), connector: connector_name.to_owned(), attempt_id: payment_attempt.attempt_id.to_owned(), @@ -272,7 +286,7 @@ pub async fn get_or_update_dispute_object( .store .insert_dispute(new_dispute.clone()) .await - .change_context(errors::WebhooksFlowError::WebhookEventCreationFailed) + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) } Some(dispute) => { logger::info!("Dispute Already exists, Updating the dispute details"); @@ -280,13 +294,16 @@ pub async fn get_or_update_dispute_object( let dispute_status: storage_models::enums::DisputeStatus = event_type .foreign_try_into() .into_report() - .change_context(errors::WebhooksFlowError::DisputeCoreFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("event type to dispute state conversion failure")?; crate::core::utils::validate_dispute_stage_and_dispute_status( dispute.dispute_stage.foreign_into(), dispute.dispute_status.foreign_into(), dispute_details.dispute_stage.clone(), dispute_status.foreign_into(), - )?; + ) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("dispute stage and status validation failed")?; let update_dispute = storage_models::dispute::DisputeUpdate::Update { dispute_stage: dispute_details.dispute_stage.foreign_into(), dispute_status, @@ -298,7 +315,7 @@ pub async fn get_or_update_dispute_object( }; db.update_dispute(dispute, update_dispute) .await - .change_context(errors::WebhooksFlowError::ResourceNotFound) + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) } } } @@ -312,13 +329,11 @@ pub async fn disputes_incoming_webhook_flow<W: api::OutgoingWebhookType>( connector: &(dyn api::Connector + Sync), request_details: &api::IncomingWebhookRequestDetails<'_>, event_type: api_models::webhooks::IncomingWebhookEvent, -) -> CustomResult<(), errors::WebhooksFlowError> { +) -> CustomResult<(), errors::ApiErrorResponse> { metrics::INCOMING_DISPUTE_WEBHOOK_METRIC.add(&metrics::CONTEXT, 1, &[]); if source_verified { let db = &*state.store; - let dispute_details = connector - .get_dispute_details(request_details) - .change_context(errors::WebhooksFlowError::WebhookEventObjectCreationFailed)?; + let dispute_details = connector.get_dispute_details(request_details).switch()?; let payment_attempt = get_payment_attempt_from_object_reference_id( &state, webhook_details.object_reference_id, @@ -332,7 +347,7 @@ pub async fn disputes_incoming_webhook_flow<W: api::OutgoingWebhookType>( &dispute_details.connector_dispute_id, ) .await - .change_context(errors::WebhooksFlowError::ResourceNotFound)?; + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)?; let dispute_object = get_or_update_dispute_object( state.clone(), option_dispute, @@ -348,7 +363,8 @@ pub async fn disputes_incoming_webhook_flow<W: api::OutgoingWebhookType>( .dispute_status .foreign_try_into() .into_report() - .change_context(errors::WebhooksFlowError::DisputeCoreFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("failed to map dispute status to event type")?; create_event_and_trigger_outgoing_webhook::<W>( state, merchant_account, @@ -364,7 +380,7 @@ pub async fn disputes_incoming_webhook_flow<W: api::OutgoingWebhookType>( Ok(()) } else { metrics::INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC.add(&metrics::CONTEXT, 1, &[]); - Err(errors::WebhooksFlowError::WebhookSourceVerificationFailed).into_report() + Err(errors::ApiErrorResponse::WebhookAuthenticationFailed).into_report() } } @@ -373,7 +389,7 @@ async fn bank_transfer_webhook_flow<W: api::OutgoingWebhookType>( merchant_account: storage::MerchantAccount, webhook_details: api::IncomingWebhookDetails, source_verified: bool, -) -> CustomResult<(), errors::WebhooksFlowError> { +) -> CustomResult<(), errors::ApiErrorResponse> { let response = if source_verified { let payment_attempt = get_payment_attempt_from_object_reference_id( &state, @@ -398,10 +414,9 @@ async fn bank_transfer_webhook_flow<W: api::OutgoingWebhookType>( payments::CallConnectorAction::Trigger, ) .await - .change_context(errors::WebhooksFlowError::PaymentsCoreFailed) } else { Err(report!( - errors::WebhooksFlowError::WebhookSourceVerificationFailed + errors::ApiErrorResponse::WebhookAuthenticationFailed )) }; @@ -411,13 +426,15 @@ async fn bank_transfer_webhook_flow<W: api::OutgoingWebhookType>( .payment_id .clone() .get_required_value("payment_id") - .change_context(errors::WebhooksFlowError::PaymentsCoreFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("did not receive payment id from payments core response")?; let event_type: enums::EventType = payments_response .status .foreign_try_into() .into_report() - .change_context(errors::WebhooksFlowError::PaymentsCoreFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("error mapping payments response status to event type")?; create_event_and_trigger_outgoing_webhook::<W>( state, @@ -432,7 +449,9 @@ async fn bank_transfer_webhook_flow<W: api::OutgoingWebhookType>( .await?; } - _ => Err(errors::WebhooksFlowError::PaymentsCoreFailed).into_report()?, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .into_report() + .attach_printable("received non-json response from payments core")?, } Ok(()) @@ -449,7 +468,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: api::OutgoingWebhookTy primary_object_id: String, primary_object_type: enums::EventObjectType, content: api::OutgoingWebhookContent, -) -> CustomResult<(), errors::WebhooksFlowError> { +) -> CustomResult<(), errors::ApiErrorResponse> { let new_event = storage::EventNew { event_id: generate_id(consts::ID_LENGTH, "evt"), event_type, @@ -464,12 +483,14 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: api::OutgoingWebhookTy .store .insert_event(new_event) .await - .change_context(errors::WebhooksFlowError::WebhookEventCreationFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("event insertion failure")?; if state.conf.webhooks.outgoing_enabled { let arbiter = actix::Arbiter::try_current() - .ok_or(errors::WebhooksFlowError::ForkFlowFailed) - .into_report()?; + .ok_or(errors::ApiErrorResponse::WebhookProcessingFailure) + .into_report() + .attach_printable("arbiter retrieval failure")?; let outgoing_webhook = api::OutgoingWebhook { merchant_id: merchant_account.merchant_id.clone(), @@ -481,7 +502,8 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: api::OutgoingWebhookTy let webhook_signature_payload = ext_traits::Encode::<serde_json::Value>::encode_to_string_of_json(&outgoing_webhook) - .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)?; + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("failed encoding outgoing webhook payload")?; let outgoing_webhooks_signature = merchant_account .payment_response_hash_key @@ -494,7 +516,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: api::OutgoingWebhookTy ) }) .transpose() - .change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("Failed to sign the message")? .map(hex::encode); @@ -625,7 +647,7 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( &merchant_account.merchant_id, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("There was an error in incoming webhook body decoding")?; request_details.body = &decoded_body; @@ -646,7 +668,8 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( logger::info!(process_webhook=?process_webhook_further); logger::info!(event_type=?event_type); - if process_webhook_further { + let flow_type: api::WebhookFlow = event_type.to_owned().into(); + if process_webhook_further && !matches!(flow_type, api::WebhookFlow::ReturnResponse) { let source_verified = connector .verify_webhook_source( &*state.store, @@ -654,17 +677,17 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( &merchant_account.merchant_id, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("There was an issue in incoming webhook source verification")?; let object_ref_id = connector .get_webhook_object_reference_id(&request_details) - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Could not find object reference id in incoming webhook body")?; let event_object = connector .get_webhook_resource_object(&request_details) - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Could not find resource object in incoming webhook body")?; let webhook_details = api::IncomingWebhookDetails { @@ -676,7 +699,6 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( )?, }; - let flow_type: api::WebhookFlow = event_type.to_owned().into(); match flow_type { api::WebhookFlow::Payment => payments_incoming_webhook_flow::<W>( state.clone(), @@ -685,7 +707,6 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( source_verified, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Incoming webhook flow for payments failed")?, api::WebhookFlow::Refund => refunds_incoming_webhook_flow::<W>( @@ -697,7 +718,6 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( event_type, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Incoming webhook flow for refunds failed")?, api::WebhookFlow::Dispute => disputes_incoming_webhook_flow::<W>( @@ -710,7 +730,6 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( event_type, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Incoming webhook flow for disputes failed")?, api::WebhookFlow::BankTransfer => bank_transfer_webhook_flow::<W>( @@ -720,7 +739,6 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( source_verified, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Incoming bank-transfer webhook flow failed")?, api::WebhookFlow::ReturnResponse => {} @@ -733,7 +751,7 @@ pub async fn webhooks_core<W: api::OutgoingWebhookType>( let response = connector .get_webhook_api_response(&request_details) - .change_context(errors::ApiErrorResponse::InternalServerError) + .switch() .attach_printable("Could not get incoming webhook api response from connector")?; Ok(response) diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 5826216b16b..bec61f7e2a9 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -1,4 +1,7 @@ +use error_stack::ResultExt; + use crate::{ + core::errors, db::{get_and_deserialize_key, StorageInterface}, types::api, }; @@ -45,3 +48,30 @@ pub async fn lookup_webhook_event( } } } + +pub trait WebhookApiErrorSwitch<T> { + fn switch(self) -> errors::RouterResult<T>; +} + +impl<T> WebhookApiErrorSwitch<T> for errors::CustomResult<T, errors::ConnectorError> { + fn switch(self) -> errors::RouterResult<T> { + match self { + Ok(res) => Ok(res), + Err(e) => match e.current_context() { + errors::ConnectorError::WebhookSourceVerificationFailed => { + Err(e).change_context(errors::ApiErrorResponse::WebhookAuthenticationFailed) + } + + errors::ConnectorError::WebhookSignatureNotFound + | errors::ConnectorError::WebhookReferenceIdNotFound + | errors::ConnectorError::WebhookEventTypeNotFound + | errors::ConnectorError::WebhookResourceObjectNotFound + | errors::ConnectorError::WebhookBodyDecodingFailed => { + Err(e).change_context(errors::ApiErrorResponse::WebhookBadRequest) + } + + _ => Err(e).change_context(errors::ApiErrorResponse::InternalServerError), + }, + } + } +}
fix
use api error response for returning errors from webhooks core (#1305)
15418a6d0f9429a69eaa179e5f7d9d798bf505e6
2023-09-15 16:11:19
Shankar Singh C
fix(router): move `get_connector_tokenization_action_when_confirm_true` above `call_create_connector_customer_if_required` (#2167)
false
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 70c250d5335..03e56306342 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -594,15 +594,6 @@ where ) .await?; - let updated_customer = call_create_connector_customer_if_required( - state, - customer, - merchant_account, - key_store, - payment_data, - ) - .await?; - let (pd, tokenization_action) = get_connector_tokenization_action_when_confirm_true( state, operation, @@ -611,8 +602,18 @@ where &merchant_connector_account, ) .await?; + *payment_data = pd; + let updated_customer = call_create_connector_customer_if_required( + state, + customer, + merchant_account, + key_store, + payment_data, + ) + .await?; + let mut router_data = payment_data .construct_router_data( state,
fix
move `get_connector_tokenization_action_when_confirm_true` above `call_create_connector_customer_if_required` (#2167)
b8b3bfa77055648345ba827ec03e213e66539e7f
2025-03-10 05:55:06
github-actions
chore(version): 2025.03.10.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index a5b01f8274b..b977771c2b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,30 @@ All notable changes to HyperSwitch will be documented here. +- - - + +## 2025.03.10.0 + +### Features + +- **core:** + - Add bulk tokenization flows ([#7066](https://github.com/juspay/hyperswitch/pull/7066)) ([`2ff0d4f`](https://github.com/juspay/hyperswitch/commit/2ff0d4f956112ea71f4ecb2a48fd756a12578dab)) + - Add record attempt operation for revenue recovery webhooks ([#7236](https://github.com/juspay/hyperswitch/pull/7236)) ([`24aa003`](https://github.com/juspay/hyperswitch/commit/24aa00341f907e7b77df9348f62d1416cc098691)) +- **hipay:** Add Template PR ([#7360](https://github.com/juspay/hyperswitch/pull/7360)) ([`add5152`](https://github.com/juspay/hyperswitch/commit/add51526de9594f34c71809077fb2fe27ba0868d)) + +### Bug Fixes + +- **dashboard:** Added auth key to juspay threeds server ([#7457](https://github.com/juspay/hyperswitch/pull/7457)) ([`15ad6da`](https://github.com/juspay/hyperswitch/commit/15ad6da0793be4bc149ae2e92f4805735be8712a)) +- **openapi_v2:** Add missing struct in openapi v2 ([#7383](https://github.com/juspay/hyperswitch/pull/7383)) ([`3cf529c`](https://github.com/juspay/hyperswitch/commit/3cf529c4dc9eb7bf2753398f629b72d2655aae73)) + +### Miscellaneous Tasks + +- Make v1 merchant account forward compatible ([#7426](https://github.com/juspay/hyperswitch/pull/7426)) ([`b63439a`](https://github.com/juspay/hyperswitch/commit/b63439a0936c02902ae5256ec853935fecff6fca)) +- Add migrate_v2_compatible recipe in justfile ([#7415](https://github.com/juspay/hyperswitch/pull/7415)) ([`9cbe384`](https://github.com/juspay/hyperswitch/commit/9cbe38459681784d37ec2a6588a2618ae941a667)) + +**Full Changelog:** [`2025.03.07.0...2025.03.10.0`](https://github.com/juspay/hyperswitch/compare/2025.03.07.0...2025.03.10.0) + + - - - ## 2025.03.07.0
chore
2025.03.10.0
01a5e0a0c927a9b2b5ff86b5607b0ea882674c85
2023-03-27 18:53:20
Nishant Joshi
docs(rfc): add rfc template & first RFC (#806)
false
diff --git a/docs/rfcs/000-issuing-template.md b/docs/rfcs/000-issuing-template.md new file mode 100644 index 00000000000..12a694e47a1 --- /dev/null +++ b/docs/rfcs/000-issuing-template.md @@ -0,0 +1,13 @@ +## RFC 000: [Title] + +### I. Objective +A clear and concise title for the RFC + +### II. Proposal +A detailed description of the proposed changes, discussion time frame, technical details and potential drawbacks or alternative solutions that were considered + +### III. Open Questions +Any questions or concerns that are still open for discussion and debate within the community + +### IV. Additional Context / Previous Improvements +Any relevant external resources or references like slack / discord threads that support the proposal \ No newline at end of file diff --git a/docs/rfcs/000-resolution-template.md b/docs/rfcs/000-resolution-template.md new file mode 100644 index 00000000000..e0a8cdf875b --- /dev/null +++ b/docs/rfcs/000-resolution-template.md @@ -0,0 +1,13 @@ +## RFC 000: [Title] + +### I. Status +The final status of the RFC (Accepted / Rejected) + +### II. Resolution +A description of the final resolution of the RFC, including any modifications or adjustments made during the discussion and review process + +### III. Implementation +A description of how the resolution will be implemented, including any relevant future scope for the solution + +### IV. Acknowledgements +Any final thoughts or acknowledgements for the community and contributors who participated in the RFC process \ No newline at end of file diff --git a/docs/rfcs/assets/rfc-001-perf-after.png b/docs/rfcs/assets/rfc-001-perf-after.png new file mode 100644 index 00000000000..70c50adfc89 Binary files /dev/null and b/docs/rfcs/assets/rfc-001-perf-after.png differ diff --git a/docs/rfcs/assets/rfc-001-perf-before.png b/docs/rfcs/assets/rfc-001-perf-before.png new file mode 100644 index 00000000000..58bc9687f81 Binary files /dev/null and b/docs/rfcs/assets/rfc-001-perf-before.png differ diff --git a/docs/rfcs/guidelines.md b/docs/rfcs/guidelines.md new file mode 100644 index 00000000000..1a53e3ff264 --- /dev/null +++ b/docs/rfcs/guidelines.md @@ -0,0 +1,67 @@ +# Hyperswitch RFC Process + +Hyperswitch welcomes contributions from anyone in the open-source community. Although some contributions can be easily reviewed and implemented through regular GitHub pull requests, larger changes that require design decisions will require more discussion and collaboration within the community. + +To facilitate this process, Hyperswitch has adopted the RFC (Request for Comments) process from other successful open-source projects like Rust and React. The RFC process is designed to encourage community-driven change and ensure that everyone has a voice in the decision-making process, including both core and non-core contributors. + +Here are the steps involved: +1. Prepare an RFC Proposal +2. Submit Proposal +3. Complete Initial Review +4. Initiate RFC Discussion +5. Finalize Proposal +6. Complete Implementation +7. Close RFC + +**Prepare an RFC Proposal:** Anyone interested in proposing a change to Hyperswitch should first create an RFC(in the format given below) that outlines the proposed change. This document should describe the problem the proposal is trying to solve, the proposed solution, and any relevant technical details. The document should also include any potential drawbacks or alternative solutions that were considered. + +**Submit Proposal:** Once the RFC document is complete, the proposer should submit it to the Hyperswitch community for review. The proposal can be submitted either as a pull request to the RFC Documents folder or as a GitHub Issue. + +**Complete Initial Review:** After the proposal is submitted, the Hyperswitch core team would review it and provide feedback. Feedback can include suggestions for improvements, questions about the proposal, or concerns about its potential impact. + +**Initiate RFC Discussion:** If the initial review results in interest from the community, a discussion should be opened to debate the proposal. The discussion can take place on GitHub or on Hyperswitch’s Slack & Discord servers. The discussion timeframe would be one week unless specified otherwise by the proposer or the core team. + +**Finalize Proposal:** During the discussion phase, the proposer should work with the community to refine the proposal based on feedback and input. Once the proposal is deemed mature enough, a final version should be submitted for community review and acceptance. If the proposal is accepted, the proposed changes can be implemented. If the proposal is rejected, the proposer can either abandon the proposal or rework it based on community feedback and resubmit it for another round of review. + +**Complete Implementation:** Once the proposal is accepted, the proposer or a designated contributor can implement the changes to the repository. The implementation should follow the design outlined in the RFC document and adhere to any relevant coding standards and guidelines. + +**Close RFC:** After the proposal is implemented, the RFC process would be closed by marking the proposal as completed. The RFC document would be kept for future reference, and any feedback received during the process can be used to inform future RFCs. + +This RFC process for Hyperswitch is intended to encourage collaboration and communication within the community and ensure that proposed changes to the platform are thoroughly evaluated before implementation. Please note that ​​a lack of response from others is assumed to be positive indifference. + +## Templates: + +### Issuing an RFC +```text +**Title** + +**Objective** +A clear and concise title for the RFC + +**Proposal** +A detailed description of the proposed changes, discussion time frame, technical details and potential drawbacks or alternative solutions that were considered + +**Open Questions** +Any questions or concerns that are still open for discussion and debate within the community + +**Additional Context / Previous Improvements** +Any relevant external resources or references like slack / discord threads that support the proposal +``` + +### Resolving an RFC +```text +**Title** +The title of the resolved RFC + +**Status** +The final status of the RFC (Accepted / Rejected) + +**Resolution** +A description of the final resolution of the RFC, including any modifications or adjustments made during the discussion and review process + +**Implementation** +A description of how the resolution will be implemented, including any relevant future scope for the solution + +**Acknowledgements** +Any final thoughts or acknowledgements for the community and contributors who participated in the RFC process +``` \ No newline at end of file diff --git a/docs/rfcs/text/001-compile-time-perf.md b/docs/rfcs/text/001-compile-time-perf.md new file mode 100644 index 00000000000..d5eaa0dfeff --- /dev/null +++ b/docs/rfcs/text/001-compile-time-perf.md @@ -0,0 +1,41 @@ + + +## RFC 001: Hyperswitch compile time optimization + + +### I. Objective + +Optimizing the compile time of Hyperswitch while preserving (and/or improving) the runtime performance. This would ensure accessibility across machines and improve developer experience for the community + + +### II. Proposal +While the Rust compiler provides various options like zero-cost abstractions or compiler code optimizations, there is always a trade-off between compile time and runtime performance. Through this RFC, we intend to improve the compile time without losing any runtime performance. Compile time enhances developer experience by improving iteration speed and hence developer productivity. It enables machines with limited computing resources (especially machines with 4 GB RAMs) to work on Hyperswitch. Currently the target directory occupies ~6.4 GB of disk space for debug builds and checks. + +The focus of this RFC is on external dependencies and the dependency tree which has a significant impact on the compilation time. Sometimes adding redundant features to dependencies can also have a severe impact on the compilation time, one such improvement is mentioned in the Past Improvements section. Dependencies might be repeated or be present with different versions. Reduced compile time also implies faster deployment and lower cost incurred for compiling the project on a sandbox / production environment. + +Another area for optimization is code generation. Rust provides means to extend the existing functionality of the code with constructs like `monomorphization` and `proc_macros`. These patterns help the developer reduce code repetition but it comes at the cost of compile time. Adding to this, there are some data structures in the codebase which might have redundant `derive` implementations, which could also contribute to code generation, i.e. generating redundant code which isn't used. + +### III. Open Questions +* How can we reduce the depth of the crate dependency tree? +* Can we remove some of the procedural macros used, for an OOTB (out of the box) solution available? +* Are there any other features in the overall dependencies which could be removed? +* Which `derive` macros can be removed to reduce code generation? + + +### IV. Past Improvements + +Below mentioned are some of the PR's that were intended to improve the performance of the codebase: + +* [#40](http://github.com/juspay/hyperswitch/pull/40): move `serde` implementations and date-time utils to `common_utils` crate +* [#356](http://github.com/juspay/hyperswitch/pull/356): cleanup unused `ApplicationError` variants +* [#413](http://github.com/juspay/hyperswitch/pull/413): Reusing request client for significant performance boost on the connector side. +* [#753](http://github.com/juspay/hyperswitch/pull/753): Removing redundant and unnecessary logs +* [#775](http://github.com/juspay/hyperswitch/pull/775): Removing unused features from diesel to improve the compile time: + + This is an example that was mentioned in the Proposal section that illustrated the performance boost from a relatively small change. Prior to this change diesel contributed a whopping *59.17s* to the compile time, though there are crates compiling alongside diesel, for the longest of time only diesel was compiling even after all the dependencies were compiled. + + ![pre-opt](../assets/rfc-001-perf-before.png) + After removing a redundant feature flag used for diesel in various crates, the performance boost was visibly significant, the compile time taken by diesel was a measly *4.8s*. This provided a *37.65%* improvement in the overall compile time. + + ![post-opt](../assets/rfc-001-perf-after.png) + Note: these benchmarks were performed on an M1 pro chip with a ~250 Mbps connection.
docs
add rfc template & first RFC (#806)
6954de77a0fda14d87b79ec7ceee7cc8f1c491db
2023-11-22 16:34:17
Kartikeya Hegde
fix: kv logs when KeyNotSet is returned (#2928)
false
diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs index 213fb799892..5289ec4fec4 100644 --- a/crates/redis_interface/src/errors.rs +++ b/crates/redis_interface/src/errors.rs @@ -8,6 +8,8 @@ pub enum RedisError { InvalidConfiguration(String), #[error("Failed to set key value in Redis")] SetFailed, + #[error("Failed to set key value in Redis. Duplicate value")] + SetNxFailed, #[error("Failed to set key value with expiry in Redis")] SetExFailed, #[error("Failed to set expiry for key value in Redis")] diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index c45282da7f5..9339b11a9b9 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -1,6 +1,7 @@ use std::{fmt::Debug, sync::Arc}; use common_utils::errors::CustomResult; +use error_stack::IntoReport; use redis_interface::errors::RedisError; use router_derive::TryGetEnumVariant; use router_env::logger; @@ -145,8 +146,10 @@ where store .push_to_drainer_stream::<S>(sql, partition_key) .await?; + Ok(KvResult::HSetNx(result)) + } else { + Err(RedisError::SetNxFailed).into_report() } - Ok(KvResult::HSetNx(result)) } KvOperation::SetNx(value, sql) => { @@ -160,9 +163,10 @@ where store .push_to_drainer_stream::<S>(sql, partition_key) .await?; + Ok(KvResult::SetNx(result)) + } else { + Err(RedisError::SetNxFailed).into_report() } - - Ok(KvResult::SetNx(result)) } KvOperation::Get => {
fix
kv logs when KeyNotSet is returned (#2928)
aa337eee9cae96056a5ce6d8a9eb9c84f4d376fe
2025-03-13 14:48:36
Aditya Chaurasia
feat(router): add connector field to PaymentRevenueRecoveryMetadata and implement schedule_failed_payment (#7462)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index f9540fd08fc..c55ef483287 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -7473,6 +7473,15 @@ pub struct FeatureMetadata { pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } +#[cfg(feature = "v2")] +impl FeatureMetadata { + pub fn get_retry_count(&self) -> Option<u16> { + self.payment_revenue_recovery_metadata + .as_ref() + .map(|metadata| metadata.total_retry_count) + } +} + /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] @@ -8378,6 +8387,9 @@ pub struct PaymentRevenueRecoveryMetadata { /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, + /// The name of the payment connector through which the payment attempt was made. + #[schema(value_type = Connector, example = "stripe")] + pub connector: common_enums::connector_enums::Connector, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs index 64b9a66afba..294fb33c662 100644 --- a/crates/diesel_models/src/process_tracker.rs +++ b/crates/diesel_models/src/process_tracker.rs @@ -69,12 +69,14 @@ pub struct ProcessTrackerNew { } impl ProcessTrackerNew { + #[allow(clippy::too_many_arguments)] pub fn new<T>( process_tracker_id: impl Into<String>, task: impl Into<String>, runner: ProcessTrackerRunner, tag: impl IntoIterator<Item = impl Into<String>>, tracking_data: T, + retry_count: Option<i32>, schedule_time: PrimitiveDateTime, api_version: ApiVersion, ) -> StorageResult<Self> @@ -87,7 +89,7 @@ impl ProcessTrackerNew { name: Some(task.into()), tag: tag.into_iter().map(Into::into).collect(), runner: Some(runner.to_string()), - retry_count: 0, + retry_count: retry_count.unwrap_or(0), schedule_time: Some(schedule_time), rule: String::new(), tracking_data: tracking_data diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index b79974c33fd..b1fa2197034 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -159,6 +159,8 @@ pub struct PaymentRevenueRecoveryMetadata { pub payment_method_type: common_enums::enums::PaymentMethod, /// PaymentMethod Subtype pub payment_method_subtype: common_enums::enums::PaymentMethodType, + /// The name of the payment connector through which the payment attempt was made. + pub connector: common_enums::connector_enums::Connector, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index fac251d8b68..76e06ab9b43 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -274,6 +274,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven ), payment_method_type: from.payment_method_type, payment_method_subtype: from.payment_method_subtype, + connector: from.connector, } } @@ -288,6 +289,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven .convert_back(), payment_method_type: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, + connector: self.connector, } } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 36cc1c5f808..9921cee8a63 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -424,24 +424,6 @@ impl PaymentIntent { .and_then(|metadata| metadata.get_payment_method_type()) } - pub fn set_payment_connector_transmission( - &self, - feature_metadata: Option<FeatureMetadata>, - status: bool, - ) -> Option<Box<FeatureMetadata>> { - feature_metadata.map(|fm| { - let mut updated_metadata = fm; - if let Some(ref mut rrm) = updated_metadata.payment_revenue_recovery_metadata { - rrm.payment_connector_transmission = if status { - common_enums::PaymentConnectorTransmission::ConnectorCallFailed - } else { - common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded - }; - } - Box::new(updated_metadata) - }) - } - pub fn get_connector_customer_id_from_feature_metadata(&self) -> Option<String> { self.feature_metadata .as_ref() @@ -774,11 +756,13 @@ where let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata(); let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata(); - - let payment_revenue_recovery_metadata = - Some(diesel_models::types::PaymentRevenueRecoveryMetadata { + let payment_attempt_connector = self.payment_attempt.connector.clone(); + let payment_revenue_recovery_metadata = match payment_attempt_connector { + Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata { // Update retry count by one. - total_retry_count: revenue_recovery.map_or(1, |data| (data.total_retry_count + 1)), + total_retry_count: revenue_recovery + .as_ref() + .map_or(1, |data| (data.total_retry_count + 1)), // Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded. payment_connector_transmission: common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded, @@ -799,7 +783,14 @@ where }, payment_method_type: self.payment_attempt.payment_method_type, payment_method_subtype: self.payment_attempt.payment_method_subtype, - }); + connector: connector.parse().map_err(|err| { + router_env::logger::error!(?err, "Failed to parse connector string to enum"); + errors::api_error_response::ApiErrorResponse::InternalServerError + })?, + }), + None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError) + .attach_printable("Connector not found in payment attempt")?, + }; Ok(Some(FeatureMetadata { redirect_response: payment_intent_feature_metadata .as_ref() diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs index 8adf5676f97..3e1bc93d91c 100644 --- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs +++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs @@ -61,7 +61,6 @@ pub enum RecoveryAction { /// Invalid event has been received. InvalidAction, } - pub struct RecoveryPaymentIntent { pub payment_id: id_type::GlobalPaymentId, pub status: common_enums::IntentStatus, @@ -75,10 +74,11 @@ pub struct RecoveryPaymentAttempt { } impl RecoveryPaymentAttempt { - pub fn get_attempt_triggered_by(self) -> Option<common_enums::TriggeredBy> { - self.feature_metadata.and_then(|metadata| { + pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> { + self.feature_metadata.as_ref().and_then(|metadata| { metadata .revenue_recovery + .as_ref() .map(|recovery| recovery.attempt_triggered_by) }) } diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index ae17e69710a..7eb8a8091aa 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -475,12 +475,24 @@ impl ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); let status = payment_data.payment_attempt.status.is_terminal_status(); - let updated_feature_metadata = payment_data - .payment_intent - .set_payment_connector_transmission( - payment_data.payment_intent.feature_metadata.clone(), - status, - ); + let updated_feature_metadata = + payment_data + .payment_intent + .feature_metadata + .clone() + .map(|mut feature_metadata| { + if let Some(ref mut payment_revenue_recovery_metadata) = + feature_metadata.payment_revenue_recovery_metadata + { + payment_revenue_recovery_metadata.payment_connector_transmission = + if self.response.is_ok() { + common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded + } else { + common_enums::PaymentConnectorTransmission::ConnectorCallFailed + }; + } + Box::new(feature_metadata) + }); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index fc87a490b65..bb970a4956e 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -228,6 +228,7 @@ pub async fn add_api_key_expiry_task( API_KEY_EXPIRY_RUNNER, [API_KEY_EXPIRY_TAG], api_key_expiry_tracker, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 64b2b817252..5e1ef76056b 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -481,6 +481,8 @@ pub enum RevenueRecoveryError { PaymentIntentFetchFailed, #[error("Failed to fetch payment attempt")] PaymentAttemptFetchFailed, + #[error("Failed to fetch payment attempt")] + PaymentAttemptIdNotFound, #[error("Failed to get revenue recovery invoice webhook")] InvoiceWebhookProcessingFailed, #[error("Failed to get revenue recovery invoice transaction")] @@ -491,4 +493,10 @@ pub enum RevenueRecoveryError { WebhookAuthenticationFailed, #[error("Payment merchant connector account not found using account reference id")] PaymentMerchantConnectorAccountNotFound, + #[error("Failed to fetch primitive date_time")] + ScheduleTimeFetchFailed, + #[error("Failed to create process tracker")] + ProcessTrackerCreationError, + #[error("Failed to get the response from process tracker")] + ProcessTrackerResponseError, } diff --git a/crates/router/src/core/passive_churn_recovery.rs b/crates/router/src/core/passive_churn_recovery.rs index 958baeee3f9..3b4ca0d7af6 100644 --- a/crates/router/src/core/passive_churn_recovery.rs +++ b/crates/router/src/core/passive_churn_recovery.rs @@ -142,6 +142,7 @@ async fn insert_psync_pcr_task( runner, tag, psync_workflow_tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 5893fbc6853..eec47ca6255 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -493,6 +493,7 @@ pub async fn add_payment_method_status_update_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 0325acd5991..8181df8c056 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1399,6 +1399,7 @@ pub async fn add_delete_tokenized_data_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d072463020a..0ab33dedf68 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -5941,6 +5941,7 @@ pub async fn add_process_sync_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs index c029f1439e1..bdf20635dfa 100644 --- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs +++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs @@ -160,12 +160,6 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsR self.validate_status_for_operation(payment_intent.status)?; - let client_secret = header_payload - .client_secret - .as_ref() - .get_required_value("client_secret header")?; - payment_intent.validate_client_secret(client_secret)?; - let cell_id = state.conf.cell_information.id.clone(); let batch_encrypted_data = domain_types::crypto_operation( diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index f1c8d29ca61..21a560e781b 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -3092,6 +3092,7 @@ pub async fn add_external_account_addition_task( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 1057f47b4c5..b850420dfd7 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1605,6 +1605,7 @@ pub async fn add_refund_sync_task( runner, tag, refund_workflow_tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) @@ -1643,6 +1644,7 @@ pub async fn add_refund_execute_task( runner, tag, refund_workflow_tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index 595171114f7..92c29282b21 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -553,6 +553,7 @@ pub(crate) async fn add_outgoing_webhook_retry_task_to_process_tracker( runner, tag, tracking_data, + None, schedule_time, hyperswitch_domain_models::consts::API_VERSION, ) diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs index f27ee47d6aa..60e06ab0782 100644 --- a/crates/router/src/core/webhooks/recovery_incoming.rs +++ b/crates/router/src/core/webhooks/recovery_incoming.rs @@ -1,18 +1,22 @@ use api_models::{payments as api_payments, webhooks}; -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, id_type}; +use diesel_models::{process_tracker as storage, schema::process_tracker::retry_count}; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::revenue_recovery; +use hyperswitch_domain_models::{errors::api_error_response, revenue_recovery}; use hyperswitch_interfaces::webhooks as interface_webhooks; use router_env::{instrument, tracing}; +use serde_with::rust::unwrap_or_skip; use crate::{ core::{ errors::{self, CustomResult}, payments, }, - routes::{app::ReqState, SessionState}, + db::StorageInterface, + routes::{app::ReqState, metrics, SessionState}, services::{self, connector_integration_interface}, - types::{api, domain}, + types::{api, domain, storage::passive_churn_recovery as storage_churn_recovery}, + workflows::passive_churn_recovery_workflow, }; #[allow(clippy::too_many_arguments)] @@ -122,6 +126,7 @@ pub async fn recovery_incoming_webhook_flow( }; let attempt_triggered_by = payment_attempt + .as_ref() .and_then(revenue_recovery::RecoveryPaymentAttempt::get_attempt_triggered_by); let action = revenue_recovery::RecoveryAction::get_action(event_type, attempt_triggered_by); @@ -129,10 +134,21 @@ pub async fn recovery_incoming_webhook_flow( match action { revenue_recovery::RecoveryAction::CancelInvoice => todo!(), revenue_recovery::RecoveryAction::ScheduleFailedPayment => { - todo!() + Ok(RevenueRecoveryAttempt::insert_execute_pcr_task( + &*state.store, + merchant_account.get_id().to_owned(), + payment_intent, + business_profile.get_id().to_owned(), + payment_attempt.map(|attempt| attempt.attempt_id.clone()), + storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, + ) + .await + .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)?) } revenue_recovery::RecoveryAction::SuccessPaymentExternal => { - todo!() + // Need to add recovery stop flow for this scenario + router_env::logger::info!("Payment has been succeeded via external system"); + Ok(webhooks::WebhookResponseTracker::NoEffect) } revenue_recovery::RecoveryAction::PendingPayment => { router_env::logger::info!( @@ -217,8 +233,7 @@ impl RevenueRecoveryInvoice { key_store: &domain::MerchantKeyStore, ) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> { let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0); - let global_payment_id = - common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); + let global_payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); let create_intent_response = Box::pin(payments::payments_intent_core::< hyperswitch_domain_models::router_flow_types::payments::PaymentCreateIntent, @@ -264,7 +279,7 @@ impl RevenueRecoveryAttempt { merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, - payment_id: common_utils::id_type::GlobalPaymentId, + payment_id: id_type::GlobalPaymentId, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentAttempt>, errors::RevenueRecoveryError> { let attempt_response = Box::pin(payments::payments_core::< @@ -332,8 +347,8 @@ impl RevenueRecoveryAttempt { merchant_account: &domain::MerchantAccount, profile: &domain::Profile, key_store: &domain::MerchantKeyStore, - payment_id: common_utils::id_type::GlobalPaymentId, - billing_connector_account_id: &common_utils::id_type::MerchantConnectorAccountId, + payment_id: id_type::GlobalPaymentId, + billing_connector_account_id: &id_type::MerchantConnectorAccountId, payment_connector_account: Option<domain::MerchantConnectorAccount>, ) -> CustomResult<revenue_recovery::RecoveryPaymentAttempt, errors::RevenueRecoveryError> { let request_payload = self @@ -372,7 +387,7 @@ impl RevenueRecoveryAttempt { pub fn create_payment_record_request( &self, - billing_merchant_connector_account_id: &common_utils::id_type::MerchantConnectorAccountId, + billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId, payment_merchant_connector_account: Option<domain::MerchantConnectorAccount>, ) -> api_payments::PaymentsAttemptRecordRequest { let amount_details = api_payments::PaymentAttemptAmountDetails::from(&self.0); @@ -431,4 +446,80 @@ impl RevenueRecoveryAttempt { )?; Ok(payment_merchant_connector_account) } + + async fn insert_execute_pcr_task( + db: &dyn StorageInterface, + merchant_id: id_type::MerchantId, + payment_intent: revenue_recovery::RecoveryPaymentIntent, + profile_id: id_type::ProfileId, + payment_attempt_id: Option<id_type::GlobalAttemptId>, + runner: storage::ProcessTrackerRunner, + ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { + let task = "EXECUTE_WORKFLOW"; + + let payment_id = payment_intent.payment_id.clone(); + + let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr()); + + let total_retry_count = payment_intent + .feature_metadata + .and_then(|feature_metadata| feature_metadata.get_retry_count()) + .unwrap_or(0); + + let schedule_time = + passive_churn_recovery_workflow::get_schedule_time_to_retry_mit_payments( + db, + &merchant_id, + (total_retry_count + 1).into(), + ) + .await + .map_or_else( + || { + Err( + report!(errors::RevenueRecoveryError::ScheduleTimeFetchFailed) + .attach_printable("Failed to get schedule time for pcr workflow"), + ) + }, + Ok, // Simply returns `time` wrapped in `Ok` + )?; + + let payment_attempt_id = payment_attempt_id + .ok_or(report!( + errors::RevenueRecoveryError::PaymentAttemptIdNotFound + )) + .attach_printable("payment attempt id is required for pcr workflow tracking")?; + + let execute_workflow_tracking_data = storage_churn_recovery::PcrWorkflowTrackingData { + global_payment_id: payment_id.clone(), + merchant_id, + profile_id, + payment_attempt_id, + }; + + let tag = ["PCR"]; + + let process_tracker_entry = storage::ProcessTrackerNew::new( + process_tracker_id, + task, + runner, + tag, + execute_workflow_tracking_data, + Some(total_retry_count.into()), + schedule_time, + common_enums::ApiVersion::V2, + ) + .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError) + .attach_printable("Failed to construct process tracker entry")?; + + db.insert_process(process_tracker_entry) + .await + .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError) + .attach_printable("Failed to enter process_tracker_entry in DB")?; + metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ExecutePCR"))); + + Ok(webhooks::WebhookResponseTracker::Payment { + payment_id, + status: payment_intent.status, + }) + } }
feat
add connector field to PaymentRevenueRecoveryMetadata and implement schedule_failed_payment (#7462)
1261791d9f70794b3d6426ff35f4eb0fc1076be0
2023-05-31 15:59:04
Narayan Bhat
fix: customer id is not mandatory during confirm (#1317)
false
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 00dcc4a8511..ee2d4028031 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -151,10 +151,7 @@ pub async fn get_address_for_payment_request( } None => { // generate a new address here - let customer_id = customer_id - .as_deref() - .get_required_value("customer_id") - .change_context(errors::ApiErrorResponse::CustomerNotFound)?; + let customer_id = customer_id.as_deref().get_required_value("customer_id")?; let address_details = address.address.clone().unwrap_or_default(); Some( @@ -395,11 +392,12 @@ pub fn validate_request_amount_and_amount_to_capture( pub fn validate_mandate( req: impl Into<api::MandateValidationFields>, + is_confirm_operation: bool, ) -> RouterResult<Option<api::MandateTxnType>> { let req: api::MandateValidationFields = req.into(); match req.is_mandate() { Some(api::MandateTxnType::NewMandateTxn) => { - validate_new_mandate_request(req)?; + validate_new_mandate_request(req, is_confirm_operation)?; Ok(Some(api::MandateTxnType::NewMandateTxn)) } Some(api::MandateTxnType::RecurringMandateTxn) => { @@ -410,8 +408,18 @@ pub fn validate_mandate( } } -fn validate_new_mandate_request(req: api::MandateValidationFields) -> RouterResult<()> { - let _ = req.customer_id.as_ref().get_required_value("customer_id")?; +fn validate_new_mandate_request( + req: api::MandateValidationFields, + is_confirm_operation: bool, +) -> RouterResult<()> { + // We need not check for customer_id in the confirm request if it is already passed + //in create request + + fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || { + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: "`customer_id` is mandatory for mandates".into() + })) + })?; let mandate_data = req .mandate_data @@ -776,10 +784,15 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( let req = req .get_required_value("customer") .change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?; - let optional_customer = match req.customer_id.as_ref() { + + let customer_id = req + .customer_id + .or(payment_data.payment_intent.customer_id.clone()); + + let optional_customer = match customer_id { Some(customer_id) => { let customer_data = db - .find_customer_optional_by_customer_id_merchant_id(customer_id, merchant_id) + .find_customer_optional_by_customer_id_merchant_id(&customer_id, merchant_id) .await?; Some(match customer_data { Some(c) => Ok(c), diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 39448d6412c..cf7ad77a684 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -9,7 +9,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, - payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, + payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, db::StorageInterface, @@ -331,7 +331,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for CompleteAutho helpers::validate_payment_method_fields_present(request)?; - let mandate_type = helpers::validate_mandate(request)?; + let mandate_type = + helpers::validate_mandate(request, payments::is_operation_confirm(self))?; let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?; Ok(( diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 9d28f77dcc5..7dc60813ea1 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -10,7 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, - payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, + payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, db::StorageInterface, @@ -467,7 +467,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir helpers::validate_payment_method_fields_present(request)?; - let mandate_type = helpers::validate_mandate(request)?; + let mandate_type = + helpers::validate_mandate(request, payments::is_operation_confirm(self))?; let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?; Ok(( diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 6130afd0b9c..2ece098c0d7 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -434,7 +434,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?; - let mandate_type = helpers::validate_mandate(request)?; + let mandate_type = + helpers::validate_mandate(request, payments::is_operation_confirm(self))?; if request.confirm.unwrap_or(false) { helpers::validate_pm_or_token_given( diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index 7cdf9fee750..1a3406dc874 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -45,7 +45,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodVa helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id) .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let mandate_type = helpers::validate_mandate(request)?; + let mandate_type = + helpers::validate_mandate(request, payments::is_operation_confirm(self))?; let validation_id = core_utils::get_or_generate_id("validation_id", &None, "val")?; Ok(( diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index b48cc1348c4..2fbb1bd6012 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -188,7 +188,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; - // let mandate_type = validate_mandate(request)?; + let payment_id = request.payment_id.clone(); Ok(( diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index bdf381004ba..f8e206267dc 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -532,7 +532,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate helpers::validate_payment_method_fields_present(request)?; - let mandate_type = helpers::validate_mandate(request)?; + let mandate_type = helpers::validate_mandate(request, false)?; let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?; Ok((
fix
customer id is not mandatory during confirm (#1317)
fcd206b6af0e0afdb8276077c61adc53f030e471
2023-11-21 21:51:40
github-actions
chore(version): v1.86.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index bbe55818002..7d7b6770d47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,27 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.86.0 (2023-11-21) + +### Features + +- **connector:** [Prophetpay] Save card token for Refund and remove Void flow ([#2927](https://github.com/juspay/hyperswitch/pull/2927)) ([`15a255e`](https://github.com/juspay/hyperswitch/commit/15a255ea60dffad9e4cf20d642636028c27c7c00)) +- Add support for 3ds and surcharge decision through routing rules ([#2869](https://github.com/juspay/hyperswitch/pull/2869)) ([`f8618e0`](https://github.com/juspay/hyperswitch/commit/f8618e077065d94aa27d7153fc5ea6f93870bd81)) + +### Bug Fixes + +- **mca:** Change the check for `disabled` field in mca create and update ([#2938](https://github.com/juspay/hyperswitch/pull/2938)) ([`e66ccde`](https://github.com/juspay/hyperswitch/commit/e66ccde4cf6d055b7d02c5e982d2e09364845602)) +- Status goes from pending to partially captured in psync ([#2915](https://github.com/juspay/hyperswitch/pull/2915)) ([`3f3b797`](https://github.com/juspay/hyperswitch/commit/3f3b797dc65c1bc6f710b122ef00d5bcb409e600)) + +### Testing + +- **postman:** Update postman collection files ([`245e489`](https://github.com/juspay/hyperswitch/commit/245e489d13209da19d6e9af01219056eec04e897)) + +**Full Changelog:** [`v1.85.0...v1.86.0`](https://github.com/juspay/hyperswitch/compare/v1.85.0...v1.86.0) + +- - - + + ## 1.85.0 (2023-11-21) ### Features
chore
v1.86.0
3c1406787ee6b6d93505a3721da7eda7964fe7e5
2023-01-05 16:09:10
Manoj Ghorela
fix: check if saved payment method and that in request are for the same customer (#260)
false
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index d773ebc8f7d..89ef5058b2a 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -155,7 +155,7 @@ pub async fn add_card( response } else { let card_id = generate_id(consts::ID_LENGTH, "card"); - mock_add_card(db, &card_id, &card, None, None).await? + mock_add_card(db, &card_id, &card, None, None, Some(&customer_id)).await? }; if let Some(false) = response.duplicate { @@ -188,6 +188,7 @@ pub async fn mock_add_card( card: &api::CardDetail, card_cvc: Option<String>, payment_method_id: Option<String>, + customer_id: Option<&str>, ) -> errors::CustomResult<payment_methods::AddCardResponse, errors::CardVaultError> { let locker_mock_up = storage::LockerMockUpNew { card_id: card_id.to_string(), @@ -200,6 +201,7 @@ pub async fn mock_add_card( card_exp_month: card.card_exp_month.peek().to_string(), card_cvc, payment_method_id, + customer_id: customer_id.map(str::to_string), }; let response = db @@ -615,6 +617,7 @@ impl BasiliskCardSupport { &card_detail, None, Some(pm.payment_method_id.to_string()), + Some(&pm.customer_id), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -758,16 +761,9 @@ pub async fn delete_payment_method( ) -> errors::RouterResponse<api::DeletePaymentMethodResponse> { let (_, value2) = helpers::Vault::get_payment_method_data_from_locker(state, &pm.payment_method_id).await?; - let payment_method_id = value2.map_or( - Err(errors::ApiErrorResponse::PaymentMethodNotFound), - |pm_value2| { - pm_value2 - .payment_method_id - .map_or(Err(errors::ApiErrorResponse::PaymentMethodNotFound), |x| { - Ok(x) - }) - }, - )?; + let payment_method_id = value2 + .payment_method_id + .map_or(Err(errors::ApiErrorResponse::PaymentMethodNotFound), Ok)?; let pm = state .store .delete_payment_method_by_merchant_id_payment_method_id( diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0cceb937125..1d2d6bfdbef 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -92,24 +92,12 @@ where .await .change_context(errors::ApiErrorResponse::InternalServerError)?; - let (operation, payment_method_data, payment_token) = operation + let (operation, payment_method_data) = operation .to_domain()? - .make_pm_data( - state, - payment_data.payment_attempt.payment_method, - &payment_data.payment_attempt.attempt_id, - &payment_data.payment_attempt, - &payment_data.payment_method_data, - &payment_data.token, - payment_data.card_cvc.clone(), - validate_result.storage_scheme, - ) + .make_pm_data(state, &mut payment_data, validate_result.storage_scheme) .await?; payment_data.payment_method_data = payment_method_data; - if let Some(token) = payment_token { - payment_data.token = Some(token) - } let connector_details = operation .to_domain()? diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 61a33de4efd..9adbaa6b468 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -19,7 +19,6 @@ use crate::{ }, db::StorageInterface, logger, - pii::Secret, routes::AppState, scheduler::{metrics, workflows::payment_sync}, services, @@ -750,48 +749,71 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( pub async fn make_pm_data<'a, F: Clone, R>( operation: BoxedOperation<'a, F, R>, state: &'a AppState, - payment_method_type: Option<storage_enums::PaymentMethodType>, - txn_id: &str, - _payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, -) -> RouterResult<( - BoxedOperation<'a, F, R>, - Option<api::PaymentMethod>, - Option<String>, -)> { - let (payment_method, payment_token) = match (request, token) { + payment_data: &mut PaymentData<F>, +) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethod>)> { + let payment_method_type = payment_data.payment_attempt.payment_method; + let attempt_id = &payment_data.payment_attempt.attempt_id; + let request = &payment_data.payment_method_data; + let token = payment_data.token.clone(); + let card_cvc = payment_data.card_cvc.clone(); + + let payment_method = match (request, token) { (_, Some(token)) => Ok::<_, error_stack::Report<errors::ApiErrorResponse>>( if payment_method_type == Some(storage_enums::PaymentMethodType::Card) { // TODO: Handle token expiry - let (pm, _) = Vault::get_payment_method_data_from_locker(state, token).await?; - let updated_pm = match (pm.clone(), card_cvc) { + let (pm, tokenize_value2) = + Vault::get_payment_method_data_from_locker(state, &token).await?; + utils::when( + tokenize_value2 + .customer_id + .ne(&payment_data.payment_intent.customer_id), + || { + Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer payment method and customer passed in payment are not same".into() }) + }, + )?; + payment_data.token = Some(token.to_string()); + match (pm.clone(), card_cvc) { (Some(api::PaymentMethod::Card(card)), Some(card_cvc)) => { let mut updated_card = card; updated_card.card_cvc = card_cvc; - Vault::store_payment_method_data_in_locker(state, txn_id, &updated_card) - .await?; + Vault::store_payment_method_data_in_locker( + state, + &token, + &updated_card, + payment_data.payment_intent.customer_id.to_owned(), + ) + .await?; Some(api::PaymentMethod::Card(updated_card)) } (_, _) => pm, - }; - (updated_pm, Some(token.to_string())) + } } else { + utils::when(payment_method_type.is_none(), || { + Err(errors::ApiErrorResponse::MissingRequiredField { + field_name: "payment_method_type".to_owned(), + }) + })?; // TODO: Implement token flow for other payment methods - (None, Some(token.to_string())) + None }, ), (pm @ Some(api::PaymentMethod::Card(card)), _) => { - Vault::store_payment_method_data_in_locker(state, txn_id, card).await?; - Ok((pm.to_owned(), Some(txn_id.to_string()))) + Vault::store_payment_method_data_in_locker( + state, + attempt_id, + card, + payment_data.payment_intent.customer_id.to_owned(), + ) + .await?; + payment_data.token = Some(attempt_id.to_string()); + Ok(pm.to_owned()) } - (pm @ Some(api::PaymentMethod::PayLater(_)), _) => Ok((pm.to_owned(), None)), - (pm @ Some(api::PaymentMethod::Wallet(_)), _) => Ok((pm.to_owned(), None)), - _ => Ok((None, None)), + (pm @ Some(api::PaymentMethod::PayLater(_)), _) => Ok(pm.to_owned()), + (pm @ Some(api::PaymentMethod::Wallet(_)), _) => Ok(pm.to_owned()), + _ => Ok(None), }?; - Ok((operation, payment_method, payment_token)) + Ok((operation, payment_method)) } pub struct Vault {} @@ -802,7 +824,7 @@ impl Vault { pub async fn get_payment_method_data_from_locker( state: &AppState, lookup_key: &str, - ) -> RouterResult<(Option<api::PaymentMethod>, Option<api::TokenizedCardValue2>)> { + ) -> RouterResult<(Option<api::PaymentMethod>, api::TokenizedCardValue2)> { let (resp, card_cvc) = cards::mock_get_card(&*state.store, lookup_key) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; @@ -831,10 +853,10 @@ impl Vault { card_security_code: None, card_fingerprint: None, external_id: None, - customer_id: None, + customer_id: card.customer_id, payment_method_id: Some(card.card_id), }; - Ok((Some(pm), Some(value2))) + Ok((Some(pm), value2)) } #[instrument(skip_all)] @@ -842,6 +864,7 @@ impl Vault { state: &AppState, txn_id: &str, card: &api::CCard, + customer_id: Option<String>, ) -> RouterResult<String> { let card_detail = api::CardDetail { card_number: card.card_number.clone(), @@ -856,6 +879,7 @@ impl Vault { &card_detail, Some(card.card_cvc.peek().clone()), None, + customer_id.as_deref(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -887,7 +911,7 @@ impl Vault { pub async fn get_payment_method_data_from_locker( state: &AppState, lookup_key: &str, - ) -> RouterResult<(Option<api::PaymentMethod>, Option<api::TokenizedCardValue2>)> { + ) -> RouterResult<(Option<api::PaymentMethod>, api::TokenizedCardValue2)> { let de_tokenize = cards::get_tokenized_data(state, lookup_key, true).await?; let value1: api::TokenizedCardValue1 = de_tokenize .value1 @@ -907,7 +931,7 @@ impl Vault { card_holder_name: value1.name_on_card.unwrap_or_default().into(), card_cvc: value2.card_security_code.clone().unwrap_or_default().into(), }); - Ok((Some(card), Some(value2))) + Ok((Some(card), value2)) } #[instrument(skip_all)] @@ -915,6 +939,7 @@ impl Vault { state: &AppState, txn_id: &str, card: &api::CCard, + customer_id: Option<String>, ) -> RouterResult<String> { let value1 = transformers::mk_card_value1( card.card_number.peek().clone(), @@ -931,7 +956,7 @@ impl Vault { Some(card.card_cvc.peek().clone()), None, None, - None, + customer_id, None, ) .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 2daa0993171..5d127c205ac 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -24,7 +24,6 @@ use super::{helpers, CustomerDetails, PaymentData}; use crate::{ core::errors::{self, CustomResult, RouterResult}, db::StorageInterface, - pii::Secret, routes::AppState, types::{ self, @@ -111,18 +110,9 @@ pub trait Domain<F: Clone, R>: Send + Sync { async fn make_pm_data<'a>( &'a self, state: &'a AppState, - _payment_method: Option<enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, storage_scheme: enums::MerchantStorageScheme, - ) -> RouterResult<( - BoxedOperation<'a, F, R>, - Option<api::PaymentMethod>, - Option<String>, - )>; + ) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethod>)>; async fn add_task_to_process_tracker<'a>( &'a self, @@ -212,29 +202,13 @@ where async fn make_pm_data<'a>( &'a self, state: &'a AppState, - payment_method: Option<enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_method, - txn_id, - payment_attempt, - request, - token, - card_cvc, - ) - .await + helpers::make_pm_data(Box::new(self), state, payment_data).await } } @@ -272,19 +246,13 @@ where async fn make_pm_data<'a>( &'a self, _state: &'a AppState, - _payment_method: Option<enums::PaymentMethodType>, - _txn_id: &str, - _payment_attempt: &storage::PaymentAttempt, - _request: &Option<api::PaymentMethod>, - _token: &Option<String>, - _card_cvc: Option<Secret<String>>, + _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - Ok((Box::new(self), None, None)) + Ok((Box::new(self), None)) } async fn get_connector<'a>( @@ -332,19 +300,13 @@ where async fn make_pm_data<'a>( &'a self, _state: &'a AppState, - _payment_method: Option<enums::PaymentMethodType>, - _txn_id: &str, - _payment_attempt: &storage::PaymentAttempt, - _request: &Option<api::PaymentMethod>, - _token: &Option<String>, - _card_cvc: Option<Secret<String>>, + _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - Ok((Box::new(self), None, None)) + Ok((Box::new(self), None)) } async fn get_connector<'a>( diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index d1176c97e09..af0c1cc3303 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -2,7 +2,6 @@ use std::marker::PhantomData; use async_trait::async_trait; use error_stack::{report, ResultExt}; -use masking::Secret; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -209,37 +208,22 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm { async fn make_pm_data<'a>( &'a self, state: &'a AppState, - payment_method: Option<enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - let (op, payment_method_data, payment_token) = helpers::make_pm_data( - Box::new(self), - state, - payment_method, - txn_id, - payment_attempt, - request, - token, - card_cvc, - ) - .await?; + let (op, payment_method_data) = + helpers::make_pm_data(Box::new(self), state, payment_data).await?; - if payment_method != Some(enums::PaymentMethodType::Paypal) { + if payment_data.payment_attempt.payment_method != Some(enums::PaymentMethodType::Paypal) { utils::when(payment_method_data.is_none(), || { Err(errors::ApiErrorResponse::PaymentMethodNotFound) })?; } - Ok((op, payment_method_data, payment_token)) + Ok((op, payment_method_data)) } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index ceb4f5df03c..eb1cf1d5339 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -3,7 +3,6 @@ use std::marker::PhantomData; use async_trait::async_trait; use common_utils::ext_traits::AsyncExt; use error_stack::ResultExt; -use masking::Secret; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use uuid::Uuid; @@ -271,29 +270,13 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate { async fn make_pm_data<'a>( &'a self, state: &'a AppState, - payment_method: Option<enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_method, - txn_id, - payment_attempt, - request, - token, - card_cvc, - ) - .await + helpers::make_pm_data(Box::new(self), state, payment_data).await } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index 5e9b510ca31..c57b499ff22 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -16,7 +16,6 @@ use crate::{ utils as core_utils, }, db::StorageInterface, - pii::Secret, routes::AppState, types::{ self, @@ -237,29 +236,13 @@ where async fn make_pm_data<'a>( &'a self, state: &'a AppState, - payment_method: Option<storage_enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::VerifyRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_method, - txn_id, - payment_attempt, - request, - token, - card_cvc, - ) - .await + helpers::make_pm_data(Box::new(self), state, payment_data).await } async fn get_connector<'a>( diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 9f940cf3963..d104eead109 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -253,20 +253,14 @@ where async fn make_pm_data<'b>( &'b self, _state: &'b AppState, - _payment_method: Option<enums::PaymentMethodType>, - _txn_id: &str, - _payment_attempt: &storage::PaymentAttempt, - _request: &Option<api::PaymentMethod>, - _token: &Option<String>, - _card_cvc: Option<Secret<String>>, + _payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsSessionRequest>, Option<api::PaymentMethod>, - Option<String>, )> { //No payment method data for this operation - Ok((Box::new(self), None, None)) + Ok((Box::new(self), None)) } async fn get_connector<'a>( diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 8f086e6695b..6ffb441de2a 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -238,29 +238,13 @@ where async fn make_pm_data<'a>( &'a self, state: &'a AppState, - payment_method: Option<enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsStartRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_method, - txn_id, - payment_attempt, - request, - token, - card_cvc, - ) - .await + helpers::make_pm_data(Box::new(self), state, payment_data).await } async fn get_connector<'a>( diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 105f28506db..7736ffdf874 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -2,7 +2,6 @@ use std::marker::PhantomData; use async_trait::async_trait; use error_stack::ResultExt; -use masking::Secret; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -79,29 +78,13 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentStatus { async fn make_pm_data<'a>( &'a self, state: &'a AppState, - payment_method: Option<enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_method, - txn_id, - payment_attempt, - request, - token, - card_cvc, - ) - .await + helpers::make_pm_data(Box::new(self), state, payment_data).await } #[instrument(skip_all)] diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 810dec8f32d..427e9fbc3d6 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -3,7 +3,6 @@ use std::marker::PhantomData; use async_trait::async_trait; use common_utils::ext_traits::AsyncExt; use error_stack::{report, ResultExt}; -use masking::Secret; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -232,29 +231,13 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentUpdate { async fn make_pm_data<'a>( &'a self, state: &'a AppState, - payment_method: Option<enums::PaymentMethodType>, - txn_id: &str, - payment_attempt: &storage::PaymentAttempt, - request: &Option<api::PaymentMethod>, - token: &Option<String>, - card_cvc: Option<Secret<String>>, + payment_data: &mut PaymentData<F>, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRequest>, Option<api::PaymentMethod>, - Option<String>, )> { - helpers::make_pm_data( - Box::new(self), - state, - payment_method, - txn_id, - payment_attempt, - request, - token, - card_cvc, - ) - .await + helpers::make_pm_data(Box::new(self), state, payment_data).await } #[instrument(skip_all)] diff --git a/crates/storage_models/src/locker_mock_up.rs b/crates/storage_models/src/locker_mock_up.rs index 8190244c313..19553f1cb9b 100644 --- a/crates/storage_models/src/locker_mock_up.rs +++ b/crates/storage_models/src/locker_mock_up.rs @@ -35,4 +35,5 @@ pub struct LockerMockUpNew { pub card_exp_month: String, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, + pub customer_id: Option<String>, }
fix
check if saved payment method and that in request are for the same customer (#260)
66563595df6ad397feb607fbca342e4b56183a91
2023-02-19 19:29:22
Narayan Bhat
refactor: add payment_issuer and payment_experience in pa (#491)
false
diff --git a/Cargo.lock b/Cargo.lock index fa1ee727160..607a98aa820 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1181,6 +1181,41 @@ dependencies = [ "typenum", ] +[[package]] +name = "darling" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0808e1bd8671fb44a113a14e13497557533369847788fa2ae912b6ebfce9fa8" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "001d80444f28e193f30c2f293455da62dcf9a6b29918a4253152ae2b1de592cb" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b36230598a2d5de7ec1c6f51f72d8a99a9208daff41de2084d06e3fd3ea56685" +dependencies = [ + "darling_core", + "quote", + "syn", +] + [[package]] name = "dashmap" version = "5.4.0" @@ -1893,6 +1928,12 @@ dependencies = [ "tokio-native-tls", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "0.3.0" @@ -3094,6 +3135,7 @@ dependencies = [ name = "router_derive" version = "0.1.0" dependencies = [ + "darling", "diesel", "proc-macro2", "quote", @@ -3531,6 +3573,12 @@ dependencies = [ "time", ] +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + [[package]] name = "strum" version = "0.24.1" diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index a7f91bae6d1..e4434ad23ed 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use super::payments::AddressDetails; -use crate::{enums as api_enums, payment_methods}; +use crate::enums as api_enums; #[derive(Clone, Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] @@ -325,7 +325,7 @@ pub struct PaymentMethods { pub installment_payment_enabled: bool, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] - pub payment_experience: Option<Vec<payment_methods::PaymentExperience>>, + pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index e6c2201145b..fbf421d43f6 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -343,6 +343,66 @@ pub enum PaymentMethodIssuerCode { JpBacs, } +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + frunk::LabelledGeneric, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +pub enum PaymentIssuer { + Klarna, + Affirm, + AfterpayClearpay, + AmericanExpress, + BankOfAmerica, + Barclays, + CapitalOne, + Chase, + Citi, + Discover, + NavyFederalCreditUnion, + PentagonFederalCreditUnion, + SynchronyBank, + WellsFargo, +} + +#[derive( + Eq, + PartialEq, + Hash, + Copy, + Clone, + Debug, + serde::Serialize, + serde::Deserialize, + ToSchema, + Default, + frunk::LabelledGeneric, +)] +#[serde(rename_all = "snake_case")] +pub enum PaymentExperience { + /// The URL to which the customer needs to be redirected for completing the payment. + #[default] + RedirectToUrl, + /// Contains the data for invoking the sdk client for completing the payment. + InvokeSdkClient, + /// The QR code data to be displayed to the customer. + DisplayQrCode, + /// Contains data to finish one click payment. + OneClick, + /// Redirect customer to link wallet + LinkWallet, + /// Contains the data for invoking the sdk client for completing the payment. + InvokePaymentApp, +} + #[derive( Clone, Copy, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 4d0f484f3b1..d768b52f7ea 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -122,7 +122,7 @@ pub struct PaymentMethodResponse { /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] - pub payment_experience: Option<Vec<PaymentExperience>>, + pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] @@ -348,8 +348,8 @@ pub struct ListPaymentMethod { pub installment_payment_enabled: bool, /// Type of payment experience enabled with the connector - #[schema(example = json!(["redirect_to_url"]))] - pub payment_experience: Option<Vec<PaymentExperience>>, + #[schema(value_type = Option<Vec<PaymentExperience>>, example = json!(["redirect_to_url"]))] + pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, } /// We need a custom serializer to only send relevant fields in ListPaymentMethodResponse @@ -447,7 +447,7 @@ pub struct CustomerPaymentMethod { /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] - pub payment_experience: Option<Vec<PaymentExperience>>, + pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] @@ -462,26 +462,6 @@ pub struct CustomerPaymentMethod { #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, } - -#[derive(Eq, PartialEq, Hash, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] -#[serde(rename_all = "snake_case")] -#[non_exhaustive] -pub enum PaymentExperience { - /// The URL to which the customer needs to be redirected for completing the payment.The URL to - /// which the customer needs to be redirected for completing the payment. - RedirectToUrl, - /// Contains the data for invoking the sdk client for completing the payment. - InvokeSdkClient, - /// The QR code data to be displayed to the customer. - DisplayQrCode, - /// Contains data to finish one click payment. - OneClick, - /// Redirect customer to link wallet - LinkWallet, - /// Contains the data for invoking the sdk client for completing the payment. - InvokePaymentApp, -} - #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { pub payment_method_id: String, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b28736c9805..a4705057be9 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -132,6 +132,12 @@ pub struct PaymentsRequest { "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, + /// Payment Issuser for the current payment + #[schema(value_type = Option<PaymentIssuer>, example = "klarna")] + pub payment_issuer: Option<api_enums::PaymentIssuer>, + /// Payment Experience, works in tandem with payment_issuer + #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] + pub payment_experience: Option<api_enums::PaymentExperience>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] @@ -342,35 +348,27 @@ pub enum AfterpayClearpayIssuer { pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { - /// The issuer name of the redirect - issuer_name: KlarnaIssuer, /// The billing email - billing_email: String, + #[schema(value_type = String)] + billing_email: Secret<String, pii::Email>, // The billing country code billing_country: String, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { - /// The issuer name of the sdk - issuer_name: KlarnaIssuer, /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option - AffirmRedirect { - /// The issuer name of affirm redirect issuer - issuer_name: AffirmIssuer, - /// The billing email - billing_email: String, - }, + AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { - /// The issuer name of afterpayclearpay redirect issuer - issuer_name: AfterpayClearpayIssuer, /// The billing email - billing_email: String, + #[schema(value_type = String)] + billing_email: Secret<String, pii::Email>, /// The billing name - billing_name: String, + #[schema(value_type = String)] + billing_name: Secret<String>, }, } diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs index d7bd9721507..2d797a5bda9 100644 --- a/crates/common_utils/src/custom_serde.rs +++ b/crates/common_utils/src/custom_serde.rs @@ -86,7 +86,7 @@ pub mod iso8601 { } } -/// https://github.com/serde-rs/serde/issues/994#issuecomment-316895860 +/// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860> pub mod json_string { use serde::de::{self, Deserialize, DeserializeOwned, Deserializer}; diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 2f0e693f37e..2f681a72f76 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -216,7 +216,6 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index de811604779..03a74af1960 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -672,7 +672,6 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), @@ -722,7 +721,6 @@ pub fn get_adyen_response( let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.psp_reference), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }; @@ -783,7 +781,6 @@ pub fn get_redirection_response( let payments_response_data = types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, redirection_data: Some(redirection_data), - redirect: true, mandate_reference: None, connector_metadata: None, }; @@ -876,7 +873,6 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>> status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference), - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 1d0de718a07..027ecd30c92 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -329,7 +329,6 @@ impl<F, T> item.response.transaction_response.transaction_id, ), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: metadata, }), @@ -606,7 +605,6 @@ impl<F, Req> item.response.transaction.transaction_id, ), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 37dbe67a84c..e2ca6ae93f8 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -219,7 +219,6 @@ impl<F, T> item.response.transaction.id, ), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 7a1cf05520e..dfb6d152aca 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -246,7 +246,6 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>> )), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirect: redirection_data.is_some(), redirection_data, mandate_reference: None, connector_metadata: None, @@ -289,7 +288,6 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>> )), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirect: redirection_data.is_some(), redirection_data, mandate_reference: None, connector_metadata: None, @@ -332,7 +330,6 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>> Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.action_id.clone()), - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -404,7 +401,6 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>> resource_id: types::ResponseId::ConnectorTransactionId( item.data.request.connector_transaction_id.to_owned(), ), - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index acec267d9f4..23f555d3646 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -315,7 +315,6 @@ impl<F, T> _ => Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), @@ -379,7 +378,6 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs index b998db5d70f..6699991b157 100644 --- a/crates/router/src/connector/fiserv/transformers.rs +++ b/crates/router/src/connector/fiserv/transformers.rs @@ -226,7 +226,6 @@ impl<F, T> gateway_resp.transaction_processing_details.transaction_id, ), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 80adfb4efa4..e743ab34037 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -165,7 +165,6 @@ fn get_payment_response( _ => Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(response.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 01a2aee175f..aab27644cf5 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -13,6 +13,7 @@ use crate::{ types::{ self, api::{self, ConnectorCommon}, + storage::enums as storage_enums, }, utils::{self, BytesExt}, }; @@ -235,12 +236,27 @@ impl match payment_method_data { api_payments::PaymentMethod::PayLater(api_payments::PayLaterData::KlarnaSdk { token, - .. - }) => Ok(format!( - "{}payments/v1/authorizations/{}/order", - self.base_url(connectors), - token - )), + }) => match ( + req.request.payment_issuer.as_ref(), + req.request.payment_experience.as_ref(), + ) { + ( + Some(storage_enums::PaymentIssuer::Klarna), + Some(storage_enums::PaymentExperience::InvokeSdkClient), + ) => Ok(format!( + "{}payments/v1/authorizations/{}/order", + self.base_url(connectors), + token + )), + (None, _) | (_, None) => Err(error_stack::report!( + errors::ConnectorError::MissingRequiredField { + field_name: "payment_issuer and payment_experience" + } + )), + _ => Err(error_stack::report!( + errors::ConnectorError::MismatchedPaymentData + )), + }, _ => Err(error_stack::report!( errors::ConnectorError::NotImplemented( "We only support wallet payments through klarna".to_string(), diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 14810ba6724..589eeecf19b 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -114,7 +114,6 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>> Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs index 20a2c6f4bb7..3c107ddcb1b 100644 --- a/crates/router/src/connector/payu/transformers.rs +++ b/crates/router/src/connector/payu/transformers.rs @@ -207,7 +207,6 @@ impl<F, T> status: enums::AttemptStatus::from(item.response.status.status_code), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -258,7 +257,6 @@ impl<F, T> status: enums::AttemptStatus::from(item.response.status.status_code.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::NoResponseId, - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -337,7 +335,6 @@ impl<F, T> status: enums::AttemptStatus::from(item.response.status.status_code.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id), - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -466,7 +463,6 @@ impl<F, T> status: enums::AttemptStatus::from(order.status.clone()), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(order.order_id.clone()), - redirect: false, redirection_data: None, mandate_reference: None, connector_metadata: None, diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index a0b6df812c0..e5f58668900 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -414,7 +414,6 @@ impl<F, T> resource_id: types::ResponseId::ConnectorTransactionId( data.id.to_owned(), ), //transaction_id is also the field but this id is used to initiate a refund - redirect: redirection_data.is_some(), redirection_data, mandate_reference: None, connector_metadata: None, diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index ea1ebce8c5d..bb744fe0679 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -154,7 +154,6 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 865d7a243ae..b473525a42e 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,7 +1,7 @@ use std::str::FromStr; use api_models::{self, payments}; -use common_utils::fp_utils; +use common_utils::{fp_utils, pii::Email}; use error_stack::{IntoReport, ResultExt}; use masking::ExposeInterface; use serde::{Deserialize, Serialize}; @@ -80,12 +80,13 @@ pub struct PaymentIntentRequest { pub metadata_txn_uuid: String, pub return_url: String, pub confirm: bool, - pub off_session: Option<bool>, pub mandate: Option<String>, pub description: Option<String>, #[serde(flatten)] pub shipping: StripeShippingAddress, #[serde(flatten)] + pub billing: StripeBillingAddress, + #[serde(flatten)] pub payment_data: Option<StripePaymentMethodData>, pub capture_method: StripeCaptureMethod, } @@ -128,27 +129,19 @@ pub struct StripePayLaterData { pub payment_method_types: StripePaymentMethodType, #[serde(rename = "payment_method_data[type]")] pub payment_method_data_type: StripePaymentMethodType, - #[serde(rename = "payment_method_data[billing_details][email]")] - pub billing_email: String, - #[serde(rename = "payment_method_data[billing_details][address][country]")] - pub billing_country: Option<String>, - #[serde(rename = "payment_method_data[billing_details][name]")] - pub billing_name: Option<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] #[serde(untagged)] pub enum StripePaymentMethodData { Card(StripeCardData), - Klarna(StripePayLaterData), - Affirm(StripePayLaterData), - AfterpayClearpay(StripePayLaterData), + PayLater(StripePayLaterData), Bank, Wallet, Paypal, } -#[derive(Debug, Eq, PartialEq, Serialize)] +#[derive(Debug, Eq, PartialEq, Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { Card, @@ -159,63 +152,165 @@ pub enum StripePaymentMethodType { fn validate_shipping_address_against_payment_method( shipping_address: &StripeShippingAddress, - payment_method: &payments::PaymentMethod, + payment_method: &StripePaymentMethodType, ) -> Result<(), errors::ConnectorError> { - if let payments::PaymentMethod::PayLater(payments::PayLaterData::AfterpayClearpayRedirect { - .. - }) = payment_method - { + if let StripePaymentMethodType::AfterpayClearpay = payment_method { fp_utils::when(shipping_address.name.is_none(), || { Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.first_name", + field_name: "shipping.address.first_name", }) })?; fp_utils::when(shipping_address.line1.is_none(), || { Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.line1", + field_name: "shipping.address.line1", }) })?; fp_utils::when(shipping_address.country.is_none(), || { Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.country", + field_name: "shipping.address.country", }) })?; fp_utils::when(shipping_address.zip.is_none(), || { Err(errors::ConnectorError::MissingRequiredField { - field_name: "shipping.zip", + field_name: "shipping.address.zip", }) })?; } Ok(()) } +fn infer_stripe_pay_later_issuer( + issuer: &enums::PaymentIssuer, + experience: &enums::PaymentExperience, +) -> Result<StripePaymentMethodType, errors::ConnectorError> { + if &enums::PaymentExperience::RedirectToUrl == experience { + match issuer { + enums::PaymentIssuer::Klarna => Ok(StripePaymentMethodType::Klarna), + enums::PaymentIssuer::Affirm => Ok(StripePaymentMethodType::Affirm), + enums::PaymentIssuer::AfterpayClearpay => Ok(StripePaymentMethodType::AfterpayClearpay), + _ => Err(errors::ConnectorError::NotSupported { + payment_method: format!("{issuer} payments by {experience}"), + connector: "stripe", + }), + } + } else { + Err(errors::ConnectorError::NotSupported { + payment_method: format!("{issuer} payments by {experience}"), + connector: "stripe", + }) + } +} + +impl TryFrom<(&api_models::payments::PayLaterData, StripePaymentMethodType)> + for StripeBillingAddress +{ + type Error = errors::ConnectorError; + + fn try_from( + (pay_later_data, pm_type): (&api_models::payments::PayLaterData, StripePaymentMethodType), + ) -> Result<Self, Self::Error> { + match (pay_later_data, pm_type) { + ( + payments::PayLaterData::KlarnaRedirect { + billing_email, + billing_country, + }, + StripePaymentMethodType::Klarna, + ) => Ok(Self { + email: Some(billing_email.to_owned()), + country: Some(billing_country.to_owned()), + ..Self::default() + }), + (payments::PayLaterData::AffirmRedirect {}, StripePaymentMethodType::Affirm) => { + Ok(Self::default()) + } + ( + payments::PayLaterData::AfterpayClearpayRedirect { + billing_email, + billing_name, + }, + StripePaymentMethodType::AfterpayClearpay, + ) => Ok(Self { + email: Some(billing_email.to_owned()), + name: Some(billing_name.to_owned()), + ..Self::default() + }), + _ => Err(errors::ConnectorError::MismatchedPaymentData), + } + } +} + +fn create_stripe_payment_method( + issuer: Option<&enums::PaymentIssuer>, + experience: Option<&enums::PaymentExperience>, + payment_method: &api_models::payments::PaymentMethod, + auth_type: enums::AuthenticationType, +) -> Result< + ( + StripePaymentMethodData, + StripePaymentMethodType, + StripeBillingAddress, + ), + errors::ConnectorError, +> { + match payment_method { + payments::PaymentMethod::Card(card_details) => { + let payment_method_auth_type = match auth_type { + enums::AuthenticationType::ThreeDs => Auth3ds::Any, + enums::AuthenticationType::NoThreeDs => Auth3ds::Automatic, + }; + Ok(( + StripePaymentMethodData::Card(StripeCardData { + payment_method_types: StripePaymentMethodType::Card, + payment_method_data_type: StripePaymentMethodType::Card, + payment_method_data_card_number: card_details.card_number.clone(), + payment_method_data_card_exp_month: card_details.card_exp_month.clone(), + payment_method_data_card_exp_year: card_details.card_exp_year.clone(), + payment_method_data_card_cvc: card_details.card_cvc.clone(), + payment_method_auth_type, + }), + StripePaymentMethodType::Card, + StripeBillingAddress::default(), + )) + } + payments::PaymentMethod::PayLater(pay_later_data) => { + let pm_issuer = issuer.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "payment_issuer", + })?; + + let pm_experience = experience.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "payment_experience", + })?; + + let pm_type = infer_stripe_pay_later_issuer(pm_issuer, pm_experience)?; + + let billing_address = + StripeBillingAddress::try_from((pay_later_data, pm_type.clone()))?; + + Ok(( + StripePaymentMethodData::PayLater(StripePayLaterData { + payment_method_types: pm_type.clone(), + payment_method_data_type: pm_type.clone(), + }), + pm_type, + billing_address, + )) + } + _ => Err(errors::ConnectorError::NotImplemented( + "stripe does not support this payment method".to_string(), + )), + } +} + impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { type Error = errors::ConnectorError; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let metadata_order_id = item.payment_id.to_string(); let metadata_txn_id = format!("{}_{}_{}", item.merchant_id, item.payment_id, "1"); let metadata_txn_uuid = Uuid::new_v4().to_string(); //Fetch autogenerated txn_uuid from Database. - // let api::PaymentMethod::Card(a) = item.payment_method_data; - // let api::PaymentMethod::Card(a) = item.payment_method_data; - - let (payment_data, mandate) = { - match item - .request - .mandate_id - .clone() - .and_then(|mandate_ids| mandate_ids.connector_mandate_id) - { - None => { - let payment_method: StripePaymentMethodData = - (item.request.payment_method_data.clone(), item.auth_type).try_into()?; - (Some(payment_method), None) - } - Some(mandate_id) => (None, Some(mandate_id)), - } - }; let shipping_address = match item.address.shipping.clone() { Some(mut shipping) => StripeShippingAddress { @@ -247,15 +342,32 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { None => StripeShippingAddress::default(), }; - validate_shipping_address_against_payment_method( - &shipping_address, - &item.request.payment_method_data, - )?; - - let off_session = item - .request - .off_session - .and_then(|value| mandate.as_ref().map(|_| value)); + let (payment_data, mandate, billing_address) = { + match item + .request + .mandate_id + .clone() + .and_then(|mandate_ids| mandate_ids.connector_mandate_id) + { + None => { + let (payment_method_data, payment_method_type, billing_address) = + create_stripe_payment_method( + item.request.payment_issuer.as_ref(), + item.request.payment_experience.as_ref(), + &item.request.payment_method_data, + item.auth_type, + )?; + + validate_shipping_address_against_payment_method( + &shipping_address, + &payment_method_type, + )?; + + (Some(payment_method_data), None, billing_address) + } + Some(mandate_id) => (None, Some(mandate_id), StripeBillingAddress::default()), + } + }; Ok(Self { amount: item.request.amount, //hopefully we don't loose some cents here @@ -272,9 +384,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { description: item.description.clone(), shipping: shipping_address, + billing: billing_address, capture_method: StripeCaptureMethod::from(item.request.capture_method), payment_data, - off_session, mandate, }) } @@ -287,8 +399,13 @@ impl TryFrom<&types::VerifyRouterData> for SetupIntentRequest { let metadata_txn_id = format!("{}_{}_{}", item.merchant_id, item.payment_id, "1"); let metadata_txn_uuid = Uuid::new_v4().to_string(); - let payment_data: StripePaymentMethodData = - (item.request.payment_method_data.clone(), item.auth_type).try_into()?; + //Only cards supported for mandates + let pm_type = StripePaymentMethodType::Card; + let payment_data = StripePaymentMethodData::try_from(( + item.request.payment_method_data.clone(), + item.auth_type, + pm_type, + ))?; Ok(Self { confirm: true, @@ -421,7 +538,6 @@ impl<F, T> // three_ds_form, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirect: redirection_data.is_some(), redirection_data, mandate_reference, connector_metadata: None, @@ -473,7 +589,6 @@ impl<F, T> status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), - redirect: redirection_data.is_some(), redirection_data, mandate_reference, connector_metadata: None, @@ -649,13 +764,23 @@ pub struct StripeShippingAddress { pub phone: Option<Secret<String>>, } +#[derive(Debug, Default, Eq, PartialEq, Serialize)] +pub struct StripeBillingAddress { + #[serde(rename = "payment_method_data[billing_details][email]")] + pub email: Option<Secret<String, Email>>, + #[serde(rename = "payment_method_data[billing_details][address][country]")] + pub country: Option<String>, + #[serde(rename = "payment_method_data[billing_details][name]")] + pub name: Option<Secret<String>>, +} + #[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)] pub struct StripeRedirectResponse { pub payment_intent: String, pub payment_intent_client_secret: String, pub source_redirect_slug: Option<String>, pub redirect_status: Option<StripePaymentStatus>, - pub source_type: Option<String>, + pub source_type: Option<Secret<String>>, } #[derive(Debug, Serialize, Clone, Copy)] @@ -792,10 +917,20 @@ pub struct StripeWebhookObjectId { pub data: StripeWebhookDataId, } -impl TryFrom<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentMethodData { +impl + TryFrom<( + api::PaymentMethod, + enums::AuthenticationType, + StripePaymentMethodType, + )> for StripePaymentMethodData +{ type Error = errors::ConnectorError; fn try_from( - (pm_data, auth_type): (api::PaymentMethod, enums::AuthenticationType), + (pm_data, auth_type, pm_type): ( + api::PaymentMethod, + enums::AuthenticationType, + StripePaymentMethodType, + ), ) -> Result<Self, Self::Error> { match pm_data { api::PaymentMethod::Card(ref ccard) => Ok(Self::Card({ @@ -814,42 +949,10 @@ impl TryFrom<(api::PaymentMethod, enums::AuthenticationType)> for StripePaymentM } })), api::PaymentMethod::BankTransfer => Ok(Self::Bank), - api::PaymentMethod::PayLater(pay_later_data) => match pay_later_data { - api_models::payments::PayLaterData::KlarnaRedirect { - billing_email, - billing_country, - .. - } => Ok(Self::Klarna(StripePayLaterData { - payment_method_types: StripePaymentMethodType::Klarna, - payment_method_data_type: StripePaymentMethodType::Klarna, - billing_email, - billing_country: Some(billing_country), - billing_name: None, - })), - api_models::payments::PayLaterData::AffirmRedirect { billing_email, .. } => { - Ok(Self::Affirm(StripePayLaterData { - payment_method_types: StripePaymentMethodType::Affirm, - payment_method_data_type: StripePaymentMethodType::Affirm, - billing_email, - billing_country: None, - billing_name: None, - })) - } - api_models::payments::PayLaterData::AfterpayClearpayRedirect { - billing_email, - billing_name, - .. - } => Ok(Self::AfterpayClearpay(StripePayLaterData { - payment_method_types: StripePaymentMethodType::AfterpayClearpay, - payment_method_data_type: StripePaymentMethodType::AfterpayClearpay, - billing_email, - billing_country: None, - billing_name: Some(billing_name), - })), - _ => Err(errors::ConnectorError::NotImplemented(String::from( - "Stripe does not support payment through provided payment method", - ))), - }, + api::PaymentMethod::PayLater(_) => Ok(Self::PayLater(StripePayLaterData { + payment_method_types: pm_type.clone(), + payment_method_data_type: pm_type, + })), api::PaymentMethod::Wallet(_) => Ok(Self::Wallet), api::PaymentMethod::Paypal => Ok(Self::Paypal), } diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index f2eefdf8ba6..4722a81ed28 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -357,7 +357,6 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, types::PaymentsRespo response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), @@ -386,7 +385,6 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, types::Payme response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index c039bb8ed21..bd53b9fd784 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -160,7 +160,6 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::try_from(response.links)?, redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), @@ -256,7 +255,6 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: data.request.connector_transaction_id.clone(), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), @@ -314,7 +312,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::try_from(response.links)?, redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 88427b3ee90..2e50e71840a 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -167,7 +167,6 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::try_from(item.response.links)?, redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }), diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 8bead7d183e..c27f2ee65a8 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -248,6 +248,11 @@ pub enum ConnectorError { FailedToObtainCertificateKey, #[error("This step has not been implemented for: {0}")] NotImplemented(String), + #[error("{payment_method} is not supported by {connector}")] + NotSupported { + payment_method: String, + connector: &'static str, + }, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")] @@ -270,6 +275,8 @@ pub enum ConnectorError { WebhookResourceObjectNotFound, #[error("Invalid Date/time format")] InvalidDateFormat, + #[error("Payment Issuer does not match the Payment Data provided")] + MismatchedPaymentData, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index d146dd0dd67..4371b6bf5a9 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -101,6 +101,12 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> { ), } } + errors::ConnectorError::MismatchedPaymentData => { + errors::ApiErrorResponse::InvalidDataValue { + field_name: + "payment_method_data and payment_issuer, payment_experience does not match", + } + } _ => errors::ApiErrorResponse::InternalServerError, }; self.change_context(error) diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ee9a8ea546d..e004707a1d8 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -85,9 +85,7 @@ pub async fn add_payment_method( payment_method_issuer_code: req.payment_method_issuer_code, recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] - payment_experience: Some(vec![ - api_models::payment_methods::PaymentExperience::RedirectToUrl, - ]), //[#219] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] }) } } @@ -635,9 +633,7 @@ pub async fn list_customer_payment_method( .map(ForeignInto::foreign_into), recurring_enabled: false, installment_payment_enabled: false, - payment_experience: Some(vec![ - api_models::payment_methods::PaymentExperience::RedirectToUrl, - ]), + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), created: Some(pm.created_at), }; vec.push(pma); @@ -880,9 +876,7 @@ pub async fn retrieve_payment_method( .map(ForeignInto::foreign_into), recurring_enabled: false, //[#219] installment_payment_enabled: false, //[#219] - payment_experience: Some(vec![ - api_models::payment_methods::PaymentExperience::RedirectToUrl, - ]), //[#219], + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219], }, )) } diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index cedf98e5dcc..2144bd7e01b 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -127,9 +127,7 @@ pub fn mk_add_card_response( payment_method_issuer_code: req.payment_method_issuer_code, recurring_enabled: false, // [#256] installment_payment_enabled: false, // #[#256] - payment_experience: Some(vec![ - api_models::payment_methods::PaymentExperience::RedirectToUrl, - ]), // [#256] + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), // [#256] } } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 450572adaa8..f8b8f756a3c 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -433,6 +433,8 @@ impl PaymentCreate { last_synced, authentication_type: request.authentication_type.map(ForeignInto::foreign_into), browser_info, + payment_experience: request.payment_experience.map(ForeignInto::foreign_into), + payment_issuer: request.payment_issuer.map(ForeignInto::foreign_into), ..storage::PaymentAttemptNew::default() } } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 33c0d4fe69d..6f8761363ed 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -280,7 +280,6 @@ async fn payment_response_update_tracker<F: Clone, T>( types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, - redirect, connector_metadata, .. } => { @@ -305,7 +304,6 @@ async fn payment_response_update_tracker<F: Clone, T>( connector_transaction_id: connector_transaction_id.clone(), authentication_type: None, payment_method_id: Some(router_data.payment_method_id), - redirect: Some(redirect), mandate_id: payment_data .mandate_id .clone() diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 51c4d35ce16..ee6b62f9e77 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -65,7 +65,6 @@ where .map(|id| types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(id.to_string()), redirection_data: None, - redirect: false, mandate_reference: None, connector_metadata: None, }); @@ -430,6 +429,8 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsAuthorizeData { currency: payment_data.currency, browser_info, email: payment_data.email, + payment_experience: payment_data.payment_attempt.payment_experience, + payment_issuer: payment_data.payment_attempt.payment_issuer, order_details, }) } diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs index ab8c0027ad3..83f4bc97266 100644 --- a/crates/router/src/db/payment_attempt.rs +++ b/crates/router/src/db/payment_attempt.rs @@ -227,8 +227,6 @@ impl PaymentAttemptInterface for MockDb { tax_amount: payment_attempt.tax_amount, payment_method_id: payment_attempt.payment_method_id, payment_method: payment_attempt.payment_method, - payment_flow: payment_attempt.payment_flow, - redirect: payment_attempt.redirect, connector_transaction_id: payment_attempt.connector_transaction_id, capture_method: payment_attempt.capture_method, capture_on: payment_attempt.capture_on, @@ -244,6 +242,8 @@ impl PaymentAttemptInterface for MockDb { payment_token: None, error_code: payment_attempt.error_code, connector_metadata: None, + payment_experience: payment_attempt.payment_experience, + payment_issuer: payment_attempt.payment_issuer, }; payment_attempts.push(payment_attempt.clone()); Ok(payment_attempt) @@ -366,8 +366,6 @@ mod storage { tax_amount: payment_attempt.tax_amount, payment_method_id: payment_attempt.payment_method_id.clone(), payment_method: payment_attempt.payment_method, - payment_flow: payment_attempt.payment_flow, - redirect: payment_attempt.redirect, connector_transaction_id: payment_attempt.connector_transaction_id.clone(), capture_method: payment_attempt.capture_method, capture_on: payment_attempt.capture_on, @@ -383,6 +381,8 @@ mod storage { payment_token: payment_attempt.payment_token.clone(), error_code: payment_attempt.error_code.clone(), connector_metadata: payment_attempt.connector_metadata.clone(), + payment_experience: payment_attempt.payment_experience.clone(), + payment_issuer: payment_attempt.payment_issuer, }; let field = format!("pa_{}", created_attempt.attempt_id); diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index d158c5316f1..89032a53ea7 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -139,6 +139,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::SupportedWallets, api_models::enums::PaymentMethodIssuerCode, api_models::enums::MandateStatus, + api_models::enums::PaymentExperience, + api_models::enums::PaymentIssuer, api_models::admin::PaymentConnectorCreate, api_models::admin::PaymentMethods, api_models::payments::AddressDetails, @@ -163,7 +165,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::CustomerAcceptance, api_models::payments::PaymentsRequest, api_models::payments::PaymentsResponse, - api_models::payment_methods::PaymentExperience, api_models::payments::PaymentsStartRequest, api_models::payments::PaymentRetrieveBody, api_models::payments::PaymentsRetrieveRequest, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 0cc6d6f2181..86d2fd67c0a 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -115,6 +115,8 @@ pub struct PaymentsAuthorizeData { pub setup_mandate_details: Option<payments::MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<api_models::payments::OrderDetails>, + pub payment_issuer: Option<storage_enums::PaymentIssuer>, + pub payment_experience: Option<storage_enums::PaymentExperience>, } #[derive(Debug, Clone)] @@ -181,7 +183,6 @@ pub enum PaymentsResponseData { TransactionResponse { resource_id: ResponseId, redirection_data: Option<services::RedirectForm>, - redirect: bool, mandate_reference: Option<String>, connector_metadata: Option<serde_json::Value>, }, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 6d4a3511fd6..b900c630f94 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -88,18 +88,6 @@ where } } -impl From<F<api_enums::RoutingAlgorithm>> for F<storage_enums::RoutingAlgorithm> { - fn from(algo: F<api_enums::RoutingAlgorithm>) -> Self { - Self(frunk::labelled_convert_from(algo.0)) - } -} - -impl From<F<storage_enums::RoutingAlgorithm>> for F<api_enums::RoutingAlgorithm> { - fn from(algo: F<storage_enums::RoutingAlgorithm>) -> Self { - Self(frunk::labelled_convert_from(algo.0)) - } -} - impl From<F<api_enums::ConnectorType>> for F<storage_enums::ConnectorType> { fn from(conn: F<api_enums::ConnectorType>) -> Self { Self(frunk::labelled_convert_from(conn.0)) @@ -158,6 +146,18 @@ impl From<F<storage_enums::PaymentMethodIssuerCode>> for F<api_enums::PaymentMet } } +impl From<F<api_enums::PaymentIssuer>> for F<storage_enums::PaymentIssuer> { + fn from(issuer: F<api_enums::PaymentIssuer>) -> Self { + Self(frunk::labelled_convert_from(issuer.0)) + } +} + +impl From<F<api_enums::PaymentExperience>> for F<storage_enums::PaymentExperience> { + fn from(experience: F<api_enums::PaymentExperience>) -> Self { + Self(frunk::labelled_convert_from(experience.0)) + } +} + impl From<F<storage_enums::IntentStatus>> for F<api_enums::IntentStatus> { fn from(status: F<storage_enums::IntentStatus>) -> Self { Self(frunk::labelled_convert_from(status.0)) diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 115d4af308f..23f9ddfcf81 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -50,6 +50,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { browser_info: None, order_details: None, email: None, + payment_experience: None, + payment_issuer: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index da0a412784d..632d8faf718 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -78,6 +78,8 @@ impl AdyenTest { browser_info: None, order_details: None, email: None, + payment_experience: None, + payment_issuer: None, }) } } diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 5068e1d46c1..c5fa9ccc58c 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -50,6 +50,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { browser_info: None, order_details: None, email: None, + payment_experience: None, + payment_issuer: None, }, payment_method_id: None, response: Err(types::ErrorResponse::default()), diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index a75caff6c1b..e9f6b6b1c88 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -47,6 +47,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { browser_info: None, order_details: None, email: None, + payment_experience: None, + payment_issuer: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 32ab2637bf7..e1974180e56 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -469,6 +469,8 @@ impl Default for PaymentAuthorizeType { browser_info: Some(BrowserInfoType::default().0), order_details: None, email: None, + payment_experience: None, + payment_issuer: None, }; Self(data) } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 08bcbad43f9..f284baf6dff 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -80,6 +80,8 @@ impl WorldlineTest { browser_info: None, order_details: None, email: None, + payment_experience: None, + payment_issuer: None, }) } } diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index b27a100d765..7452ecda85d 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -327,6 +327,8 @@ async fn payments_create_core() { off_session: None, client_secret: None, browser_info: None, + payment_experience: None, + payment_issuer: None, }; let expected_response = api::PaymentsResponse { @@ -482,6 +484,8 @@ async fn payments_create_core_adyen_no_redirect() { off_session: None, client_secret: None, browser_info: None, + payment_experience: None, + payment_issuer: None, }; let expected_response = services::ApplicationResponse::Json(api::PaymentsResponse { diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index a4e9e498ccd..d7c80f560af 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -239,6 +239,8 @@ async fn payments_create_core_adyen_no_redirect() { mandate_id: None, client_secret: None, browser_info: None, + payment_experience: None, + payment_issuer: None, }; let expected_response = services::ApplicationResponse::Json(api::PaymentsResponse { diff --git a/crates/router_derive/Cargo.toml b/crates/router_derive/Cargo.toml index 47a4d8a59d1..62540a0f2dd 100644 --- a/crates/router_derive/Cargo.toml +++ b/crates/router_derive/Cargo.toml @@ -12,6 +12,7 @@ proc-macro = true doctest = false [dependencies] +darling = "0.14.3" proc-macro2 = "1.0.50" quote = "1.0.23" syn = { version = "1.0.107", features = ["full", "extra-traits"] } # the full feature does not seem to encompass all the features diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index da7c01202f4..4fe12da088e 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -53,13 +53,13 @@ pub fn debug_as_display_derive(input: proc_macro::TokenStream) -> proc_macro::To /// # Example /// /// ``` -/// use router_derive::{DieselEnum, diesel_enum}; +/// use router_derive::diesel_enum; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. /// #[derive(strum::Display, strum::EnumString)] -/// #[derive(Debug, DieselEnum)] -/// #[diesel_enum] +/// #[derive(Debug)] +/// #[diesel_enum(storage_type = "pg_enum")] /// enum Color { /// Red, /// Green, @@ -69,32 +69,64 @@ pub fn debug_as_display_derive(input: proc_macro::TokenStream) -> proc_macro::To #[proc_macro_derive(DieselEnum)] pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse_macro_input!(input as syn::DeriveInput); - let tokens = macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error()); tokens.into() } +/// Similar to [`DieselEnum`] but uses text when storing in the database, this is to avoid +/// making changes to the database when the enum variants are added or modified +/// +/// # Example +/// [DieselEnum]: macro@crate::diesel_enum +/// +/// ``` +/// use router_derive::{diesel_enum}; +/// +/// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it +/// // yourself if required. +/// #[derive(strum::Display, strum::EnumString)] +/// #[derive(Debug)] +/// #[diesel_enum(storage_type = "text")] +/// enum Color { +/// Red, +/// Green, +/// Blue, +/// } +/// ``` +#[proc_macro_derive(DieselEnumText)] +pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let ast = syn::parse_macro_input!(input as syn::DeriveInput); + let tokens = macros::diesel_enum_text_derive_inner(&ast) + .unwrap_or_else(|error| error.to_compile_error()); + tokens.into() +} + /// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database. /// -/// Works in tandem with the [`DieselEnum`][DieselEnum] derive macro to achieve the desired results. +/// Storage Type can either be "text" or "pg_enum" +/// Choosing text will store the enum as text in the database, whereas pg_enum will map it to the +/// database enum +/// +/// Works in tandem with the [`DieselEnum`][DieselEnum] and [`DieselEnumText`][DieselEnumText] derive macro to achieve the desired results. /// The enum is required to implement (or derive) the [`ToString`][ToString] and the /// [`FromStr`][FromStr] traits for the [`DieselEnum`][DieselEnum] derive macro to be used. /// /// [DieselEnum]: crate::DieselEnum +/// [DieselEnumText]: crate::DieselEnumText /// [FromStr]: ::core::str::FromStr /// [ToString]: ::std::string::ToString /// /// # Example /// /// ``` -/// use router_derive::{DieselEnum, diesel_enum}; +/// use router_derive::{diesel_enum}; /// /// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it /// // yourself if required. (Required by the DieselEnum derive macro.) /// #[derive(strum::Display, strum::EnumString)] -/// #[derive(Debug, DieselEnum)] -/// #[diesel_enum] +/// #[derive(Debug)] +/// #[diesel_enum(storage_type = "text")] /// enum Color { /// Red, /// Green, diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs index db3eb7fc9d8..f9dfa3e741d 100644 --- a/crates/router_derive/src/macros.rs +++ b/crates/router_derive/src/macros.rs @@ -9,7 +9,9 @@ use syn::DeriveInput; pub(crate) use self::{ api_error::api_error_derive_inner, - diesel::{diesel_enum_attribute_inner, diesel_enum_derive_inner}, + diesel::{ + diesel_enum_attribute_inner, diesel_enum_derive_inner, diesel_enum_text_derive_inner, + }, operation::operation_derive_inner, }; diff --git a/crates/router_derive/src/macros/diesel.rs b/crates/router_derive/src/macros/diesel.rs index b49b9ccc33c..3b50fdcf6c9 100644 --- a/crates/router_derive/src/macros/diesel.rs +++ b/crates/router_derive/src/macros/diesel.rs @@ -1,9 +1,46 @@ +use darling::FromMeta; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{AttributeArgs, Data, DeriveInput, ItemEnum}; use crate::macros::helpers::non_enum_error; +pub(crate) fn diesel_enum_text_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { + let name = &ast.ident; + let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); + + match &ast.data { + Data::Enum(_) => (), + _ => return Err(non_enum_error()), + } + + Ok(quote! { + #[automatically_derived] + impl #impl_generics ::diesel::serialize::ToSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics + #where_clause + { + fn to_sql<'b>(&'b self, out: &mut ::diesel::serialize::Output<'b, '_, ::diesel::pg::Pg>) -> ::diesel::serialize::Result { + use ::std::io::Write; + + out.write_all(self.to_string().as_bytes())?; + Ok(::diesel::serialize::IsNull::No) + } + } + + #[automatically_derived] + impl #impl_generics ::diesel::deserialize::FromSql<::diesel::sql_types::Text, ::diesel::pg::Pg> for #name #ty_generics + #where_clause + { + fn from_sql(value: ::diesel::pg::PgValue) -> diesel::deserialize::Result<Self> { + use ::core::str::FromStr; + + Self::from_str(::core::str::from_utf8(value.as_bytes())?) + .map_err(|_| "Unrecognized enum variant".into()) + } + } + }) +} + pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); @@ -50,18 +87,41 @@ pub(crate) fn diesel_enum_attribute_inner( args: &AttributeArgs, item: &ItemEnum, ) -> syn::Result<TokenStream> { - if !args.is_empty() { - return Err(syn::Error::new( - Span::call_site(), - "This attribute macro does not accept any arguments.", - )); + #[derive(FromMeta, Debug)] + enum StorageType { + PgEnum, + Text, } - let name = &item.ident; - let struct_name = format_ident!("Db{name}"); - Ok(quote! { - #[derive(diesel::AsExpression, diesel::FromSqlRow)] - #[diesel(sql_type = #struct_name)] - #item - }) + #[derive(FromMeta, Debug)] + struct StorageTypeArgs { + storage_type: StorageType, + } + + let storage_type_args = match StorageTypeArgs::from_list(args) { + Ok(v) => v, + Err(_) => { + return Err(syn::Error::new( + Span::call_site(), + "Expected storage_type of text or pg_enum", + )); + } + }; + + match storage_type_args.storage_type { + StorageType::PgEnum => { + let name = &item.ident; + let type_name = format_ident!("Db{name}"); + Ok(quote! { + #[derive(diesel::AsExpression, diesel::FromSqlRow, router_derive::DieselEnum) ] + #[diesel(sql_type = #type_name)] + #item + }) + } + StorageType::Text => Ok(quote! { + #[derive(diesel::AsExpression, diesel::FromSqlRow, router_derive::DieselEnumText) ] + #[diesel(sql_type = ::diesel::sql_types::Text)] + #item + }), + } } diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs index eb4d4a200af..89e37f74996 100644 --- a/crates/storage_models/src/enums.rs +++ b/crates/storage_models/src/enums.rs @@ -6,11 +6,11 @@ pub mod diesel_exports { DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, - DbMerchantStorageScheme as MerchantStorageScheme, DbPaymentFlow as PaymentFlow, + DbMerchantStorageScheme as MerchantStorageScheme, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentMethodSubType as PaymentMethodSubType, DbPaymentMethodType as PaymentMethodType, DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus, - DbRefundType as RefundType, DbRoutingAlgorithm as RoutingAlgorithm, + DbRefundType as RefundType, }; } @@ -25,9 +25,8 @@ pub mod diesel_exports { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AttemptStatus { @@ -66,10 +65,9 @@ pub enum AttemptStatus { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthenticationType { @@ -89,10 +87,9 @@ pub enum AuthenticationType { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CaptureMethod { @@ -113,10 +110,9 @@ pub enum CaptureMethod { strum::EnumString, serde::Deserialize, serde::Serialize, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ConnectorType { @@ -149,10 +145,9 @@ pub enum ConnectorType { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] pub enum Currency { AED, ALL, @@ -270,9 +265,8 @@ pub enum Currency { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventClass { @@ -289,9 +283,8 @@ pub enum EventClass { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventObjectType { @@ -308,10 +301,9 @@ pub enum EventObjectType { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventType { @@ -329,10 +321,9 @@ pub enum EventType { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum IntentStatus { @@ -358,10 +349,9 @@ pub enum IntentStatus { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FutureUsage { @@ -381,9 +371,8 @@ pub enum FutureUsage { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MerchantStorageScheme { @@ -392,30 +381,6 @@ pub enum MerchantStorageScheme { RedisKv, } -#[derive( - Clone, - Copy, - Debug, - Eq, - PartialEq, - strum::Display, - strum::EnumString, - serde::Serialize, - serde::Deserialize, - router_derive::DieselEnum, -)] -#[router_derive::diesel_enum] -#[strum(serialize_all = "snake_case")] -pub enum PaymentFlow { - Vsc, - Emi, - Otp, - UpiIntent, - UpiCollect, - UpiScanAndPay, - Sdk, -} - #[derive( Clone, Copy, @@ -427,10 +392,9 @@ pub enum PaymentFlow { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMethodIssuerCode { @@ -457,10 +421,9 @@ pub enum PaymentMethodIssuerCode { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodSubType { @@ -484,10 +447,9 @@ pub enum PaymentMethodSubType { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodType { @@ -517,9 +479,8 @@ pub enum PaymentMethodType { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum WalletIssuer { @@ -537,9 +498,8 @@ pub enum WalletIssuer { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ProcessTrackerStatus { @@ -566,10 +526,9 @@ pub enum ProcessTrackerStatus { serde::Deserialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[strum(serialize_all = "snake_case")] pub enum RefundStatus { Failure, @@ -591,9 +550,8 @@ pub enum RefundStatus { serde::Deserialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[strum(serialize_all = "snake_case")] pub enum RefundType { InstantRefund, @@ -602,30 +560,28 @@ pub enum RefundType { RetryRefund, } +// Mandate #[derive( Clone, Copy, Debug, Eq, PartialEq, + Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, - frunk::LabelledGeneric, )] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] -#[router_derive::diesel_enum] -pub enum RoutingAlgorithm { - RoundRobin, - MaxConversion, - MinCost, - Custom, +pub enum MandateType { + SingleUse, + #[default] + MultiUse, } -// Mandate #[derive( Clone, Copy, @@ -637,15 +593,17 @@ pub enum RoutingAlgorithm { serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, + frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "pg_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] -pub enum MandateType { - SingleUse, +pub enum MandateStatus { #[default] - MultiUse, + Active, + Inactive, + Pending, + Revoked, } #[derive( @@ -653,22 +611,56 @@ pub enum MandateType { Copy, Debug, Eq, + Hash, PartialEq, - Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, - router_derive::DieselEnum, frunk::LabelledGeneric, )] -#[router_derive::diesel_enum] +#[router_derive::diesel_enum(storage_type = "text")] +#[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] +pub enum PaymentIssuer { + Klarna, + Affirm, + AfterpayClearpay, + AmericanExpress, + BankOfAmerica, + Barclays, + CapitalOne, + Chase, + Citi, + Discover, + NavyFederalCreditUnion, + PentagonFederalCreditUnion, + SynchronyBank, + WellsFargo, +} + +#[derive( + Eq, + PartialEq, + Hash, + Clone, + Debug, + serde::Serialize, + serde::Deserialize, + Default, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, +)] +#[router_derive::diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] -pub enum MandateStatus { +#[serde(rename_all = "snake_case")] +pub enum PaymentExperience { #[default] - Active, - Inactive, - Pending, - Revoked, + RedirectToUrl, + InvokeSdkClient, + DisplayQrCode, + OneClick, + LinkWallet, + InvokePaymentApp, } diff --git a/crates/storage_models/src/payment_attempt.rs b/crates/storage_models/src/payment_attempt.rs index 93aa1d3c6c9..175e625c08c 100644 --- a/crates/storage_models/src/payment_attempt.rs +++ b/crates/storage_models/src/payment_attempt.rs @@ -22,8 +22,6 @@ pub struct PaymentAttempt { pub tax_amount: Option<i64>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethodType>, - pub payment_flow: Option<storage_enums::PaymentFlow>, - pub redirect: Option<bool>, pub connector_transaction_id: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub capture_on: Option<PrimitiveDateTime>, @@ -39,6 +37,8 @@ pub struct PaymentAttempt { pub error_code: Option<String>, pub payment_token: Option<String>, pub connector_metadata: Option<serde_json::Value>, + pub payment_issuer: Option<storage_enums::PaymentIssuer>, + pub payment_experience: Option<storage_enums::PaymentExperience>, } #[derive( @@ -61,8 +61,6 @@ pub struct PaymentAttemptNew { pub tax_amount: Option<i64>, pub payment_method_id: Option<String>, pub payment_method: Option<storage_enums::PaymentMethodType>, - pub payment_flow: Option<storage_enums::PaymentFlow>, - pub redirect: Option<bool>, pub connector_transaction_id: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub capture_on: Option<PrimitiveDateTime>, @@ -78,6 +76,8 @@ pub struct PaymentAttemptNew { pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, + pub payment_issuer: Option<storage_enums::PaymentIssuer>, + pub payment_experience: Option<storage_enums::PaymentExperience>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -117,7 +117,6 @@ pub enum PaymentAttemptUpdate { connector_transaction_id: Option<String>, authentication_type: Option<storage_enums::AuthenticationType>, payment_method_id: Option<Option<String>>, - redirect: Option<bool>, mandate_id: Option<String>, connector_metadata: Option<serde_json::Value>, }, @@ -146,7 +145,6 @@ pub struct PaymentAttemptUpdateInternal { payment_method_id: Option<Option<String>>, cancellation_reason: Option<String>, modified_at: Option<PrimitiveDateTime>, - redirect: Option<bool>, mandate_id: Option<String>, browser_info: Option<serde_json::Value>, payment_token: Option<String>, @@ -243,7 +241,6 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, authentication_type, payment_method_id, - redirect, mandate_id, connector_metadata, } => Self { @@ -253,7 +250,6 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { authentication_type, payment_method_id, modified_at: Some(common_utils::date_time::now()), - redirect, mandate_id, connector_metadata, ..Default::default() diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index d2fd26ec384..0cfed2bd421 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -219,8 +219,6 @@ diesel::table! { tax_amount -> Nullable<Int8>, payment_method_id -> Nullable<Varchar>, payment_method -> Nullable<PaymentMethodType>, - payment_flow -> Nullable<PaymentFlow>, - redirect -> Nullable<Bool>, connector_transaction_id -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, capture_on -> Nullable<Timestamp>, @@ -236,6 +234,8 @@ diesel::table! { error_code -> Nullable<Varchar>, payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, + payment_issuer -> Nullable<Varchar>, + payment_experience -> Nullable<Varchar>, } } diff --git a/migrations/2023-02-02-055700_add_payment_issuer_and_experience_in_payment_attempt/down.sql b/migrations/2023-02-02-055700_add_payment_issuer_and_experience_in_payment_attempt/down.sql new file mode 100644 index 00000000000..bc8ba15c7b5 --- /dev/null +++ b/migrations/2023-02-02-055700_add_payment_issuer_and_experience_in_payment_attempt/down.sql @@ -0,0 +1,3 @@ +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS payment_issuer; + +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS payment_experience; diff --git a/migrations/2023-02-02-055700_add_payment_issuer_and_experience_in_payment_attempt/up.sql b/migrations/2023-02-02-055700_add_payment_issuer_and_experience_in_payment_attempt/up.sql new file mode 100644 index 00000000000..0fd96f21f14 --- /dev/null +++ b/migrations/2023-02-02-055700_add_payment_issuer_and_experience_in_payment_attempt/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS payment_issuer VARCHAR(50); + +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS payment_experience VARCHAR(50); diff --git a/migrations/2023-02-02-062215_remove_redirect_and_payment_flow_from_payment_attempt/down.sql b/migrations/2023-02-02-062215_remove_redirect_and_payment_flow_from_payment_attempt/down.sql new file mode 100644 index 00000000000..67dc64c0f5f --- /dev/null +++ b/migrations/2023-02-02-062215_remove_redirect_and_payment_flow_from_payment_attempt/down.sql @@ -0,0 +1,15 @@ +CREATE TYPE "PaymentFlow" AS ENUM ( + 'vsc', + 'emi', + 'otp', + 'upi_intent', + 'upi_collect', + 'upi_scan_and_pay', + 'sdk' +); + +ALTER TABLE payment_attempt +ADD COLUMN payment_flow "PaymentFlow"; + +ALTER TABLE payment_attempt +ADD COLUMN redirect BOOLEAN; diff --git a/migrations/2023-02-02-062215_remove_redirect_and_payment_flow_from_payment_attempt/up.sql b/migrations/2023-02-02-062215_remove_redirect_and_payment_flow_from_payment_attempt/up.sql new file mode 100644 index 00000000000..e1997e0226c --- /dev/null +++ b/migrations/2023-02-02-062215_remove_redirect_and_payment_flow_from_payment_attempt/up.sql @@ -0,0 +1,5 @@ +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS redirect; + +ALTER TABLE payment_attempt DROP COLUMN IF EXISTS payment_flow; + +DROP TYPE IF EXISTS "PaymentFlow"; diff --git a/openapi/generated.json b/openapi/generated.json index 34ead266ca7..28273b8b5b9 100644 --- a/openapi/generated.json +++ b/openapi/generated.json @@ -22,9 +22,7 @@ "paths": { "/accounts": { "post": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nCreate a new account for a merchant and the merchant could be a seller or retailer or client who likes to receive and send payments.", "operationId": "Create a Merchant Account", @@ -58,9 +56,7 @@ }, "/accounts/{account_id}": { "get": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nRetrieve a merchant account details.", "operationId": "Retrieve a Merchant Account", @@ -93,9 +89,7 @@ "deprecated": false }, "post": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nTo update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc", "operationId": "Update a Merchant Account", @@ -138,9 +132,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Merchant Account" - ], + "tags": ["Merchant Account"], "summary": "", "description": "\nTo delete a merchant account", "operationId": "Delete a Merchant Account", @@ -175,9 +167,7 @@ }, "/accounts/{account_id}/connectors": { "get": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nList Payment Connector Details for the merchant", "operationId": "List all Merchant Connectors", @@ -216,9 +206,7 @@ "deprecated": false }, "post": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nCreate a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", "operationId": "Create a Merchant Connector", @@ -252,9 +240,7 @@ }, "/accounts/{account_id}/connectors/{connector_id}": { "get": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nRetrieve Payment Connector Details", "operationId": "Retrieve a Merchant Connector", @@ -300,9 +286,7 @@ "deprecated": false }, "post": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nTo update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.", "operationId": "Update a Merchant Connector", @@ -358,9 +342,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Merchant Connector Account" - ], + "tags": ["Merchant Connector Account"], "summary": "", "description": "\nDelete or Detach a Payment Connector from Merchant Account", "operationId": "Delete a Merchant Connector", @@ -609,9 +591,7 @@ }, "/customers": { "post": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nCreate a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details.", "operationId": "Create a Customer", @@ -645,9 +625,7 @@ }, "/customers/{customer_id}": { "get": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nRetrieve a customer's details.", "operationId": "Retrieve a Customer", @@ -680,9 +658,7 @@ "deprecated": false }, "post": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nUpdates the customer's details in a customer object.", "operationId": "Update a Customer", @@ -725,9 +701,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Customers" - ], + "tags": ["Customers"], "summary": "", "description": "\nDelete a customer record.", "operationId": "Delete a Customer", @@ -762,9 +736,7 @@ }, "/mandates/revoke/{mandate_id}": { "post": { - "tags": [ - "Mandates" - ], + "tags": ["Mandates"], "summary": "", "description": "\nRevoke a mandate", "operationId": "Revoke a Mandate", @@ -799,9 +771,7 @@ }, "/mandates/{mandate_id}": { "get": { - "tags": [ - "Mandates" - ], + "tags": ["Mandates"], "summary": "", "description": "\nRetrieve a mandate", "operationId": "Retrieve a Mandate", @@ -836,9 +806,7 @@ }, "/payment_methods": { "post": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants", "operationId": "Create a Payment Method", @@ -872,9 +840,7 @@ }, "/payment_methods/{account_id}": { "get": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo filter and list the applicable payment methods for a particular Merchant ID", "operationId": "List all Payment Methods for a Merchant", @@ -974,9 +940,7 @@ }, "/payment_methods/{customer_id}": { "get": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo filter and list the applicable payment methods for a particular Customer ID", "operationId": "List all Payment Methods for a Customer", @@ -1076,9 +1040,7 @@ }, "/payment_methods/{method_id}": { "get": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo retrieve a payment method", "operationId": "Retrieve a Payment method", @@ -1111,9 +1073,7 @@ "deprecated": false }, "post": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nTo update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments", "operationId": "Update a Payment method", @@ -1156,9 +1116,7 @@ "deprecated": false }, "delete": { - "tags": [ - "Payment Methods" - ], + "tags": ["Payment Methods"], "summary": "", "description": "\nDelete payment method", "operationId": "Delete a Payment method", @@ -1193,9 +1151,7 @@ }, "/payments": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture", "operationId": "Create a Payment", @@ -1229,9 +1185,7 @@ }, "/payments/list": { "get": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo list the payments", "operationId": "List all Payments", @@ -1337,9 +1291,7 @@ }, "/payments/session_tokens": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo create the session object or to get session token for wallets", "operationId": "Create Session tokens for a Payment", @@ -1373,9 +1325,7 @@ }, "/payments/{payment_id}": { "get": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment", "operationId": "Retrieve a Payment", @@ -1418,9 +1368,7 @@ "deprecated": false }, "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created", "operationId": "Update a Payment", @@ -1465,9 +1413,7 @@ }, "/payments/{payment_id}/cancel": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nA Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action", "operationId": "Cancel a Payment", @@ -1505,9 +1451,7 @@ }, "/payments/{payment_id}/capture": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nTo capture the funds for an uncaptured payment", "operationId": "Capture a Payment", @@ -1552,9 +1496,7 @@ }, "/payments/{payment_id}/confirm": { "post": { - "tags": [ - "Payments" - ], + "tags": ["Payments"], "summary": "", "description": "\nThis API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments Create API", "operationId": "Confirm a Payment", @@ -1599,9 +1541,7 @@ }, "/refunds": { "post": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo create a refund against an already processed payment", "operationId": "Create a Refund", @@ -1635,9 +1575,7 @@ }, "/refunds/list": { "get": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo list the refunds associated with a payment_id or with the merchant, if payment_id is not provided", "operationId": "List all Refunds", @@ -1732,9 +1670,7 @@ }, "/refunds/{refund_id}": { "get": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment", "operationId": "Retrieve a Refund", @@ -1767,9 +1703,7 @@ "deprecated": false }, "post": { - "tags": [ - "Refunds" - ], + "tags": ["Refunds"], "summary": "", "description": "\nTo update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields", "operationId": "Update a Refund", @@ -1817,10 +1751,7 @@ "schemas": { "AcceptanceType": { "type": "string", - "enum": [ - "online", - "offline" - ] + "enum": ["online", "offline"] }, "Address": { "type": "object", @@ -1894,15 +1825,11 @@ }, "AffirmIssuer": { "type": "string", - "enum": [ - "affirm" - ] + "enum": ["affirm"] }, "AfterpayClearpayIssuer": { "type": "string", - "enum": [ - "afterpay_clearpay" - ] + "enum": ["afterpay_clearpay"] }, "ApiKeyExpiration": { "oneOf": [ @@ -1920,19 +1847,11 @@ }, "AuthenticationType": { "type": "string", - "enum": [ - "three_ds", - "no_three_ds" - ] + "enum": ["three_ds", "no_three_ds"] }, "CaptureMethod": { "type": "string", - "enum": [ - "automatic", - "manual", - "manual_multiple", - "scheduled" - ] + "enum": ["automatic", "manual", "manual_multiple", "scheduled"] }, "Card": { "type": "object", @@ -2144,9 +2063,7 @@ }, "CreateMerchantAccount": { "type": "object", - "required": [ - "merchant_id" - ], + "required": ["merchant_id"], "properties": { "merchant_id": { "type": "string", @@ -2224,9 +2141,7 @@ }, "CreatePaymentMethod": { "type": "object", - "required": [ - "payment_method" - ], + "required": ["payment_method"], "properties": { "payment_method": { "$ref": "#/components/schemas/PaymentMethodType" @@ -2365,9 +2280,7 @@ }, "CustomerAcceptance": { "type": "object", - "required": [ - "acceptance_type" - ], + "required": ["acceptance_type"], "properties": { "acceptance_type": { "$ref": "#/components/schemas/AcceptanceType" @@ -2464,9 +2377,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] }, "card": { "$ref": "#/components/schemas/CardDetailFromLocker" @@ -2532,10 +2443,7 @@ }, "CustomerResponse": { "type": "object", - "required": [ - "customer_id", - "created_at" - ], + "required": ["customer_id", "created_at"], "properties": { "customer_id": { "type": "string", @@ -2589,11 +2497,7 @@ }, "DeleteMcaResponse": { "type": "object", - "required": [ - "merchant_id", - "merchant_connector_id", - "deleted" - ], + "required": ["merchant_id", "merchant_connector_id", "deleted"], "properties": { "merchant_id": { "type": "string", @@ -2602,10 +2506,9 @@ "maxLength": 255 }, "merchant_connector_id": { - "type": "integer", - "format": "int32", + "type": "string", "description": "Unique ID of the connector", - "example": 42 + "example": "mca_5apGeP94tMts6rg3U3kR" }, "deleted": { "type": "boolean", @@ -2616,10 +2519,7 @@ }, "DeleteMerchantAccountResponse": { "type": "object", - "required": [ - "merchant_id", - "deleted" - ], + "required": ["merchant_id", "deleted"], "properties": { "merchant_id": { "type": "string", @@ -2636,10 +2536,7 @@ }, "DeletePaymentMethodResponse": { "type": "object", - "required": [ - "payment_method_id", - "deleted" - ], + "required": ["payment_method_id", "deleted"], "properties": { "payment_method_id": { "type": "string", @@ -2655,17 +2552,11 @@ }, "FutureUsage": { "type": "string", - "enum": [ - "off_session", - "on_session" - ] + "enum": ["off_session", "on_session"] }, "GpayAllowedMethodsParameters": { "type": "object", - "required": [ - "allowed_auth_methods", - "allowed_card_networks" - ], + "required": ["allowed_auth_methods", "allowed_card_networks"], "properties": { "allowed_auth_methods": { "type": "array", @@ -2685,11 +2576,7 @@ }, "GpayAllowedPaymentMethods": { "type": "object", - "required": [ - "type", - "parameters", - "tokenization_specification" - ], + "required": ["type", "parameters", "tokenization_specification"], "properties": { "type": { "type": "string", @@ -2705,9 +2592,7 @@ }, "GpayMerchantInfo": { "type": "object", - "required": [ - "merchant_name" - ], + "required": ["merchant_name"], "properties": { "merchant_name": { "type": "string", @@ -2717,10 +2602,7 @@ }, "GpayTokenParameters": { "type": "object", - "required": [ - "gateway", - "gateway_merchant_id" - ], + "required": ["gateway", "gateway_merchant_id"], "properties": { "gateway": { "type": "string", @@ -2734,10 +2616,7 @@ }, "GpayTokenizationSpecification": { "type": "object", - "required": [ - "type", - "parameters" - ], + "required": ["type", "parameters"], "properties": { "type": { "type": "string", @@ -2791,16 +2670,11 @@ }, "KlarnaIssuer": { "type": "string", - "enum": [ - "klarna" - ] + "enum": ["klarna"] }, "ListCustomerPaymentMethodsResponse": { "type": "object", - "required": [ - "enabled_payment_methods", - "customer_payment_methods" - ], + "required": ["enabled_payment_methods", "customer_payment_methods"], "properties": { "enabled_payment_methods": { "type": "array", @@ -2811,10 +2685,7 @@ { "payment_method": "wallet", "payment_experience": null, - "payment_method_issuers": [ - "labore magna ipsum", - "aute" - ] + "payment_method_issuers": ["labore magna ipsum", "aute"] } ] }, @@ -2842,9 +2713,7 @@ "items": { "$ref": "#/components/schemas/PaymentMethodSubType" }, - "example": [ - "credit_card" - ] + "example": ["credit_card"] }, "payment_method_issuers": { "type": "array", @@ -2852,18 +2721,14 @@ "type": "string", "description": "The name of the bank/ provider issuing the payment method to the end user" }, - "example": [ - "Citibank" - ] + "example": ["Citibank"] }, "payment_method_issuer_code": { "type": "array", "items": { "$ref": "#/components/schemas/PaymentMethodIssuerCode" }, - "example": [ - "jp_applepay" - ] + "example": ["jp_applepay"] }, "payment_schemes": { "type": "array", @@ -2871,11 +2736,7 @@ "type": "string", "description": "List of payment schemes accepted or has the processing capabilities of the processor" }, - "example": [ - "MASTER", - "VISA", - "DINERS" - ] + "example": ["MASTER", "VISA", "DINERS"] }, "accepted_countries": { "type": "array", @@ -2883,21 +2744,14 @@ "type": "string", "description": "List of Countries accepted or has the processing capabilities of the processor" }, - "example": [ - "US", - "UK", - "IN" - ] + "example": ["US", "UK", "IN"] }, "accepted_currencies": { "type": "array", "items": { "$ref": "#/components/schemas/Currency" }, - "example": [ - "USD", - "EUR" - ] + "example": ["USD", "EUR"] }, "minimum_amount": { "type": "integer", @@ -2926,17 +2780,13 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] } } }, "ListPaymentMethodResponse": { "type": "object", - "required": [ - "payment_methods" - ], + "required": ["payment_methods"], "properties": { "redirect_url": { "type": "string", @@ -2952,10 +2802,7 @@ { "payment_method": "wallet", "payment_experience": null, - "payment_method_issuers": [ - "labore magna ipsum", - "aute" - ] + "payment_method_issuers": ["labore magna ipsum", "aute"] } ] } @@ -2963,10 +2810,7 @@ }, "MandateAmountData": { "type": "object", - "required": [ - "amount", - "currency" - ], + "required": ["amount", "currency"], "properties": { "amount": { "type": "integer", @@ -3018,10 +2862,7 @@ }, "MandateData": { "type": "object", - "required": [ - "customer_acceptance", - "mandate_type" - ], + "required": ["customer_acceptance", "mandate_type"], "properties": { "customer_acceptance": { "$ref": "#/components/schemas/CustomerAcceptance" @@ -3065,10 +2906,7 @@ }, "MandateRevokedResponse": { "type": "object", - "required": [ - "mandate_id", - "status" - ], + "required": ["mandate_id", "status"], "properties": { "mandate_id": { "type": "string", @@ -3082,20 +2920,13 @@ "MandateStatus": { "type": "string", "description": "The status of the mandate, which indicates whether it can be used to initiate a payment", - "enum": [ - "active", - "inactive", - "pending", - "revoked" - ] + "enum": ["active", "inactive", "pending", "revoked"] }, "MandateType": { "oneOf": [ { "type": "object", - "required": [ - "single_use" - ], + "required": ["single_use"], "properties": { "single_use": { "$ref": "#/components/schemas/MandateAmountData" @@ -3104,9 +2935,7 @@ }, { "type": "object", - "required": [ - "multi_use" - ], + "required": ["multi_use"], "properties": { "multi_use": { "$ref": "#/components/schemas/MandateAmountData" @@ -3201,17 +3030,13 @@ }, "MerchantConnectorId": { "type": "object", - "required": [ - "merchant_id", - "merchant_connector_id" - ], + "required": ["merchant_id", "merchant_connector_id"], "properties": { "merchant_id": { "type": "string" }, "merchant_connector_id": { - "type": "integer", - "format": "int32" + "type": "string" } } }, @@ -3288,9 +3113,7 @@ }, "NextAction": { "type": "object", - "required": [ - "type" - ], + "required": ["type"], "properties": { "type": { "$ref": "#/components/schemas/NextActionType" @@ -3313,10 +3136,7 @@ }, "OnlineMandate": { "type": "object", - "required": [ - "ip_address", - "user_agent" - ], + "required": ["ip_address", "user_agent"], "properties": { "ip_address": { "type": "string", @@ -3331,10 +3151,7 @@ }, "OrderDetails": { "type": "object", - "required": [ - "product_name", - "quantity" - ], + "required": ["product_name", "quantity"], "properties": { "product_name": { "type": "string", @@ -3354,22 +3171,13 @@ "oneOf": [ { "type": "object", - "required": [ - "klarna_redirect" - ], + "required": ["klarna_redirect"], "properties": { "klarna_redirect": { "type": "object", "description": "For KlarnaRedirect as PayLater Option", - "required": [ - "issuer_name", - "billing_email", - "billing_country" - ], + "required": ["billing_email", "billing_country"], "properties": { - "issuer_name": { - "$ref": "#/components/schemas/KlarnaIssuer" - }, "billing_email": { "type": "string", "description": "The billing email" @@ -3383,21 +3191,13 @@ }, { "type": "object", - "required": [ - "klarna_sdk" - ], + "required": ["klarna_sdk"], "properties": { "klarna_sdk": { "type": "object", "description": "For Klarna Sdk as PayLater Option", - "required": [ - "issuer_name", - "token" - ], + "required": ["token"], "properties": { - "issuer_name": { - "$ref": "#/components/schemas/KlarnaIssuer" - }, "token": { "type": "string", "description": "The token for the sdk workflow" @@ -3408,47 +3208,23 @@ }, { "type": "object", - "required": [ - "affirm_redirect" - ], + "required": ["affirm_redirect"], "properties": { "affirm_redirect": { "type": "object", - "description": "For Affirm redirect as PayLater Option", - "required": [ - "issuer_name", - "billing_email" - ], - "properties": { - "issuer_name": { - "$ref": "#/components/schemas/AffirmIssuer" - }, - "billing_email": { - "type": "string", - "description": "The billing email" - } - } + "description": "For Affirm redirect as PayLater Option" } } }, { "type": "object", - "required": [ - "afterpay_clearpay_redirect" - ], + "required": ["afterpay_clearpay_redirect"], "properties": { "afterpay_clearpay_redirect": { "type": "object", "description": "For AfterpayClearpay redirect as PayLater Option", - "required": [ - "issuer_name", - "billing_email", - "billing_name" - ], + "required": ["billing_email", "billing_name"], "properties": { - "issuer_name": { - "$ref": "#/components/schemas/AfterpayClearpayIssuer" - }, "billing_email": { "type": "string", "description": "The billing email" @@ -3466,10 +3242,7 @@ "PaymentConnectorCreate": { "type": "object", "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", - "required": [ - "connector_type", - "connector_name" - ], + "required": ["connector_type", "connector_name"], "properties": { "connector_type": { "$ref": "#/components/schemas/ConnectorType" @@ -3480,10 +3253,9 @@ "example": "stripe" }, "merchant_connector_id": { - "type": "integer", - "format": "int32", + "type": "string", "description": "Unique ID of the connector", - "example": 42 + "example": "mca_5apGeP94tMts6rg3U3kR" }, "connector_account_details": { "type": "object" @@ -3508,26 +3280,11 @@ "example": [ { "payment_method": "wallet", - "payment_method_types": [ - "upi_collect", - "upi_intent" - ], - "payment_method_issuers": [ - "labore magna ipsum", - "aute" - ], - "payment_schemes": [ - "Discover", - "Discover" - ], - "accepted_currencies": [ - "AED", - "AED" - ], - "accepted_countries": [ - "in", - "us" - ], + "payment_method_types": ["upi_collect", "upi_intent"], + "payment_method_issuers": ["labore magna ipsum", "aute"], + "payment_schemes": ["Discover", "Discover"], + "accepted_currencies": ["AED", "AED"], + "accepted_countries": ["in", "us"], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, @@ -3555,9 +3312,7 @@ "oneOf": [ { "type": "object", - "required": [ - "PaymentIntentId" - ], + "required": ["PaymentIntentId"], "properties": { "PaymentIntentId": { "type": "string", @@ -3567,9 +3322,7 @@ }, { "type": "object", - "required": [ - "ConnectorTransactionId" - ], + "required": ["ConnectorTransactionId"], "properties": { "ConnectorTransactionId": { "type": "string", @@ -3579,9 +3332,7 @@ }, { "type": "object", - "required": [ - "PaymentAttemptId" - ], + "required": ["PaymentAttemptId"], "properties": { "PaymentAttemptId": { "type": "string", @@ -3591,6 +3342,25 @@ } ] }, + "PaymentIssuer": { + "type": "string", + "enum": [ + "klarna", + "affirm", + "afterpay_clearpay", + "american_express", + "bank_of_america", + "barclays", + "capital_one", + "chase", + "citi", + "discover", + "navy_federal_credit_union", + "pentagon_federal_credit_union", + "synchrony_bank", + "wells_fargo" + ] + }, "PaymentListConstraints": { "type": "object", "properties": { @@ -3640,10 +3410,7 @@ }, "PaymentListResponse": { "type": "object", - "required": [ - "size", - "data" - ], + "required": ["size", "data"], "properties": { "size": { "type": "integer", @@ -3661,9 +3428,7 @@ "oneOf": [ { "type": "object", - "required": [ - "card" - ], + "required": ["card"], "properties": { "card": { "$ref": "#/components/schemas/Card" @@ -3672,15 +3437,11 @@ }, { "type": "string", - "enum": [ - "bank_transfer" - ] + "enum": ["bank_transfer"] }, { "type": "object", - "required": [ - "wallet" - ], + "required": ["wallet"], "properties": { "wallet": { "$ref": "#/components/schemas/WalletData" @@ -3689,9 +3450,7 @@ }, { "type": "object", - "required": [ - "pay_later" - ], + "required": ["pay_later"], "properties": { "pay_later": { "$ref": "#/components/schemas/PayLaterData" @@ -3700,9 +3459,7 @@ }, { "type": "string", - "enum": [ - "paypal" - ] + "enum": ["paypal"] } ] }, @@ -3778,9 +3535,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] }, "metadata": { "type": "object" @@ -3838,9 +3593,7 @@ "items": { "$ref": "#/components/schemas/PaymentMethodSubType" }, - "example": [ - "credit" - ] + "example": ["credit"] }, "payment_method_issuers": { "type": "array", @@ -3848,9 +3601,7 @@ "type": "string", "description": "List of payment method issuers to be enabled for this payment method" }, - "example": [ - "HDFC" - ] + "example": ["HDFC"] }, "payment_schemes": { "type": "array", @@ -3858,22 +3609,14 @@ "type": "string", "description": "List of payment schemes accepted or has the processing capabilities of the processor" }, - "example": [ - "MASTER", - "VISA", - "DINERS" - ] + "example": ["MASTER", "VISA", "DINERS"] }, "accepted_currencies": { "type": "array", "items": { "$ref": "#/components/schemas/Currency" }, - "example": [ - "USD", - "EUR", - "AED" - ] + "example": ["USD", "EUR", "AED"] }, "accepted_countries": { "type": "array", @@ -3881,10 +3624,7 @@ "type": "string", "description": "List of Countries accepted or has the processing capabilities of the processor" }, - "example": [ - "US", - "IN" - ] + "example": ["US", "IN"] }, "minimum_amount": { "type": "integer", @@ -3915,9 +3655,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, - "example": [ - "redirect_to_url" - ] + "example": ["redirect_to_url"] } } }, @@ -4125,17 +3863,18 @@ }, "browser_info": { "type": "object" + }, + "payment_issuer": { + "$ref": "#/components/schemas/PaymentIssuer" + }, + "payment_experience": { + "$ref": "#/components/schemas/PaymentExperience" } } }, "PaymentsResponse": { "type": "object", - "required": [ - "status", - "amount", - "currency", - "payment_method" - ], + "required": ["status", "amount", "currency", "payment_method"], "properties": { "payment_id": { "type": "string", @@ -4314,10 +4053,7 @@ }, "PaymentsRetrieveRequest": { "type": "object", - "required": [ - "resource_id", - "force_sync" - ], + "required": ["resource_id", "force_sync"], "properties": { "resource_id": { "$ref": "#/components/schemas/PaymentIdType" @@ -4342,11 +4078,7 @@ }, "PaymentsSessionRequest": { "type": "object", - "required": [ - "payment_id", - "client_secret", - "wallets" - ], + "required": ["payment_id", "client_secret", "wallets"], "properties": { "payment_id": { "type": "string", @@ -4366,11 +4098,7 @@ }, "PaymentsSessionResponse": { "type": "object", - "required": [ - "payment_id", - "client_secret", - "session_token" - ], + "required": ["payment_id", "client_secret", "session_token"], "properties": { "payment_id": { "type": "string", @@ -4390,11 +4118,7 @@ }, "PaymentsStartRequest": { "type": "object", - "required": [ - "payment_id", - "merchant_id", - "attempt_id" - ], + "required": ["payment_id", "merchant_id", "attempt_id"], "properties": { "payment_id": { "type": "string", @@ -4466,9 +4190,7 @@ }, "RefundListResponse": { "type": "object", - "required": [ - "data" - ], + "required": ["data"], "properties": { "data": { "type": "array", @@ -4480,9 +4202,7 @@ }, "RefundRequest": { "type": "object", - "required": [ - "payment_id" - ], + "required": ["payment_id"], "properties": { "refund_id": { "type": "string", @@ -4527,13 +4247,7 @@ }, "RefundResponse": { "type": "object", - "required": [ - "refund_id", - "payment_id", - "amount", - "currency", - "status" - ], + "required": ["refund_id", "payment_id", "amount", "currency", "status"], "properties": { "refund_id": { "type": "string", @@ -4585,19 +4299,11 @@ "RefundStatus": { "type": "string", "description": "The status for refunds", - "enum": [ - "succeeded", - "failed", - "pending", - "review" - ] + "enum": ["succeeded", "failed", "pending", "review"] }, "RefundType": { "type": "string", - "enum": [ - "scheduled", - "instant" - ] + "enum": ["scheduled", "instant"] }, "RefundUpdateRequest": { "type": "object", @@ -4689,12 +4395,7 @@ "RoutingAlgorithm": { "type": "string", "description": "The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'", - "enum": [ - "round_robin", - "max_conversion", - "min_cost", - "custom" - ], + "enum": ["round_robin", "max_conversion", "min_cost", "custom"], "example": "custom" }, "SessionToken": { @@ -4723,20 +4424,14 @@ }, "wallet_name": { "type": "string", - "enum": [ - "gpay" - ] + "enum": ["gpay"] } } }, { "type": "object", "description": "The session response structure for Klarna", - "required": [ - "session_token", - "session_id", - "wallet_name" - ], + "required": ["session_token", "session_id", "wallet_name"], "properties": { "session_token": { "type": "string", @@ -4748,19 +4443,14 @@ }, "wallet_name": { "type": "string", - "enum": [ - "klarna" - ] + "enum": ["klarna"] } } }, { "type": "object", "description": "The session response structure for PayPal", - "required": [ - "session_token", - "wallet_name" - ], + "required": ["session_token", "wallet_name"], "properties": { "session_token": { "type": "string", @@ -4768,9 +4458,7 @@ }, "wallet_name": { "type": "string", - "enum": [ - "paypal" - ] + "enum": ["paypal"] } } }, @@ -4841,9 +4529,7 @@ }, "wallet_name": { "type": "string", - "enum": [ - "applepay" - ] + "enum": ["applepay"] } } } @@ -4855,12 +4541,7 @@ "SupportedWallets": { "type": "string", "description": "Wallets which support obtaining session object", - "enum": [ - "paypal", - "apple_pay", - "klarna", - "gpay" - ] + "enum": ["paypal", "apple_pay", "klarna", "gpay"] }, "UpdateApiKeyRequest": { "type": "object", @@ -4896,9 +4577,7 @@ }, "WalletData": { "type": "object", - "required": [ - "issuer_name" - ], + "required": ["issuer_name"], "properties": { "issuer_name": { "$ref": "#/components/schemas/WalletIssuer" @@ -4911,11 +4590,7 @@ }, "WalletIssuer": { "type": "string", - "enum": [ - "googlepay", - "applepay", - "paypal" - ] + "enum": ["googlepay", "applepay", "paypal"] }, "WebhookDetails": { "type": "object", @@ -4996,4 +4671,4 @@ "description": "Create and manage API Keys" } ] -} \ No newline at end of file +}
refactor
add payment_issuer and payment_experience in pa (#491)
6808272de305c685b7cf948060f006d39cbac60b
2024-11-12 16:23:00
Kashif
refactor: move Payout traits to hyperswitch_interfaces for connectors crate (#6481)
false
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 418d58eb54b..81c079d5d52 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -1049,6 +1049,56 @@ default_imp_for_file_upload!( connectors::Zsl ); +macro_rules! default_imp_for_payouts { + ($($path:ident::$connector:ident),*) => { + $( + impl api::Payouts for $path::$connector {} + )* + }; +} + +default_imp_for_payouts!( + connectors::Airwallex, + connectors::Amazonpay, + connectors::Bambora, + connectors::Billwerk, + connectors::Bitpay, + connectors::Cashtocode, + connectors::Cryptopay, + connectors::Coinbase, + connectors::Deutschebank, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Elavon, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Fiuu, + connectors::Forte, + connectors::Globepay, + connectors::Helcim, + connectors::Jpmorgan, + connectors::Mollie, + connectors::Multisafepay, + connectors::Nexinets, + connectors::Nexixpay, + connectors::Nomupay, + connectors::Novalnet, + connectors::Payeezy, + connectors::Payu, + connectors::Powertranz, + connectors::Razorpay, + connectors::Shift4, + connectors::Square, + connectors::Stax, + connectors::Taxjar, + connectors::Tsys, + connectors::Volt, + connectors::Worldline, + connectors::Worldpay, + connectors::Zen, + connectors::Zsl +); + #[cfg(feature = "payouts")] macro_rules! default_imp_for_payouts_create { ($($path:ident::$connector:ident),*) => { diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs index 7205865f24a..0ea8996cb4c 100644 --- a/crates/hyperswitch_interfaces/src/api.rs +++ b/crates/hyperswitch_interfaces/src/api.rs @@ -38,6 +38,8 @@ use masking::Maskable; use router_env::metrics::add_attributes; use serde_json::json; +#[cfg(feature = "payouts")] +pub use self::payouts::*; pub use self::{payments::*, refunds::*}; use crate::{ configs::Connectors, connector_integration_v2::ConnectorIntegrationV2, consts, errors, @@ -410,3 +412,7 @@ pub trait ConnectorRedirectResponse { Ok(CallConnectorAction::Avoid) } } + +/// Empty trait for when payouts feature is disabled +#[cfg(not(feature = "payouts"))] +pub trait Payouts {} diff --git a/crates/hyperswitch_interfaces/src/api/payouts.rs b/crates/hyperswitch_interfaces/src/api/payouts.rs index 894f636707a..5fc0280f19c 100644 --- a/crates/hyperswitch_interfaces/src/api/payouts.rs +++ b/crates/hyperswitch_interfaces/src/api/payouts.rs @@ -1,13 +1,15 @@ //! Payouts interface -use hyperswitch_domain_models::router_flow_types::payouts::{ - PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, -}; -#[cfg(feature = "payouts")] use hyperswitch_domain_models::{ - router_request_types::PayoutsData, router_response_types::PayoutsResponseData, + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, + router_response_types::PayoutsResponseData, }; +use super::ConnectorCommon; use crate::api::ConnectorIntegration; /// trait PayoutCancel @@ -42,3 +44,17 @@ pub trait PayoutRecipientAccount: /// trait PayoutSync pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {} + +/// trait Payouts +pub trait Payouts: + ConnectorCommon + + PayoutCancel + + PayoutCreate + + PayoutEligibility + + PayoutFulfill + + PayoutQuote + + PayoutRecipient + + PayoutRecipientAccount + + PayoutSync +{ +} diff --git a/crates/hyperswitch_interfaces/src/api/payouts_v2.rs b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs index 40e0726ce80..9027152f02d 100644 --- a/crates/hyperswitch_interfaces/src/api/payouts_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs @@ -1,13 +1,15 @@ //! Payouts V2 interface -use hyperswitch_domain_models::router_flow_types::payouts::{ - PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, -}; -#[cfg(feature = "payouts")] use hyperswitch_domain_models::{ - router_data_v2::flow_common_types::PayoutFlowData, router_request_types::PayoutsData, + router_data_v2::flow_common_types::PayoutFlowData, + router_flow_types::payouts::{ + PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, + PoSync, + }, + router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; +use super::ConnectorCommon; use crate::api::ConnectorIntegrationV2; /// trait PayoutCancelV2 @@ -57,3 +59,21 @@ pub trait PayoutSyncV2: ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData> { } + +/// trait Payouts +pub trait PayoutsV2: + ConnectorCommon + + PayoutCancelV2 + + PayoutCreateV2 + + PayoutEligibilityV2 + + PayoutFulfillV2 + + PayoutQuoteV2 + + PayoutRecipientV2 + + PayoutRecipientAccountV2 + + PayoutSyncV2 +{ +} + +/// Empty trait for when payouts feature is disabled +#[cfg(not(feature = "payouts"))] +pub trait PayoutsV2 {} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index a6894502996..1358bcedba1 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -12,6 +12,7 @@ pub mod session_update_flow; pub mod setup_mandate_flow; use async_trait::async_trait; +use hyperswitch_interfaces::api::payouts::Payouts; #[cfg(feature = "frm")] use crate::types::fraud_check as frm_types; @@ -969,88 +970,49 @@ default_imp_for_post_processing_steps!( macro_rules! default_imp_for_payouts { ($($path:ident::$connector:ident),*) => { $( - impl api::Payouts for $path::$connector {} + impl Payouts for $path::$connector {} )* }; } #[cfg(feature = "dummy_connector")] -impl<const T: u8> api::Payouts for connector::DummyConnector<T> {} +impl<const T: u8> Payouts for connector::DummyConnector<T> {} default_imp_for_payouts!( connector::Aci, - connector::Airwallex, - connector::Amazonpay, connector::Authorizedotnet, - connector::Bambora, connector::Bamboraapac, connector::Bankofamerica, - connector::Billwerk, - connector::Bitpay, connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, - connector::Deutschebank, - connector::Digitalvirgo, - connector::Dlocal, - connector::Elavon, - connector::Fiserv, - connector::Fiservemea, - connector::Fiuu, - connector::Forte, connector::Globalpay, - connector::Globepay, connector::Gocardless, connector::Gpayments, - connector::Helcim, connector::Iatapay, connector::Itaubank, - connector::Jpmorgan, connector::Klarna, connector::Mifinity, - connector::Mollie, - connector::Multisafepay, connector::Netcetera, - connector::Nexinets, - connector::Nexixpay, connector::Nmi, - connector::Nomupay, connector::Noon, - connector::Novalnet, connector::Nuvei, connector::Opayo, connector::Opennode, connector::Paybox, - connector::Payeezy, connector::Payme, - connector::Payu, connector::Placetopay, connector::Plaid, - connector::Powertranz, connector::Prophetpay, connector::Rapyd, - connector::Razorpay, connector::Riskified, - connector::Shift4, connector::Signifyd, - connector::Square, - connector::Stax, - connector::Taxjar, connector::Threedsecureio, connector::Trustpay, - connector::Tsys, - connector::Volt, connector::Wellsfargo, - connector::Wellsfargopayout, - connector::Worldline, - connector::Worldpay, - connector::Zen, - connector::Zsl + connector::Wellsfargopayout ); #[cfg(feature = "payouts")] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e3c311710d5..985a6644524 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -568,25 +568,6 @@ pub trait FraudCheck {} #[cfg(not(feature = "frm"))] pub trait FraudCheckV2 {} -#[cfg(feature = "payouts")] -pub trait Payouts: - ConnectorCommon - + PayoutCancel - + PayoutCreate - + PayoutEligibility - + PayoutFulfill - + PayoutQuote - + PayoutRecipient - + PayoutRecipientAccount - + PayoutSync -{ -} -#[cfg(not(feature = "payouts"))] -pub trait Payouts {} - -#[cfg(not(feature = "payouts"))] -pub trait PayoutsV2 {} - #[cfg(test)] mod test { #![allow(clippy::unwrap_used)] diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs index a9630beb25a..b5a6ac24ca9 100644 --- a/crates/router/src/types/api/payouts.rs +++ b/crates/router/src/types/api/payouts.rs @@ -11,7 +11,7 @@ pub use hyperswitch_domain_models::router_flow_types::payouts::{ }; pub use hyperswitch_interfaces::api::payouts::{ PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient, - PayoutRecipientAccount, PayoutSync, + PayoutRecipientAccount, PayoutSync, Payouts, }; pub use super::payouts_v2::{
refactor
move Payout traits to hyperswitch_interfaces for connectors crate (#6481)
db3d31647adcf794db98d746514b6c556b52eb95
2023-03-15 17:24:35
Manoj Ghorela
feat: Time based deletion of temp card (#729)
false
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 029c00019b0..7ce5f01ee80 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -549,7 +549,7 @@ pub struct GetTokenizePayloadRequest { pub get_value2: bool, } -#[derive(Debug, serde::Serialize)] +#[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct DeleteTokenizeByTokenRequest { pub lookup_key: String, pub service_name: String, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index bef8005fedf..9929059d8ca 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -18,6 +18,8 @@ use common_utils::{ use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; +#[cfg(feature = "basilisk")] +use crate::scheduler::metrics; use crate::{ configs::settings, core::{ @@ -1623,7 +1625,15 @@ impl BasiliskCardSupport { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Wrapped value2 construction failed when saving card to locker")?; - vault::create_tokenize(state, value1, Some(value2), payment_token.to_string()).await?; + let lookup_key = + vault::create_tokenize(state, value1, Some(value2), payment_token.to_string()).await?; + vault::add_delete_tokenized_data_task( + &*state.store, + &lookup_key, + enums::PaymentMethod::Card, + ) + .await?; + metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]); Ok(card) } } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 6796a906937..0c994dc20e3 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -5,13 +5,14 @@ use josekit::jwe; use masking::PeekInterface; use router_env::{instrument, tracing}; -#[cfg(not(feature = "basilisk"))] -use crate::types::storage; use crate::{ configs::settings::Jwekey, core::errors::{self, CustomResult, RouterResult}, logger, routes, - types::api, + types::{ + api, + storage::{self, enums}, + }, utils::{self, StringExt}, }; #[cfg(feature = "basilisk")] @@ -21,6 +22,12 @@ use crate::{ utils::BytesExt, }; #[cfg(feature = "basilisk")] +use crate::{ + db, + scheduler::{metrics, process_data, utils as process_tracker_utils}, + types::storage::ProcessTrackerExt, +}; +#[cfg(feature = "basilisk")] const VAULT_SERVICE_NAME: &str = "CARD"; #[cfg(feature = "basilisk")] const VAULT_VERSION: &str = "0"; @@ -257,6 +264,7 @@ impl Vault { token_id: Option<String>, payment_method: &api::PaymentMethodData, customer_id: Option<String>, + _pm: enums::PaymentMethod, ) -> RouterResult<String> { let value1 = payment_method .get_value1(customer_id.clone()) @@ -343,6 +351,7 @@ impl Vault { token_id: Option<String>, payment_method: &api::PaymentMethodData, customer_id: Option<String>, + pm: enums::PaymentMethod, ) -> RouterResult<String> { let value1 = payment_method .get_value1(customer_id.clone()) @@ -356,7 +365,10 @@ impl Vault { let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token")); - create_tokenize(state, value1, Some(value2), lookup_key).await + let lookup_key = create_tokenize(state, value1, Some(value2), lookup_key).await?; + add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?; + metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]); + Ok(lookup_key) } #[instrument(skip_all)] @@ -644,3 +656,137 @@ pub async fn delete_tokenized_data( .attach_printable(format!("Got 4xx from the basilisk locker: {err:?}")), } } + +// ********************************************** PROCESS TRACKER ********************************************** +#[cfg(feature = "basilisk")] +pub async fn add_delete_tokenized_data_task( + db: &dyn db::StorageInterface, + lookup_key: &str, + pm: enums::PaymentMethod, +) -> RouterResult<storage::ProcessTracker> { + let runner = "DELETE_TOKENIZE_DATA_WORKFLOW"; + let current_time = common_utils::date_time::now(); + let tracking_data = serde_json::to_value(storage::TokenizeCoreWorkflow { + lookup_key: lookup_key.to_owned(), + pm, + }) + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| format!("unable to convert into value {:?}", lookup_key))?; + + let schedule_time = get_delete_tokenize_schedule_time(db, &pm, 0).await; + + let process_tracker_entry = storage::ProcessTrackerNew { + id: format!("{}_{}", runner, lookup_key), + name: Some(String::from(runner)), + tag: vec![String::from("BASILISK-V3")], + runner: Some(String::from(runner)), + retry_count: 0, + schedule_time, + rule: String::new(), + tracking_data, + business_status: String::from("Pending"), + status: enums::ProcessTrackerStatus::New, + event: vec![], + created_at: current_time, + updated_at: current_time, + }; + let response = db + .insert_process(process_tracker_entry) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Failed while inserting task in process_tracker: lookup_key: {}", + lookup_key + ) + })?; + Ok(response) +} + +#[cfg(feature = "basilisk")] +pub async fn start_tokenize_data_workflow( + state: &routes::AppState, + tokenize_tracker: &storage::ProcessTracker, +) -> Result<(), errors::ProcessTrackerError> { + let db = &*state.store; + let delete_tokenize_data = serde_json::from_value::<storage::TokenizeCoreWorkflow>( + tokenize_tracker.tracking_data.clone(), + ) + .into_report() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "unable to convert into DeleteTokenizeByTokenRequest {:?}", + tokenize_tracker.tracking_data + ) + })?; + + let delete_resp = delete_tokenized_data(state, &delete_tokenize_data.lookup_key).await; + match delete_resp { + Ok(resp) => { + if resp == "Ok" { + logger::info!("Card From locker deleted Successfully"); + //mark task as finished + let id = tokenize_tracker.id.clone(); + tokenize_tracker + .clone() + .finish_with_status(db, format!("COMPLETED_BY_PT_{id}")) + .await?; + } else { + logger::error!("Error: Deleting Card From Locker : {}", resp); + retry_delete_tokenize(db, &delete_tokenize_data.pm, tokenize_tracker.to_owned()) + .await?; + metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]); + } + } + Err(err) => { + logger::error!("Err: Deleting Card From Locker : {}", err); + retry_delete_tokenize(db, &delete_tokenize_data.pm, tokenize_tracker.to_owned()) + .await?; + metrics::RETRIED_DELETE_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]); + } + } + Ok(()) +} + +#[cfg(feature = "basilisk")] +pub async fn get_delete_tokenize_schedule_time( + db: &dyn db::StorageInterface, + pm: &enums::PaymentMethod, + retry_count: i32, +) -> Option<time::PrimitiveDateTime> { + let redis_mapping = db::get_and_deserialize_key( + db, + &format!("pt_mapping_delete_{pm}_tokenize_data"), + "PaymentMethodsPTMapping", + ) + .await; + let mapping = match redis_mapping { + Ok(x) => x, + Err(err) => { + logger::info!("Redis Mapping Error: {}", err); + process_data::PaymentMethodsPTMapping::default() + } + }; + let time_delta = process_tracker_utils::get_pm_schedule_time(mapping, pm, retry_count + 1); + + process_tracker_utils::get_time_from_delta(time_delta) +} + +#[cfg(feature = "basilisk")] +pub async fn retry_delete_tokenize( + db: &dyn db::StorageInterface, + pm: &enums::PaymentMethod, + pt: storage::ProcessTracker, +) -> Result<(), errors::ProcessTrackerError> { + let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await; + + match schedule_time { + Some(s_time) => pt.retry(db, s_time).await, + None => { + pt.finish_with_status(db, "RETRIES_EXCEEDED".to_string()) + .await + } + } +} diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c1d29377ae9..8901eb20854 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -5,6 +5,7 @@ use common_utils::{ext_traits::AsyncExt, fp_utils}; use error_stack::{report, IntoReport, ResultExt}; use masking::ExposeOptionInterface; use router_env::{instrument, tracing}; +use storage_models::enums; use uuid::Uuid; use super::{ @@ -736,6 +737,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( Some(token), &updated_pm, payment_data.payment_intent.customer_id.to_owned(), + enums::PaymentMethod::Card, ) .await?; Some(updated_pm) @@ -757,6 +759,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( Some(token), &updated_pm, payment_data.payment_intent.customer_id.to_owned(), + enums::PaymentMethod::Wallet, ) .await?; Some(updated_pm) @@ -779,6 +782,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( None, pm, payment_data.payment_intent.customer_id.to_owned(), + enums::PaymentMethod::Card, ) .await?; payment_data.token = Some(token); @@ -792,6 +796,7 @@ pub async fn make_pm_data<'a, F: Clone, R>( None, pm, payment_data.payment_intent.customer_id.to_owned(), + enums::PaymentMethod::Wallet, ) .await?; payment_data.token = Some(token); diff --git a/crates/router/src/scheduler/metrics.rs b/crates/router/src/scheduler/metrics.rs index 3fe40a6d32e..ec23bc077d0 100644 --- a/crates/router/src/scheduler/metrics.rs +++ b/crates/router/src/scheduler/metrics.rs @@ -28,3 +28,5 @@ create_counter!(TASK_CONSUMED, PT_METER); // Tasks consumed by consumer create_counter!(TASK_PROCESSED, PT_METER); // Tasks completed processing create_counter!(TASK_FINISHED, PT_METER); // Tasks finished create_counter!(TASK_RETRIED, PT_METER); // Tasks added for retries +create_counter!(TOKENIZED_DATA_COUNT, PT_METER); // Tokenized data added +create_counter!(RETRIED_DELETE_DATA_COUNT, PT_METER); // Tokenized data retried diff --git a/crates/router/src/scheduler/types/process_data.rs b/crates/router/src/scheduler/types/process_data.rs index ddd007edcc5..589d54ebfe4 100644 --- a/crates/router/src/scheduler/types/process_data.rs +++ b/crates/router/src/scheduler/types/process_data.rs @@ -2,8 +2,7 @@ use std::collections::HashMap; use serde::{Deserialize, Serialize}; -use crate::types::storage::process_tracker::ProcessTracker; - +use crate::types::storage::{enums, process_tracker::ProcessTracker}; #[derive(Debug, Clone)] pub struct ProcessData { db_name: String, @@ -39,3 +38,25 @@ impl Default for ConnectorPTMapping { } } } + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentMethodsPTMapping { + pub default_mapping: RetryMapping, + pub custom_pm_mapping: HashMap<enums::PaymentMethod, RetryMapping>, + pub max_retries_count: i32, +} + +impl Default for PaymentMethodsPTMapping { + fn default() -> Self { + Self { + custom_pm_mapping: HashMap::new(), + default_mapping: RetryMapping { + start_after: 900, + frequency: vec![300], + count: vec![5], + }, + max_retries_count: 5, + } + } +} diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs index 866ff0c6c0a..85429d47aaa 100644 --- a/crates/router/src/scheduler/utils.rs +++ b/crates/router/src/scheduler/utils.rs @@ -17,7 +17,10 @@ use crate::{ logger, routes::AppState, scheduler::{ProcessTrackerBatch, SchedulerFlow}, - types::storage::{self, enums::ProcessTrackerStatus}, + types::storage::{ + self, + enums::{self, ProcessTrackerStatus}, + }, utils::{OptionExt, StringExt}, }; @@ -314,6 +317,26 @@ pub fn get_schedule_time( } } +pub fn get_pm_schedule_time( + mapping: process_data::PaymentMethodsPTMapping, + pm: &enums::PaymentMethod, + retry_count: i32, +) -> Option<i32> { + let mapping = match mapping.custom_pm_mapping.get(pm) { + Some(map) => map.clone(), + None => mapping.default_mapping, + }; + + if retry_count == 0 { + Some(mapping.start_after) + } else { + get_delay( + retry_count, + mapping.count.iter().zip(mapping.frequency.iter()), + ) + } +} + fn get_delay<'a>( retry_count: i32, mut array: impl Iterator<Item = (&'a i32, &'a i32)>, diff --git a/crates/router/src/scheduler/workflows.rs b/crates/router/src/scheduler/workflows.rs index 98427bed88f..09085bb59cc 100644 --- a/crates/router/src/scheduler/workflows.rs +++ b/crates/router/src/scheduler/workflows.rs @@ -6,6 +6,7 @@ use strum::EnumString; use crate::{core::errors, routes::AppState, scheduler::consumer, types::storage}; pub mod payment_sync; pub mod refund_router; +pub mod tokenized_data; macro_rules! runners { ($($body:tt),*) => { @@ -44,7 +45,8 @@ macro_rules! as_item { runners! { PaymentsSyncWorkflow, - RefundWorkflowRouter + RefundWorkflowRouter, + DeleteTokenizeDataWorkflow } #[async_trait] diff --git a/crates/router/src/scheduler/workflows/tokenized_data.rs b/crates/router/src/scheduler/workflows/tokenized_data.rs new file mode 100644 index 00000000000..8fdd9b2911e --- /dev/null +++ b/crates/router/src/scheduler/workflows/tokenized_data.rs @@ -0,0 +1,35 @@ +use super::{DeleteTokenizeDataWorkflow, ProcessTrackerWorkflow}; +#[cfg(feature = "basilisk")] +use crate::core::payment_methods::vault; +use crate::{errors, logger::error, routes::AppState, types::storage}; + +#[async_trait::async_trait] +impl ProcessTrackerWorkflow for DeleteTokenizeDataWorkflow { + #[cfg(feature = "basilisk")] + async fn execute_workflow<'a>( + &'a self, + state: &'a AppState, + process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + Ok(vault::start_tokenize_data_workflow(state, &process).await?) + } + + #[cfg(not(feature = "basilisk"))] + async fn execute_workflow<'a>( + &'a self, + _state: &'a AppState, + _process: storage::ProcessTracker, + ) -> Result<(), errors::ProcessTrackerError> { + Ok(()) + } + + async fn error_handler<'a>( + &'a self, + _state: &'a AppState, + process: storage::ProcessTracker, + _error: errors::ProcessTrackerError, + ) -> errors::CustomResult<(), errors::ProcessTrackerError> { + error!(%process.id, "Failed while executing workflow"); + Ok(()) + } +} diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index e66b2cd2eff..29e8241c1b2 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -1 +1 @@ -pub use storage_models::payment_method::{PaymentMethod, PaymentMethodNew}; +pub use storage_models::payment_method::{PaymentMethod, PaymentMethodNew, TokenizeCoreWorkflow}; diff --git a/crates/storage_models/src/payment_method.rs b/crates/storage_models/src/payment_method.rs index 1e1068f08af..e9c0a35378a 100644 --- a/crates/storage_models/src/payment_method.rs +++ b/crates/storage_models/src/payment_method.rs @@ -1,6 +1,7 @@ use common_utils::pii; use diesel::{Identifiable, Insertable, Queryable}; use masking::Secret; +use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payment_methods}; @@ -86,3 +87,9 @@ impl Default for PaymentMethodNew { } } } + +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] +pub struct TokenizeCoreWorkflow { + pub lookup_key: String, + pub pm: storage_enums::PaymentMethod, +}
feat
Time based deletion of temp card (#729)
beb038404727a9bbeb79d6fa9cbae1a9059078bf
2023-01-17 19:13:16
Sanchith Hegde
refactor: move config defaults from TOML files to `Default` trait (#352)
false
diff --git a/Cargo.lock b/Cargo.lock index 91cb3196ae0..acfab2b85d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1223,6 +1223,7 @@ version = "0.1.0" dependencies = [ "async-bb8-diesel", "bb8", + "common_utils", "config", "diesel", "error-stack", diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 76162a12d77..474e4b026be 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -353,3 +353,34 @@ impl<A: Send, B> AsyncExt<A, B> for Option<A> { } } } + +/// Extension trait for validating application configuration. This trait provides utilities to +/// check whether the value is either the default value or is empty. +pub trait ConfigExt { + /// Returns whether the value of `self` is the default value for `Self`. + fn is_default(&self) -> bool + where + Self: Default + PartialEq<Self>, + { + *self == Self::default() + } + + /// Returns whether the value of `self` is empty after trimming whitespace on both left and + /// right ends. + fn is_empty_after_trim(&self) -> bool; + + /// Returns whether the value of `self` is the default value for `Self` or empty after trimming + /// whitespace on both left and right ends. + fn is_default_or_empty(&self) -> bool + where + Self: Default + PartialEq<Self>, + { + self.is_default() || self.is_empty_after_trim() + } +} + +impl ConfigExt for String { + fn is_empty_after_trim(&self) -> bool { + self.trim().is_empty() + } +} diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 8af51c7e02c..51bb487c44e 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -21,6 +21,7 @@ thiserror = "1.0.38" tokio = { version = "1.24.1", features = ["macros", "rt-multi-thread"] } # First Party Crates +common_utils = { version = "0.1.0", path = "../common_utils" } redis_interface = { version = "0.1.0", path = "../redis_interface" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } storage_models = { version = "0.1.0", path = "../storage_models", features = ["kv_store"] } diff --git a/crates/drainer/src/defaults.toml b/crates/drainer/src/defaults.toml deleted file mode 100644 index 4a4a9de2b7e..00000000000 --- a/crates/drainer/src/defaults.toml +++ /dev/null @@ -1,26 +0,0 @@ -# log defaults in /crates/router_env/src/defaults.toml - -[master_database] -username = "none" -password = "none" -host = "localhost" -port = 5432 -dbname = "none" -pool_size = 5 - -[redis] -host = "127.0.0.1" -port = 6379 -pool_size = 5 -reconnect_max_attempts = 5 -reconnect_delay = 5 -default_ttl = 300 -stream_read_count = 1 -cluster_enabled = false -use_legacy_version = false -cluster_urls = [] - -[drainer] -stream_name = "DRAINER_STREAM" -num_partitions = 64 -max_read_count = 100 diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 44755443342..000cf561882 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -9,6 +9,9 @@ async fn main() -> DrainerResult<()> { #[allow(clippy::expect_used)] let conf = settings::Settings::with_config_path(cmd_line.config_path) .expect("Unable to construct application configuration"); + #[allow(clippy::expect_used)] + conf.validate() + .expect("Failed to validate drainer configuration"); let store = services::Store::new(&conf, false).await; let store = std::sync::Arc::new(store); diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index f9e95791c43..d7ee482f4cb 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -1,6 +1,7 @@ use std::path::PathBuf; -use config::{Environment, File, FileFormat}; +use common_utils::ext_traits::ConfigExt; +use config::{Environment, File}; use redis_interface as redis; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use router_env::{env, logger}; @@ -18,7 +19,8 @@ pub struct CmdLineConf { pub config_path: Option<PathBuf>, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct Settings { pub master_database: Database, pub redis: redis::RedisSettings, @@ -27,6 +29,7 @@ pub struct Settings { } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct Database { pub username: String, pub password: String, @@ -37,35 +40,99 @@ pub struct Database { } #[derive(Debug, Clone, Deserialize)] +#[serde(default)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, } +impl Default for Database { + fn default() -> Self { + Self { + username: String::default(), + password: String::default(), + host: "localhost".into(), + port: 5432, + dbname: String::default(), + pool_size: 5, + } + } +} + +impl Default for DrainerSettings { + fn default() -> Self { + Self { + stream_name: "DRAINER_STREAM".into(), + num_partitions: 64, + max_read_count: 100, + } + } +} + +impl Database { + fn validate(&self) -> Result<(), errors::DrainerError> { + use common_utils::fp_utils::when; + + when(self.username.is_default_or_empty(), || { + Err(errors::DrainerError::ConfigParsingError( + "database username must not be empty".into(), + )) + })?; + + when(self.password.is_default_or_empty(), || { + Err(errors::DrainerError::ConfigParsingError( + "database user password must not be empty".into(), + )) + })?; + + when(self.host.is_default_or_empty(), || { + Err(errors::DrainerError::ConfigParsingError( + "database host must not be empty".into(), + )) + })?; + + when(self.dbname.is_default_or_empty(), || { + Err(errors::DrainerError::ConfigParsingError( + "database name must not be empty".into(), + )) + }) + } +} + +impl DrainerSettings { + fn validate(&self) -> Result<(), errors::DrainerError> { + common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { + Err(errors::DrainerError::ConfigParsingError( + "drainer stream name must not be empty".into(), + )) + }) + } +} + impl Settings { pub fn new() -> Result<Self, errors::DrainerError> { Self::with_config_path(None) } pub fn with_config_path(config_path: Option<PathBuf>) -> Result<Self, errors::DrainerError> { + // Configuration values are picked up in the following priority order (1 being least + // priority): + // 1. Defaults from the implementation of the `Default` trait. + // 2. Values from config file. The config file accessed depends on the environment + // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of + // `Development`, `Sandbox` or `Production`. If nothing is specified for `RUN_ENV`, + // `/config/Development.toml` file is read. + // 3. Environment variables prefixed with `DRAINER` and each level separated by double + // underscores. + // + // Values in config file override the defaults in `Default` trait, and the values set using + // environment variables override both the defaults and the config file values. + let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); - // println!("config_path : {:?}", config_path); - // println!("current_dir : {:?}", std::env::current_dir()); - let config = router_env::Config::builder(&environment.to_string())? - // FIXME: consider embedding of textual file into bin files has several disadvantages - // 1. larger bin file - // 2. slower initialization of program - // 3. too late ( run-time ) information about broken toml file - // Consider embedding all defaults into code. - // Example: https://github.com/instrumentisto/medea/blob/medea-0.2.0/src/conf/mod.rs#L60-L102 - .add_source(File::from_str( - include_str!("defaults.toml"), - FileFormat::Toml, - )) .add_source(File::from(config_path).required(true)) .add_source( Environment::with_prefix("DRAINER") @@ -82,4 +149,15 @@ impl Settings { errors::DrainerError::from(error.into_inner()) }) } + + pub fn validate(&self) -> Result<(), errors::DrainerError> { + self.master_database.validate()?; + self.redis.validate().map_err(|error| { + println!("{error}"); + errors::DrainerError::ConfigParsingError("invalid Redis configuration".into()) + })?; + self.drainer.validate()?; + + Ok(()) + } } diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs index 43318ee06ae..c0bd00210a0 100644 --- a/crates/redis_interface/src/errors.rs +++ b/crates/redis_interface/src/errors.rs @@ -4,6 +4,8 @@ #[derive(Debug, thiserror::Error)] pub enum RedisError { + #[error("Invalid Redis configuration: {0}")] + InvalidConfiguration(String), #[error("Failed to set key value in Redis")] SetFailed, #[error("Failed to set key value with expiry in Redis")] diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index 76060d0219e..28fa49649fe 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -2,6 +2,12 @@ //! Data types and type conversions //! from `fred`'s internal data-types to custom data-types //! + +use common_utils::errors::CustomResult; +use error_stack::IntoReport; + +use crate::errors; + #[derive(Debug, serde::Deserialize, Clone)] pub struct RedisSettings { pub host: String, @@ -18,6 +24,27 @@ pub struct RedisSettings { pub stream_read_count: u64, } +impl RedisSettings { + /// Validates the Redis configuration provided. + pub fn validate(&self) -> CustomResult<(), errors::RedisError> { + use common_utils::{ext_traits::ConfigExt, fp_utils::when}; + + when(self.host.is_default_or_empty(), || { + Err(errors::RedisError::InvalidConfiguration( + "Redis `host` must be specified".into(), + )) + .into_report() + })?; + + when(self.cluster_enabled && self.cluster_urls.is_empty(), || { + Err(errors::RedisError::InvalidConfiguration( + "Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(), + )) + .into_report() + }) + } +} + impl Default for RedisSettings { fn default() -> Self { Self { diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 3480207e131..7f2c4424a41 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -26,6 +26,9 @@ async fn main() -> ApplicationResult<()> { #[allow(clippy::expect_used)] let conf = Settings::with_config_path(cmd_line.config_path) .expect("Unable to construct application configuration"); + #[allow(clippy::expect_used)] + conf.validate() + .expect("Failed to validate router configuration"); let _guard = logger::setup(&conf.log)?; diff --git a/crates/router/src/configs.rs b/crates/router/src/configs.rs index 6e98cefd04d..55fa589a6e8 100644 --- a/crates/router/src/configs.rs +++ b/crates/router/src/configs.rs @@ -1 +1,3 @@ +mod defaults; pub mod settings; +mod validations; diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs new file mode 100644 index 00000000000..44ab0640983 --- /dev/null +++ b/crates/router/src/configs/defaults.rs @@ -0,0 +1,111 @@ +impl Default for super::settings::Server { + fn default() -> Self { + Self { + port: 8080, + workers: num_cpus::get_physical(), + host: "localhost".into(), + request_body_limit: 16 * 1024, // POST request body is limited to 16KiB + base_url: "http://localhost:8080".into(), + } + } +} + +impl Default for super::settings::Database { + fn default() -> Self { + Self { + username: String::new(), + password: String::new(), + host: "localhost".into(), + port: 5432, + dbname: String::new(), + pool_size: 5, + } + } +} + +impl Default for super::settings::Secrets { + fn default() -> Self { + Self { + jwt_secret: "secret".into(), + admin_api_key: "test_admin".into(), + } + } +} + +impl Default for super::settings::Locker { + fn default() -> Self { + Self { + host: "localhost".into(), + mock_locker: true, + basilisk_host: "localhost".into(), + } + } +} + +impl Default for super::settings::SupportedConnectors { + fn default() -> Self { + Self { + wallets: ["klarna", "braintree"].map(Into::into).into(), + /* cards: [ + "adyen", + "authorizedotnet", + "braintree", + "checkout", + "cybersource", + "fiserv", + "rapyd", + "stripe", + ] + .map(Into::into) + .into(), */ + } + } +} + +impl Default for super::settings::Refund { + fn default() -> Self { + Self { + max_attempts: 10, + max_age: 365, + } + } +} + +impl Default for super::settings::EphemeralConfig { + fn default() -> Self { + Self { validity: 1 } + } +} + +impl Default for super::settings::SchedulerSettings { + fn default() -> Self { + Self { + stream: "SCHEDULER_STREAM".into(), + consumer_group: "SCHEDULER_GROUP".into(), + producer: super::settings::ProducerSettings::default(), + } + } +} + +impl Default for super::settings::ProducerSettings { + fn default() -> Self { + Self { + upper_fetch_limit: 0, + lower_fetch_limit: 1800, + lock_key: "PRODUCER_LOCKING_KEY".into(), + lock_ttl: 160, + batch_size: 200, + } + } +} + +#[cfg(feature = "kv_store")] +impl Default for super::settings::DrainerSettings { + fn default() -> Self { + Self { + stream_name: "DRAINER_STREAM".into(), + num_partitions: 64, + max_read_count: 100, + } + } +} diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml deleted file mode 100644 index 437f78eed23..00000000000 --- a/crates/router/src/configs/defaults.toml +++ /dev/null @@ -1,66 +0,0 @@ -# log defaults in /crates/router_env/src/defaults.toml - -[server] -port = 8080 -host = "127.0.0.1" -request_body_limit = 16_384 # Post request body is limited to 16k. -base_url = "http://localhost:8080" - -[proxy] -# http_url = "" -# https_url = "" - -[master_database] -username = "none" -password = "none" -host = "localhost" -port = 5432 -dbname = "none" -pool_size = 5 - -[redis] -host = "127.0.0.1" -port = 6379 -pool_size = 5 -reconnect_max_attempts = 5 -reconnect_delay = 5 -default_ttl = 300 -stream_read_count = 1 -cluster_enabled = false -use_legacy_version = false -cluster_urls = [] - -[secrets] -admin_api_key = "test_admin" -jwt_secret = "secret" - -[locker] - -[jwekey] - -[eph_key] -validity = 1 - -[refund] -max_attempts = 10 -max_age = 365 - -[scheduler] -stream = "SCHEDULER_STREAM" -consumer_group = "SCHEDULER_GROUP" - -[scheduler.producer] -upper_fetch_limit = 0 -lower_fetch_limit = 1800 -lock_key = "PRODUCER_LOCKING_KEY" -lock_ttl = 160 -batch_size = 200 - -[drainer] -stream_name = "DRAINER_STREAM" -num_partitions = 64 -max_read_count = 100 - -[connectors.supported] -wallets = ["klarna","braintree"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource", "fiserv", "rapyd"] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 72b641f9ae8..94df55b9cc3 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -1,6 +1,7 @@ use std::path::PathBuf; -use config::{Environment, File, FileFormat}; +use common_utils::ext_traits::ConfigExt; +use config::{Environment, File}; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use serde::Deserialize; @@ -29,7 +30,8 @@ pub enum Subcommand { GenerateOpenapiSpec, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct Settings { pub server: Server, pub proxy: Proxy, @@ -51,12 +53,14 @@ pub struct Settings { } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct Secrets { pub jwt_secret: String, pub admin_api_key: String, } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct Locker { pub host: String, pub mock_locker: bool, @@ -64,17 +68,20 @@ pub struct Locker { } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct Refund { pub max_attempts: usize, pub max_age: i64, } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct EphemeralConfig { pub validity: i64, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct Jwekey { #[cfg(feature = "kms")] pub aws_key_id: String, @@ -88,22 +95,25 @@ pub struct Jwekey { pub locker_decryption_key2: String, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct Proxy { pub http_url: Option<String>, pub https_url: Option<String>, } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct Server { pub port: u16, - pub workers: Option<usize>, + pub workers: usize, pub host: String, pub request_body_limit: usize, pub base_url: String, } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct Database { pub username: String, pub password: String, @@ -114,11 +124,13 @@ pub struct Database { } #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct SupportedConnectors { pub wallets: Vec<String>, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub adyen: ConnectorParams, @@ -134,17 +146,21 @@ pub struct Connectors { pub rapyd: ConnectorParams, pub shift4: ConnectorParams, pub stripe: ConnectorParams, - pub supported: SupportedConnectors, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, + + // Keep this field separate from the remaining fields + pub supported: SupportedConnectors, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct ConnectorParams { pub base_url: String, } #[derive(Debug, Clone, Deserialize)] +#[serde(default)] pub struct SchedulerSettings { pub stream: String, pub consumer_group: String, @@ -152,6 +168,7 @@ pub struct SchedulerSettings { } #[derive(Debug, Clone, Deserialize)] +#[serde(default)] pub struct ProducerSettings { pub upper_fetch_limit: i64, pub lower_fetch_limit: i64, @@ -163,6 +180,7 @@ pub struct ProducerSettings { #[cfg(feature = "kv_store")] #[derive(Debug, Clone, Deserialize)] +#[serde(default)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, @@ -175,23 +193,23 @@ impl Settings { } pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> { + // Configuration values are picked up in the following priority order (1 being least + // priority): + // 1. Defaults from the implementation of the `Default` trait. + // 2. Values from config file. The config file accessed depends on the environment + // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of + // `Development`, `Sandbox` or `Production`. If nothing is specified for `RUN_ENV`, + // `/config/Development.toml` file is read. + // 3. Environment variables prefixed with `ROUTER` and each level separated by double + // underscores. + // + // Values in config file override the defaults in `Default` trait, and the values set using + // environment variables override both the defaults and the config file values. + let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); - // println!("config_path : {:?}", config_path); - // println!("current_dir : {:?}", std::env::current_dir()); - let config = router_env::Config::builder(&environment.to_string())? - // FIXME: consider embedding of textual file into bin files has several disadvantages - // 1. larger bin file - // 2. slower initialization of program - // 3. too late ( run-time ) information about broken toml file - // Consider embedding all defaults into code. - // Example: https://github.com/instrumentisto/medea/blob/medea-0.2.0/src/conf/mod.rs#L60-L102 - .add_source(File::from_str( - include_str!("defaults.toml"), - FileFormat::Toml, - )) .add_source(File::from(config_path).required(true)) .add_source( Environment::with_prefix("ROUTER") @@ -209,4 +227,41 @@ impl Settings { ApplicationError::from(error.into_inner()) }) } + + pub fn validate(&self) -> ApplicationResult<()> { + self.server.validate()?; + self.master_database.validate()?; + #[cfg(feature = "olap")] + self.replica_database.validate()?; + self.redis.validate().map_err(|error| { + println!("{error}"); + ApplicationError::InvalidConfigurationValueError("Redis configuration".into()) + })?; + if self.log.file.enabled { + if self.log.file.file_name.is_default_or_empty() { + return Err(ApplicationError::InvalidConfigurationValueError( + "log file name must not be empty".into(), + )); + } + + if self.log.file.path.is_default_or_empty() { + return Err(ApplicationError::InvalidConfigurationValueError( + "log directory path must not be empty".into(), + )); + } + } + self.secrets.validate()?; + self.locker.validate()?; + self.connectors.validate()?; + + self.scheduler + .as_ref() + .map(|scheduler_settings| scheduler_settings.validate()) + .transpose()?; + #[cfg(feature = "kv_store")] + self.drainer.validate()?; + self.jwekey.validate()?; + + Ok(()) + } } diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs new file mode 100644 index 00000000000..e63ef2268cf --- /dev/null +++ b/crates/router/src/configs/validations.rs @@ -0,0 +1,186 @@ +use common_utils::ext_traits::ConfigExt; + +use crate::core::errors::ApplicationError; + +impl super::settings::Secrets { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::fp_utils::when; + + when(self.jwt_secret.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "JWT secret must not be empty".into(), + )) + })?; + + when(self.admin_api_key.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "admin API key must not be empty".into(), + )) + }) + } +} + +impl super::settings::Locker { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::fp_utils::when; + + when(!self.mock_locker && self.host.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "locker host must not be empty when mock locker is disabled".into(), + )) + })?; + + when( + !self.mock_locker && self.basilisk_host.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "basilisk host must not be empty when mock locker is disabled".into(), + )) + }, + ) + } +} + +impl super::settings::Jwekey { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + #[cfg(feature = "kms")] + common_utils::fp_utils::when(self.aws_key_id.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "AWS key ID must not be empty when KMS feature is enabled".into(), + )) + })?; + + #[cfg(feature = "kms")] + common_utils::fp_utils::when(self.aws_region.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "AWS region must not be empty when KMS feature is enabled".into(), + )) + })?; + + Ok(()) + } +} + +impl super::settings::Server { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.host.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "server host must not be empty".into(), + )) + }) + } +} + +impl super::settings::Database { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::fp_utils::when; + + when(self.host.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "database host must not be empty".into(), + )) + })?; + + when(self.username.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "database user username must not be empty".into(), + )) + })?; + + when(self.password.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "database user password must not be empty".into(), + )) + })?; + + when(self.dbname.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "database name must not be empty".into(), + )) + }) + } +} + +impl super::settings::SupportedConnectors { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.wallets.is_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "list of connectors supporting wallets must not be empty".into(), + )) + }) + } +} + +impl super::settings::Connectors { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + self.aci.validate()?; + self.adyen.validate()?; + self.applepay.validate()?; + self.authorizedotnet.validate()?; + self.braintree.validate()?; + self.checkout.validate()?; + self.cybersource.validate()?; + self.globalpay.validate()?; + self.klarna.validate()?; + self.shift4.validate()?; + self.stripe.validate()?; + self.worldpay.validate()?; + + self.supported.validate()?; + + Ok(()) + } +} + +impl super::settings::ConnectorParams { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.base_url.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "connector base URL must not be empty".into(), + )) + }) + } +} + +impl super::settings::SchedulerSettings { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::fp_utils::when; + + when(self.stream.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "scheduler stream must not be empty".into(), + )) + })?; + + when(self.consumer_group.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "scheduler consumer group must not be empty".into(), + )) + })?; + + self.producer.validate()?; + + Ok(()) + } +} + +impl super::settings::ProducerSettings { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.lock_key.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "producer lock key must not be empty".into(), + )) + }) + } +} + +#[cfg(feature = "kv_store")] +impl super::settings::DrainerSettings { + pub(crate) fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "drainer stream name must not be empty".into(), + )) + }) + } +} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 4c0687fa506..7f68362d9c4 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -103,6 +103,9 @@ pub enum ApplicationError { #[error("Application configuration error: {0}")] ConfigurationError(ConfigError), + #[error("Invalid configuration value provided: {0}")] + InvalidConfigurationValueError(String), + #[error("Metrics error: {0}")] MetricsError(MetricsError), @@ -144,9 +147,10 @@ fn error_response<T: Display>(err: &T) -> actix_web::HttpResponse { impl ResponseError for ApplicationError { fn status_code(&self) -> StatusCode { match self { - Self::MetricsError(_) | Self::IoError(_) | Self::ConfigurationError(_) => { - StatusCode::INTERNAL_SERVER_ERROR - } + Self::MetricsError(_) + | Self::IoError(_) + | Self::ConfigurationError(_) + | Self::InvalidConfigurationValueError(_) => StatusCode::INTERNAL_SERVER_ERROR, } } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c02da0768da..c9a69f97608 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -119,7 +119,7 @@ pub async fn start_server(conf: settings::Settings) -> ApplicationResult<(Server let request_body_limit = server.request_body_limit; let server = actix_web::HttpServer::new(move || mk_app(state.clone(), request_body_limit)) .bind((server.host.as_str(), server.port))? - .workers(server.workers.unwrap_or_else(num_cpus::get_physical)) + .workers(server.workers) .run(); Ok((server, app_state)) diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 6687d2f7f34..7ad37c8ab18 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -1,12 +1,6 @@ //! //! Logger-specific config. //! -//! Looking for config files algorithm first tries to deduce type of environment ( `Development`/`Sandbox`/`Production` ) from environment variable `RUN_ENV`. -//! It uses type of environment to deduce which config to load. -//! Default config is `/config/Development.toml`. -//! Default type of environment is `Development`. -//! It falls back to defaults defined in file "defaults.toml" in src if no config file found or it does not have some key value pairs. -//! use std::path::PathBuf; @@ -23,7 +17,8 @@ pub struct Config { } /// Log config settings. -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct Log { /// Logging to a file. pub file: LogFile, @@ -35,6 +30,7 @@ pub struct Log { /// Logging to a file. #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct LogFile { /// Whether you want to store log in log files. pub enabled: bool, @@ -50,7 +46,7 @@ pub struct LogFile { /// Describes the level of verbosity of a span or event. #[derive(Debug, Clone)] -pub struct Level(tracing::Level); +pub struct Level(pub(super) tracing::Level); impl Level { /// Returns the most verbose [`tracing::Level`] @@ -75,6 +71,7 @@ impl<'de> Deserialize<'de> for Level { /// Logging to a console. #[derive(Debug, Deserialize, Clone)] +#[serde(default)] pub struct LogConsole { /// Whether you want to see log in your terminal. pub enabled: bool, @@ -86,7 +83,8 @@ pub struct LogConsole { } /// Telemetry / tracing. -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct LogTelemetry { /// Whether tracing/telemetry is enabled. pub enabled: bool, @@ -110,10 +108,24 @@ impl Config { pub fn new() -> Result<Self, config::ConfigError> { Self::new_with_config_path(None) } + /// Constructor expecting config path set explicitly. pub fn new_with_config_path( explicit_config_path: Option<PathBuf>, ) -> Result<Self, config::ConfigError> { + // Configuration values are picked up in the following priority order (1 being least + // priority): + // 1. Defaults from the implementation of the `Default` trait. + // 2. Values from config file. The config file accessed depends on the environment + // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of + // `Development`, `Sandbox` or `Production`. If nothing is specified for `RUN_ENV`, + // `/config/Development.toml` file is read. + // 3. Environment variables prefixed with `ROUTER` and each level separated by double + // underscores. + // + // Values in config file override the defaults in `Default` trait, and the values set using + // environment variables override both the defaults and the config file values. + let environment = crate::env::which(); let config_path = Self::config_path(&environment.to_string(), explicit_config_path); @@ -133,22 +145,11 @@ impl Config { pub fn builder( environment: &str, ) -> Result<config::ConfigBuilder<config::builder::DefaultState>, config::ConfigError> { - Ok(config::Config::builder() - // Here should be `set_override` not `set_default`. + config::Config::builder() + // Here, it should be `set_override()` not `set_default()`. // "env" can't be altered by config field. // Should be single source of truth. - .set_override("env", environment)? - .add_source(config::File::from_str( - // Plan on handling with the changes in crates/router - // FIXME: embedding of textual file into bin files has several disadvantages - // 1. larger bin file - // 2. slower initialization of program - // 3. too late ( run-time ) information about broken toml file - // Consider embedding all defaults into code. - // Example: https://github.com/instrumentisto/medea/blob/medea-0.2.0/src/conf/mod.rs#L60-L102 - include_str!("defaults.toml"), - config::FileFormat::Toml, - ))) + .set_override("env", environment) } /// Config path. diff --git a/crates/router_env/src/logger/defaults.rs b/crates/router_env/src/logger/defaults.rs new file mode 100644 index 00000000000..befa44cf6fe --- /dev/null +++ b/crates/router_env/src/logger/defaults.rs @@ -0,0 +1,20 @@ +impl Default for super::config::LogFile { + fn default() -> Self { + Self { + enabled: true, + path: "logs".into(), + file_name: "debug.log".into(), + level: super::config::Level(tracing::Level::DEBUG), + } + } +} + +impl Default for super::config::LogConsole { + fn default() -> Self { + Self { + enabled: false, + level: super::config::Level(tracing::Level::INFO), + log_format: super::config::LogFormat::Json, + } + } +} diff --git a/crates/router_env/src/logger/defaults.toml b/crates/router_env/src/logger/defaults.toml deleted file mode 100644 index 330beeaec6c..00000000000 --- a/crates/router_env/src/logger/defaults.toml +++ /dev/null @@ -1,14 +0,0 @@ -[log.file] -enabled = true # Whether you want to store log in log files. -path = "logs" # Where to store log files. -file_name = "debug.log" # Name of log file without suffix. -# do_async = true # is not used -level = "DEBUG" # What gets into log files. -# rotation = "60" # mins # current framework doesn't support configuring rotation. set to hourly rotation. - -[log.console] -enabled = false # Whether you want to see log in your terminal. -level = "INFO" # What you see in your terminal. - -[log.telemetry] -enabled = false # Whether tracing/telemetry is enabled. diff --git a/crates/router_env/src/logger/mod.rs b/crates/router_env/src/logger/mod.rs index 896227c9565..a7aa0610e9b 100644 --- a/crates/router_env/src/logger/mod.rs +++ b/crates/router_env/src/logger/mod.rs @@ -6,6 +6,7 @@ pub use tracing::{debug, error, event as log, info, warn}; pub use tracing_attributes::instrument; pub mod config; +mod defaults; pub use crate::config::Config; // mod macros;
refactor
move config defaults from TOML files to `Default` trait (#352)
7ca62d3c7c04997c7eed6e82ec02dc39ea046b2f
2023-06-19 14:09:40
SamraatBansal
fix(connector): [Zen] Convert the amount to base denomination in order_details (#1477)
false
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 958dbe35ff6..d288405d380 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -395,15 +395,20 @@ fn get_item_object( _amount: String, ) -> Result<Vec<ZenItemObject>, error_stack::Report<errors::ConnectorError>> { let order_details = item.request.get_order_details()?; - Ok(order_details + + order_details .iter() - .map(|data| ZenItemObject { - name: data.product_name.clone(), - quantity: data.quantity, - price: data.amount.to_string(), - line_amount_total: (i64::from(data.quantity) * data.amount).to_string(), + .map(|data| { + Ok(ZenItemObject { + name: data.product_name.clone(), + quantity: data.quantity, + price: utils::to_currency_base_unit(data.amount, item.request.currency)?, + line_amount_total: (f64::from(data.quantity) + * utils::to_currency_base_unit_asf64(data.amount, item.request.currency)?) + .to_string(), + }) }) - .collect()) + .collect::<Result<_, _>>() } fn get_browser_details(
fix
[Zen] Convert the amount to base denomination in order_details (#1477)
de366b35f9c5e8439d86c58839dc2f79e39e9c9b
2023-12-20 18:41:45
github-actions
chore(version): v1.103.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d2c441578d..6784fd3fdeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,43 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.103.0 (2023-12-20) + +### Features + +- **connector:** + - [NMI] Implement webhook for Payments and Refunds ([#3164](https://github.com/juspay/hyperswitch/pull/3164)) ([`30c1401`](https://github.com/juspay/hyperswitch/commit/30c14019d067ad5f105563f205eb1941010233e8)) + - [BOA] Handle BOA 5XX errors ([#3178](https://github.com/juspay/hyperswitch/pull/3178)) ([`1d80949`](https://github.com/juspay/hyperswitch/commit/1d80949bef1228bf432dc445eaba15afccb030bd)) +- **connector-config:** Add wasm support for dashboard connector configuration ([#3138](https://github.com/juspay/hyperswitch/pull/3138)) ([`b0ffbe9`](https://github.com/juspay/hyperswitch/commit/b0ffbe9355b7e38226994c1ccbbe80cdbc77adde)) +- **db:** Implement `AuthorizationInterface` for `MockDb` ([#3151](https://github.com/juspay/hyperswitch/pull/3151)) ([`396a64f`](https://github.com/juspay/hyperswitch/commit/396a64f3bbad6e75d4b263286a7ef6a2f09b180e)) +- **postman:** [Prophetpay] Add test cases ([#2946](https://github.com/juspay/hyperswitch/pull/2946)) ([`583d7b8`](https://github.com/juspay/hyperswitch/commit/583d7b87a711102e4e62417f3191ac837886eca9)) + +### Bug Fixes + +- **connector:** + - [NMI] Fix response deserialization for vault id creation ([#3166](https://github.com/juspay/hyperswitch/pull/3166)) ([`d44daaf`](https://github.com/juspay/hyperswitch/commit/d44daaf539021a9cbc33c9391172c38825d74dcd)) + - Connector wise validation for zero auth flow ([#3159](https://github.com/juspay/hyperswitch/pull/3159)) ([`45ba128`](https://github.com/juspay/hyperswitch/commit/45ba128b6ab39f513dd114567d9915acf0eaea20)) +- **events:** Add logger for incoming webhook payload ([#3171](https://github.com/juspay/hyperswitch/pull/3171)) ([`cf47a65`](https://github.com/juspay/hyperswitch/commit/cf47a65916fd4fb5c996946ffd579fd6755d02f7)) +- **users:** Send correct `user_role` values in `switch_merchant` response ([#3167](https://github.com/juspay/hyperswitch/pull/3167)) ([`dc589d5`](https://github.com/juspay/hyperswitch/commit/dc589d580f1382874bc755d3719bd3244fdedc67)) + +### Refactors + +- **core:** Fix payment status for 4xx ([#3177](https://github.com/juspay/hyperswitch/pull/3177)) ([`e7949c2`](https://github.com/juspay/hyperswitch/commit/e7949c23b9be56a4cd763d4990c1a95c0fefae95)) +- **payment_methods:** Make the card_holder_name as an empty string if not sent ([#3173](https://github.com/juspay/hyperswitch/pull/3173)) ([`b98e53d`](https://github.com/juspay/hyperswitch/commit/b98e53d5cba5a5af04ada9bd83fa7bd2e27462d9)) + +### Testing + +- **postman:** Update postman collection files ([`6890e90`](https://github.com/juspay/hyperswitch/commit/6890e9029d90bfd518ba23979a0bd507853dc983)) + +### Documentation + +- **connector:** Update connector integration documentation ([#3041](https://github.com/juspay/hyperswitch/pull/3041)) ([`ce5514e`](https://github.com/juspay/hyperswitch/commit/ce5514eadfce240bc4cefb472405f37432a8507b)) + +**Full Changelog:** [`v1.102.1...v1.103.0`](https://github.com/juspay/hyperswitch/compare/v1.102.1...v1.103.0) + +- - - + + ## 1.102.1 (2023-12-18) ### Bug Fixes
chore
v1.103.0
2a66f4a392a5175404816ba83736e3eeb3e2b53b
2024-12-13 10:45:08
Amisha Prabhat
feat(routing): build the gRPC interface for communicating with the external service to perform elimination routing (#6672)
false
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index eeb67d679ee..2e570816ab4 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -745,8 +745,8 @@ pub struct EliminationRoutingConfig { #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct EliminationAnalyserConfig { - pub bucket_size: Option<u32>, - pub bucket_ttl_in_mins: Option<f64>, + pub bucket_size: Option<u64>, + pub bucket_leak_interval_in_secs: Option<u64>, } impl Default for EliminationRoutingConfig { @@ -755,7 +755,7 @@ impl Default for EliminationRoutingConfig { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), - bucket_ttl_in_mins: Some(2.0), + bucket_leak_interval_in_secs: Some(2), }), } } @@ -859,3 +859,18 @@ impl CurrentBlockThreshold { } } } + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] +pub struct RoutableConnectorChoiceWithBucketName { + pub routable_connector_choice: RoutableConnectorChoice, + pub bucket_name: String, +} + +impl RoutableConnectorChoiceWithBucketName { + pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { + Self { + routable_connector_choice, + bucket_name, + } + } +} diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs index 0a4938e94b4..b3fa1a8fed2 100644 --- a/crates/external_services/build.rs +++ b/crates/external_services/build.rs @@ -6,7 +6,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { let proto_path = router_env::workspace_path().join("proto"); let success_rate_proto_file = proto_path.join("success_rate.proto"); - + let elimination_proto_file = proto_path.join("elimination_rate.proto"); let health_check_proto_file = proto_path.join("health_check.proto"); let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?); @@ -14,7 +14,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { tonic_build::configure() .out_dir(out_dir) .compile( - &[success_rate_proto_file, health_check_proto_file], + &[ + success_rate_proto_file, + elimination_proto_file, + health_check_proto_file, + ], &[proto_path], ) .expect("Failed to compile proto files"); diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs index 7ec42de0d7c..e5050227fa8 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing.rs @@ -1,31 +1,17 @@ use std::fmt::Debug; -use api_models::routing::{ - CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus, - SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, -}; -use common_utils::{errors::CustomResult, ext_traits::OptionExt, transformers::ForeignTryFrom}; -use error_stack::ResultExt; +use common_utils::errors::CustomResult; use router_env::logger; use serde; -use success_rate::{ - success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig, - CalSuccessRateRequest, CalSuccessRateResponse, - CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest, - InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig, - UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse, -}; +/// Elimination Routing Client Interface Implementation +pub mod elimination_rate_client; +/// Success Routing Client Interface Implementation +pub mod success_rate_client; + +pub use elimination_rate_client::EliminationAnalyserClient; +pub use success_rate_client::SuccessRateCalculatorClient; use super::Client; -#[allow( - missing_docs, - unused_qualifications, - clippy::unwrap_used, - clippy::as_conversions -)] -pub mod success_rate { - tonic::include_proto!("success_rate"); -} /// Result type for Dynamic Routing pub type DynamicRoutingResult<T> = CustomResult<T, DynamicRoutingError>; @@ -38,9 +24,12 @@ pub enum DynamicRoutingError { /// The required field name field: String, }, - /// Error from Dynamic Routing Server - #[error("Error from Dynamic Routing Server : {0}")] + /// Error from Dynamic Routing Server while performing success_rate analysis + #[error("Error from Dynamic Routing Server while perfrming success_rate analysis : {0}")] SuccessRateBasedRoutingFailure(String), + /// Error from Dynamic Routing Server while perfrming elimination + #[error("Error from Dynamic Routing Server while perfrming elimination : {0}")] + EliminationRateRoutingFailure(String), } /// Type that consists of all the services provided by the client @@ -48,6 +37,8 @@ pub enum DynamicRoutingError { pub struct RoutingStrategy { /// success rate service for Dynamic Routing pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>, + /// elimination service for Dynamic Routing + pub elimination_rate_client: Option<EliminationAnalyserClient<Client>>, } /// Contains the Dynamic Routing Client Config @@ -74,190 +65,23 @@ impl DynamicRoutingClientConfig { self, client: Client, ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> { - let success_rate_client = match self { + let (success_rate_client, elimination_rate_client) = match self { Self::Enabled { host, port, .. } => { let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?; logger::info!("Connection established with dynamic routing gRPC Server"); - Some(SuccessRateCalculatorClient::with_origin(client, uri)) + ( + Some(SuccessRateCalculatorClient::with_origin( + client.clone(), + uri.clone(), + )), + Some(EliminationAnalyserClient::with_origin(client, uri)), + ) } - Self::Disabled => None, + Self::Disabled => (None, None), }; Ok(RoutingStrategy { success_rate_client, - }) - } -} - -/// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window -#[async_trait::async_trait] -pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { - /// To calculate the success rate for the list of chosen connectors - async fn calculate_success_rate( - &self, - id: String, - success_rate_based_config: SuccessBasedRoutingConfig, - params: String, - label_input: Vec<RoutableConnectorChoice>, - ) -> DynamicRoutingResult<CalSuccessRateResponse>; - /// To update the success rate with the given label - async fn update_success_rate( - &self, - id: String, - success_rate_based_config: SuccessBasedRoutingConfig, - params: String, - response: Vec<RoutableConnectorChoiceWithStatus>, - ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>; - /// To invalidates the success rate routing keys - async fn invalidate_success_rate_routing_keys( - &self, - id: String, - ) -> DynamicRoutingResult<InvalidateWindowsResponse>; -} - -#[async_trait::async_trait] -impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { - async fn calculate_success_rate( - &self, - id: String, - success_rate_based_config: SuccessBasedRoutingConfig, - params: String, - label_input: Vec<RoutableConnectorChoice>, - ) -> DynamicRoutingResult<CalSuccessRateResponse> { - let labels = label_input - .into_iter() - .map(|conn_choice| conn_choice.to_string()) - .collect::<Vec<_>>(); - - let config = success_rate_based_config - .config - .map(ForeignTryFrom::foreign_try_from) - .transpose()?; - - let request = tonic::Request::new(CalSuccessRateRequest { - id, - params, - labels, - config, - }); - - let response = self - .clone() - .fetch_success_rate(request) - .await - .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure( - "Failed to fetch the success rate".to_string(), - ))? - .into_inner(); - - Ok(response) - } - - async fn update_success_rate( - &self, - id: String, - success_rate_based_config: SuccessBasedRoutingConfig, - params: String, - label_input: Vec<RoutableConnectorChoiceWithStatus>, - ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> { - let config = success_rate_based_config - .config - .map(ForeignTryFrom::foreign_try_from) - .transpose()?; - - let labels_with_status = label_input - .into_iter() - .map(|conn_choice| LabelWithStatus { - label: conn_choice.routable_connector_choice.to_string(), - status: conn_choice.status, - }) - .collect(); - - let request = tonic::Request::new(UpdateSuccessRateWindowRequest { - id, - params, - labels_with_status, - config, - }); - - let response = self - .clone() - .update_success_rate_window(request) - .await - .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure( - "Failed to update the success rate window".to_string(), - ))? - .into_inner(); - - Ok(response) - } - - async fn invalidate_success_rate_routing_keys( - &self, - id: String, - ) -> DynamicRoutingResult<InvalidateWindowsResponse> { - let request = tonic::Request::new(InvalidateWindowsRequest { id }); - - let response = self - .clone() - .invalidate_windows(request) - .await - .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure( - "Failed to invalidate the success rate routing keys".to_string(), - ))? - .into_inner(); - Ok(response) - } -} - -impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold { - type Error = error_stack::Report<DynamicRoutingError>; - fn foreign_try_from(current_threshold: CurrentBlockThreshold) -> Result<Self, Self::Error> { - Ok(Self { - duration_in_mins: current_threshold.duration_in_mins, - max_total_count: current_threshold - .max_total_count - .get_required_value("max_total_count") - .change_context(DynamicRoutingError::MissingRequiredField { - field: "max_total_count".to_string(), - })?, - }) - } -} - -impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig { - type Error = error_stack::Report<DynamicRoutingError>; - fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> { - Ok(Self { - max_aggregates_size: config - .max_aggregates_size - .get_required_value("max_aggregate_size") - .change_context(DynamicRoutingError::MissingRequiredField { - field: "max_aggregates_size".to_string(), - })?, - current_block_threshold: config - .current_block_threshold - .map(ForeignTryFrom::foreign_try_from) - .transpose()?, - }) - } -} - -impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig { - type Error = error_stack::Report<DynamicRoutingError>; - fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> { - Ok(Self { - min_aggregates_size: config - .min_aggregates_size - .get_required_value("min_aggregate_size") - .change_context(DynamicRoutingError::MissingRequiredField { - field: "min_aggregates_size".to_string(), - })?, - default_success_rate: config - .default_success_rate - .get_required_value("default_success_rate") - .change_context(DynamicRoutingError::MissingRequiredField { - field: "default_success_rate".to_string(), - })?, + elimination_rate_client, }) } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs new file mode 100644 index 00000000000..6587b7941f4 --- /dev/null +++ b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs @@ -0,0 +1,158 @@ +use api_models::routing::{ + EliminationAnalyserConfig as EliminationConfig, RoutableConnectorChoice, + RoutableConnectorChoiceWithBucketName, +}; +use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom}; +pub use elimination_rate::{ + elimination_analyser_client::EliminationAnalyserClient, EliminationBucketConfig, + EliminationRequest, EliminationResponse, InvalidateBucketRequest, InvalidateBucketResponse, + LabelWithBucketName, UpdateEliminationBucketRequest, UpdateEliminationBucketResponse, +}; +use error_stack::ResultExt; +#[allow( + missing_docs, + unused_qualifications, + clippy::unwrap_used, + clippy::as_conversions, + clippy::use_self +)] +pub mod elimination_rate { + tonic::include_proto!("elimination"); +} + +use super::{Client, DynamicRoutingError, DynamicRoutingResult}; + +/// The trait Elimination Based Routing would have the functions required to support performance, calculation and invalidation bucket +#[async_trait::async_trait] +pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync { + /// To perform the elimination based routing for the list of connectors + async fn perform_elimination_routing( + &self, + id: String, + params: String, + labels: Vec<RoutableConnectorChoice>, + configs: Option<EliminationConfig>, + ) -> DynamicRoutingResult<EliminationResponse>; + /// To update the bucket size and ttl for list of connectors with its respective bucket name + async fn update_elimination_bucket_config( + &self, + id: String, + params: String, + report: Vec<RoutableConnectorChoiceWithBucketName>, + config: Option<EliminationConfig>, + ) -> DynamicRoutingResult<UpdateEliminationBucketResponse>; + /// To invalidate the previous id's bucket + async fn invalidate_elimination_bucket( + &self, + id: String, + ) -> DynamicRoutingResult<InvalidateBucketResponse>; +} + +#[async_trait::async_trait] +impl EliminationBasedRouting for EliminationAnalyserClient<Client> { + async fn perform_elimination_routing( + &self, + id: String, + params: String, + label_input: Vec<RoutableConnectorChoice>, + configs: Option<EliminationConfig>, + ) -> DynamicRoutingResult<EliminationResponse> { + let labels = label_input + .into_iter() + .map(|conn_choice| conn_choice.to_string()) + .collect::<Vec<_>>(); + + let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?; + + let request = tonic::Request::new(EliminationRequest { + id, + params, + labels, + config, + }); + + let response = self + .clone() + .get_elimination_status(request) + .await + .change_context(DynamicRoutingError::EliminationRateRoutingFailure( + "Failed to perform the elimination analysis".to_string(), + ))? + .into_inner(); + + Ok(response) + } + + async fn update_elimination_bucket_config( + &self, + id: String, + params: String, + report: Vec<RoutableConnectorChoiceWithBucketName>, + configs: Option<EliminationConfig>, + ) -> DynamicRoutingResult<UpdateEliminationBucketResponse> { + let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?; + + let labels_with_bucket_name = report + .into_iter() + .map(|conn_choice_with_bucket| LabelWithBucketName { + label: conn_choice_with_bucket + .routable_connector_choice + .to_string(), + bucket_name: conn_choice_with_bucket.bucket_name, + }) + .collect::<Vec<_>>(); + + let request = tonic::Request::new(UpdateEliminationBucketRequest { + id, + params, + labels_with_bucket_name, + config, + }); + + let response = self + .clone() + .update_elimination_bucket(request) + .await + .change_context(DynamicRoutingError::EliminationRateRoutingFailure( + "Failed to update the elimination bucket".to_string(), + ))? + .into_inner(); + Ok(response) + } + async fn invalidate_elimination_bucket( + &self, + id: String, + ) -> DynamicRoutingResult<InvalidateBucketResponse> { + let request = tonic::Request::new(InvalidateBucketRequest { id }); + + let response = self + .clone() + .invalidate_bucket(request) + .await + .change_context(DynamicRoutingError::EliminationRateRoutingFailure( + "Failed to invalidate the elimination bucket".to_string(), + ))? + .into_inner(); + Ok(response) + } +} + +impl ForeignTryFrom<EliminationConfig> for EliminationBucketConfig { + type Error = error_stack::Report<DynamicRoutingError>; + fn foreign_try_from(config: EliminationConfig) -> Result<Self, Self::Error> { + Ok(Self { + bucket_size: config + .bucket_size + .get_required_value("bucket_size") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "bucket_size".to_string(), + })?, + bucket_leak_interval_in_secs: config + .bucket_leak_interval_in_secs + .get_required_value("bucket_leak_interval_in_secs") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "bucket_leak_interval_in_secs".to_string(), + })?, + }) + } +} diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs new file mode 100644 index 00000000000..f6d3efb8876 --- /dev/null +++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs @@ -0,0 +1,195 @@ +use api_models::routing::{ + CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus, + SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, +}; +use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom}; +use error_stack::ResultExt; +pub use success_rate::{ + success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig, + CalSuccessRateRequest, CalSuccessRateResponse, + CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest, + InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig, + UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse, +}; +#[allow( + missing_docs, + unused_qualifications, + clippy::unwrap_used, + clippy::as_conversions +)] +pub mod success_rate { + tonic::include_proto!("success_rate"); +} +use super::{Client, DynamicRoutingError, DynamicRoutingResult}; +/// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window +#[async_trait::async_trait] +pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { + /// To calculate the success rate for the list of chosen connectors + async fn calculate_success_rate( + &self, + id: String, + success_rate_based_config: SuccessBasedRoutingConfig, + params: String, + label_input: Vec<RoutableConnectorChoice>, + ) -> DynamicRoutingResult<CalSuccessRateResponse>; + /// To update the success rate with the given label + async fn update_success_rate( + &self, + id: String, + success_rate_based_config: SuccessBasedRoutingConfig, + params: String, + response: Vec<RoutableConnectorChoiceWithStatus>, + ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>; + /// To invalidates the success rate routing keys + async fn invalidate_success_rate_routing_keys( + &self, + id: String, + ) -> DynamicRoutingResult<InvalidateWindowsResponse>; +} + +#[async_trait::async_trait] +impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { + async fn calculate_success_rate( + &self, + id: String, + success_rate_based_config: SuccessBasedRoutingConfig, + params: String, + label_input: Vec<RoutableConnectorChoice>, + ) -> DynamicRoutingResult<CalSuccessRateResponse> { + let labels = label_input + .into_iter() + .map(|conn_choice| conn_choice.to_string()) + .collect::<Vec<_>>(); + + let config = success_rate_based_config + .config + .map(ForeignTryFrom::foreign_try_from) + .transpose()?; + + let request = tonic::Request::new(CalSuccessRateRequest { + id, + params, + labels, + config, + }); + + let response = self + .clone() + .fetch_success_rate(request) + .await + .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure( + "Failed to fetch the success rate".to_string(), + ))? + .into_inner(); + + Ok(response) + } + + async fn update_success_rate( + &self, + id: String, + success_rate_based_config: SuccessBasedRoutingConfig, + params: String, + label_input: Vec<RoutableConnectorChoiceWithStatus>, + ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> { + let config = success_rate_based_config + .config + .map(ForeignTryFrom::foreign_try_from) + .transpose()?; + + let labels_with_status = label_input + .into_iter() + .map(|conn_choice| LabelWithStatus { + label: conn_choice.routable_connector_choice.to_string(), + status: conn_choice.status, + }) + .collect(); + + let request = tonic::Request::new(UpdateSuccessRateWindowRequest { + id, + params, + labels_with_status, + config, + }); + + let response = self + .clone() + .update_success_rate_window(request) + .await + .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure( + "Failed to update the success rate window".to_string(), + ))? + .into_inner(); + + Ok(response) + } + async fn invalidate_success_rate_routing_keys( + &self, + id: String, + ) -> DynamicRoutingResult<InvalidateWindowsResponse> { + let request = tonic::Request::new(InvalidateWindowsRequest { id }); + + let response = self + .clone() + .invalidate_windows(request) + .await + .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure( + "Failed to invalidate the success rate routing keys".to_string(), + ))? + .into_inner(); + Ok(response) + } +} + +impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold { + type Error = error_stack::Report<DynamicRoutingError>; + fn foreign_try_from(current_threshold: CurrentBlockThreshold) -> Result<Self, Self::Error> { + Ok(Self { + duration_in_mins: current_threshold.duration_in_mins, + max_total_count: current_threshold + .max_total_count + .get_required_value("max_total_count") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "max_total_count".to_string(), + })?, + }) + } +} + +impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig { + type Error = error_stack::Report<DynamicRoutingError>; + fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> { + Ok(Self { + max_aggregates_size: config + .max_aggregates_size + .get_required_value("max_aggregate_size") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "max_aggregates_size".to_string(), + })?, + current_block_threshold: config + .current_block_threshold + .map(ForeignTryFrom::foreign_try_from) + .transpose()?, + }) + } +} + +impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig { + type Error = error_stack::Report<DynamicRoutingError>; + fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> { + Ok(Self { + min_aggregates_size: config + .min_aggregates_size + .get_required_value("min_aggregate_size") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "min_aggregates_size".to_string(), + })?, + default_success_rate: config + .default_success_rate + .get_required_value("default_success_rate") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "default_success_rate".to_string(), + })?, + }) + } +} diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index b3be47a8743..746b6b7fb40 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -23,8 +23,8 @@ use euclid::{ frontend::{ast, dir as euclid_dir}, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use external_services::grpc_client::dynamic_routing::{ - success_rate::CalSuccessRateResponse, SuccessBasedDynamicRouting, +use external_services::grpc_client::dynamic_routing::success_rate_client::{ + CalSuccessRateResponse, SuccessBasedDynamicRouting, }; use hyperswitch_domain_models::address::Address; use kgraph_utils::{ diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index cf04bec75a0..36bcb233d02 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -12,7 +12,7 @@ use common_utils::ext_traits::AsyncExt; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use external_services::grpc_client::dynamic_routing::SuccessBasedDynamicRouting; +use external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting; use hyperswitch_domain_models::{mandates, payment_address}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 690293c7f6b..b3c951f0964 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -18,7 +18,7 @@ use diesel_models::dynamic_routing_stats::DynamicRoutingStatsNew; use diesel_models::routing_algorithm; use error_stack::ResultExt; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] -use external_services::grpc_client::dynamic_routing::SuccessBasedDynamicRouting; +use external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting; #[cfg(feature = "v1")] use hyperswitch_domain_models::api::ApplicationResponse; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] diff --git a/proto/elimination_rate.proto b/proto/elimination_rate.proto new file mode 100644 index 00000000000..c5f10597ade --- /dev/null +++ b/proto/elimination_rate.proto @@ -0,0 +1,67 @@ +syntax = "proto3"; +package elimination; + +service EliminationAnalyser { + rpc GetEliminationStatus (EliminationRequest) returns (EliminationResponse); + + rpc UpdateEliminationBucket (UpdateEliminationBucketRequest) returns (UpdateEliminationBucketResponse); + + rpc InvalidateBucket (InvalidateBucketRequest) returns (InvalidateBucketResponse); +} + +// API-1 types +message EliminationRequest { + string id = 1; + string params = 2; + repeated string labels = 3; + EliminationBucketConfig config = 4; +} + +message EliminationBucketConfig { + uint64 bucket_size = 1; + uint64 bucket_leak_interval_in_secs = 2; +} + +message EliminationResponse { + repeated LabelWithStatus labels_with_status = 1; +} + +message LabelWithStatus { + string label = 1; + bool is_eliminated = 2; + string bucket_name = 3; +} + +// API-2 types +message UpdateEliminationBucketRequest { + string id = 1; + string params = 2; + repeated LabelWithBucketName labels_with_bucket_name = 3; + EliminationBucketConfig config = 4; +} + +message LabelWithBucketName { + string label = 1; + string bucket_name = 2; +} + +message UpdateEliminationBucketResponse { + enum UpdationStatus { + BUCKET_UPDATION_SUCCEEDED = 0; + BUCKET_UPDATION_FAILED = 1; + } + UpdationStatus status = 1; +} + +// API-3 types +message InvalidateBucketRequest { + string id = 1; +} + +message InvalidateBucketResponse { + enum InvalidationStatus { + BUCKET_INVALIDATION_SUCCEEDED = 0; + BUCKET_INVALIDATION_FAILED = 1; + } + InvalidationStatus status = 1; +} \ No newline at end of file
feat
build the gRPC interface for communicating with the external service to perform elimination routing (#6672)
15c2a70b427df1c7ec719c2e738f83be1b6a5662
2023-06-30 13:11:17
Sakil Mostak
feat(connector): [ACI] implement Card Mandates for ACI (#1174)
false
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index c956a8e0ae2..b6e37ca78ed 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -5,6 +5,7 @@ use std::fmt::Debug; use error_stack::{IntoReport, ResultExt}; use transformers as aci; +use super::utils::PaymentsAuthorizeRequestData; use crate::{ configs::settings, core::errors::{self, CustomResult}, @@ -245,10 +246,17 @@ impl fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}{}", self.base_url(connectors), "v1/payments")) + match req.request.connector_mandate_id() { + Some(mandate_id) => Ok(format!( + "{}v1/registrations/{}/payments", + self.base_url(connectors), + mandate_id + )), + _ => Ok(format!("{}{}", self.base_url(connectors), "v1/payments")), + } } fn get_request_body( diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 69fc8f47a0f..2666b5c7b37 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -1,5 +1,6 @@ use std::str::FromStr; +use api_models::enums::BankNames; use common_utils::pii::Email; use error_stack::report; use masking::Secret; @@ -8,12 +9,14 @@ use serde::{Deserialize, Serialize}; use super::result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES}; use crate::{ - connector::utils, + connector::utils::{self, RouterData}, core::errors, services, types::{self, api, storage::enums}, }; +type Error = error_stack::Report<errors::ConnectorError>; + pub struct AciAuthType { pub api_key: String, pub entity_id: String, @@ -36,12 +39,22 @@ impl TryFrom<&types::ConnectorAuthType> for AciAuthType { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AciPaymentsRequest { + #[serde(flatten)] + pub txn_details: TransactionDetails, + #[serde(flatten)] + pub payment_method: PaymentDetails, + #[serde(flatten)] + pub instruction: Option<Instruction>, + pub shopper_result_url: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TransactionDetails { pub entity_id: String, pub amount: String, pub currency: String, pub payment_type: AciPaymentType, - #[serde(flatten)] - pub payment_method: PaymentDetails, } #[derive(Debug, Serialize)] @@ -59,6 +72,160 @@ pub enum PaymentDetails { BankRedirect(Box<BankRedirectionPMData>), Wallet(Box<WalletPMData>), Klarna, + Mandate, +} + +impl TryFrom<&api_models::payments::WalletData> for PaymentDetails { + type Error = Error; + fn try_from(wallet_data: &api_models::payments::WalletData) -> Result<Self, Self::Error> { + let payment_data = match wallet_data { + api_models::payments::WalletData::MbWayRedirect(data) => { + Self::Wallet(Box::new(WalletPMData { + payment_brand: PaymentBrand::Mbway, + account_id: Some(data.telephone_number.clone()), + })) + } + api_models::payments::WalletData::AliPayRedirect { .. } => { + Self::Wallet(Box::new(WalletPMData { + payment_brand: PaymentBrand::AliPay, + account_id: None, + })) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment method".to_string(), + ))?, + }; + Ok(payment_data) + } +} + +impl + TryFrom<( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::BankRedirectData, + )> for PaymentDetails +{ + type Error = Error; + fn try_from( + value: ( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::BankRedirectData, + ), + ) -> Result<Self, Self::Error> { + let (item, bank_redirect_data) = value; + let payment_data = match bank_redirect_data { + api_models::payments::BankRedirectData::Eps { .. } => { + Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Eps, + bank_account_country: Some(api_models::enums::CountryAlpha2::AT), + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: None, + })) + } + api_models::payments::BankRedirectData::Giropay { + bank_account_bic, + bank_account_iban, + .. + } => Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Giropay, + bank_account_country: Some(api_models::enums::CountryAlpha2::DE), + bank_account_bank_name: None, + bank_account_bic: bank_account_bic.clone(), + bank_account_iban: bank_account_iban.clone(), + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: None, + })), + api_models::payments::BankRedirectData::Ideal { bank_name, .. } => { + Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Ideal, + bank_account_country: Some(api_models::enums::CountryAlpha2::NL), + bank_account_bank_name: bank_name.to_owned(), + bank_account_bic: None, + bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: None, + })) + } + api_models::payments::BankRedirectData::Sofort { country, .. } => { + Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Sofortueberweisung, + bank_account_country: Some(country.to_owned()), + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: None, + })) + } + api_models::payments::BankRedirectData::Przelewy24 { + billing_details, .. + } => Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Przelewy, + bank_account_country: None, + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: billing_details.email.to_owned(), + })), + api_models::payments::BankRedirectData::Interac { email, country } => { + Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::InteracOnline, + bank_account_country: Some(country.to_owned()), + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: None, + merchant_customer_id: None, + merchant_transaction_id: None, + customer_email: Some(email.to_owned()), + })) + } + api_models::payments::BankRedirectData::Trustly { country } => { + Self::BankRedirect(Box::new(BankRedirectionPMData { + payment_brand: PaymentBrand::Trustly, + bank_account_country: None, + bank_account_bank_name: None, + bank_account_bic: None, + bank_account_iban: None, + billing_country: Some(country.to_owned()), + merchant_customer_id: Some(Secret::new(item.get_customer_id()?)), + merchant_transaction_id: Some(Secret::new(item.payment_id.clone())), + customer_email: None, + })) + } + _ => Err(errors::ConnectorError::NotImplemented( + "Payment method".to_string(), + ))?, + }; + Ok(payment_data) + } +} + +impl TryFrom<api_models::payments::Card> for PaymentDetails { + type Error = Error; + fn try_from(card_data: api_models::payments::Card) -> Result<Self, Self::Error> { + Ok(Self::AciCard(Box::new(CardDetails { + card_number: card_data.card_number, + card_holder: card_data.card_holder_name, + card_expiry_month: card_data.card_exp_month, + card_expiry_year: card_data.card_exp_year, + card_cvv: card_data.card_cvc, + }))) + } } #[derive(Debug, Clone, Serialize)] @@ -68,7 +235,7 @@ pub struct BankRedirectionPMData { #[serde(rename = "bankAccount.country")] bank_account_country: Option<api_models::enums::CountryAlpha2>, #[serde(rename = "bankAccount.bankName")] - bank_account_bank_name: Option<String>, + bank_account_bank_name: Option<BankNames>, #[serde(rename = "bankAccount.bic")] bank_account_bic: Option<Secret<String>>, #[serde(rename = "bankAccount.iban")] @@ -80,7 +247,6 @@ pub struct BankRedirectionPMData { #[serde(rename = "customer.merchantCustomerId")] merchant_customer_id: Option<Secret<String>>, merchant_transaction_id: Option<Secret<String>>, - shopper_result_url: Option<String>, } #[derive(Debug, Clone, Serialize)] @@ -89,7 +255,6 @@ pub struct WalletPMData { payment_brand: PaymentBrand, #[serde(rename = "virtualAccount.accountId")] account_id: Option<Secret<String>>, - shopper_result_url: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -121,6 +286,43 @@ pub struct CardDetails { pub card_cvv: Secret<String>, } +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum InstructionMode { + Initial, + Repeated, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum InstructionType { + Unscheduled, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum InstructionSource { + // Cardholder initiated transaction + Cit, + // Merchant initiated transaction + Mit, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Instruction { + #[serde(rename = "standingInstruction.mode")] + mode: InstructionMode, + + #[serde(rename = "standingInstruction.type")] + transaction_type: InstructionType, + + #[serde(rename = "standingInstruction.source")] + source: InstructionSource, + + create_registration: Option<bool>, +} + #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct BankDetails { #[serde(rename = "bankAccount.holder")] @@ -128,7 +330,7 @@ pub struct BankDetails { } #[allow(dead_code)] -#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize)] +#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum AciPaymentType { #[serde(rename = "PA")] Preauthorization, @@ -148,179 +350,189 @@ pub enum AciPaymentType { impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let payment_details: PaymentDetails = match item.request.payment_method_data.clone() { - api::PaymentMethodData::Card(ccard) => PaymentDetails::AciCard(Box::new(CardDetails { - card_number: ccard.card_number, - card_holder: ccard.card_holder_name, - card_expiry_month: ccard.card_exp_month, - card_expiry_year: ccard.card_exp_year, - card_cvv: ccard.card_cvc, - })), - api::PaymentMethodData::PayLater(_) => PaymentDetails::Klarna, - api::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { - api_models::payments::WalletData::MbWayRedirect(data) => { - PaymentDetails::Wallet(Box::new(WalletPMData { - payment_brand: PaymentBrand::Mbway, - account_id: Some(data.telephone_number.clone()), - shopper_result_url: item.request.router_return_url.clone(), - })) - } - api_models::payments::WalletData::AliPayRedirect { .. } => { - PaymentDetails::Wallet(Box::new(WalletPMData { - payment_brand: PaymentBrand::AliPay, - account_id: None, - shopper_result_url: item.request.router_return_url.clone(), - })) - } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - ))?, - }, - api::PaymentMethodData::BankRedirect(ref redirect_banking_data) => { - match redirect_banking_data { - api_models::payments::BankRedirectData::Eps { .. } => { - PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { - payment_brand: PaymentBrand::Eps, - bank_account_country: Some(api_models::enums::CountryAlpha2::AT), - bank_account_bank_name: None, - bank_account_bic: None, - bank_account_iban: None, - billing_country: None, - merchant_customer_id: None, - merchant_transaction_id: None, - customer_email: None, - shopper_result_url: item.request.router_return_url.clone(), - })) - } - api_models::payments::BankRedirectData::Giropay { - bank_account_bic, - bank_account_iban, - .. - } => PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { - payment_brand: PaymentBrand::Giropay, - bank_account_country: Some(api_models::enums::CountryAlpha2::DE), - bank_account_bank_name: None, - bank_account_bic: bank_account_bic.clone(), - bank_account_iban: bank_account_iban.clone(), - billing_country: None, - merchant_customer_id: None, - merchant_transaction_id: None, - customer_email: None, - shopper_result_url: item.request.router_return_url.clone(), - })), - api_models::payments::BankRedirectData::Ideal { bank_name, .. } => { - PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { - payment_brand: PaymentBrand::Ideal, - bank_account_country: Some(api_models::enums::CountryAlpha2::NL), - bank_account_bank_name: bank_name - .map(|bank_name| bank_name.to_string()), - bank_account_bic: None, - bank_account_iban: None, - billing_country: None, - merchant_customer_id: None, - merchant_transaction_id: None, - customer_email: None, - shopper_result_url: item.request.router_return_url.clone(), - })) - } - api_models::payments::BankRedirectData::Sofort { country, .. } => { - PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { - payment_brand: PaymentBrand::Sofortueberweisung, - bank_account_country: Some(*country), - bank_account_bank_name: None, - bank_account_bic: None, - bank_account_iban: None, - billing_country: None, - merchant_customer_id: None, - merchant_transaction_id: None, - customer_email: None, - shopper_result_url: item.request.router_return_url.clone(), - })) - } - - api_models::payments::BankRedirectData::Przelewy24 { - billing_details, .. - } => PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { - payment_brand: PaymentBrand::Przelewy, - bank_account_country: None, - bank_account_bank_name: None, - bank_account_bic: None, - bank_account_iban: None, - billing_country: None, - merchant_customer_id: None, - merchant_transaction_id: None, - customer_email: billing_details.email.clone(), - shopper_result_url: item.request.router_return_url.clone(), - })), - - api_models::payments::BankRedirectData::Interac { email, country } => { - PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { - payment_brand: PaymentBrand::InteracOnline, - bank_account_country: Some(*country), - bank_account_bank_name: None, - bank_account_bic: None, - bank_account_iban: None, - billing_country: None, - merchant_customer_id: None, - merchant_transaction_id: None, - customer_email: Some(email.to_owned()), - shopper_result_url: item.request.router_return_url.clone(), - })) - } - - api_models::payments::BankRedirectData::Trustly { country } => { - PaymentDetails::BankRedirect(Box::new(BankRedirectionPMData { - payment_brand: PaymentBrand::Trustly, - bank_account_country: None, - bank_account_bank_name: None, - bank_account_bic: None, - bank_account_iban: None, - billing_country: Some(*country), - merchant_customer_id: Some(Secret::new( - item.customer_id.clone().ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "customer_id", - }, - )?, - )), - merchant_transaction_id: Some(Secret::new(item.payment_id.clone())), - customer_email: None, - shopper_result_url: item.request.router_return_url.clone(), - })) - } - - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - ))?, - } + match item.request.payment_method_data.clone() { + api::PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)), + api::PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)), + api::PaymentMethodData::PayLater(ref pay_later_data) => { + Self::try_from((item, pay_later_data)) + } + api::PaymentMethodData::BankRedirect(ref bank_redirect_data) => { + Self::try_from((item, bank_redirect_data)) + } + api::PaymentMethodData::MandatePayment => { + let mandate_id = item.request.mandate_id.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "mandate_id", + }, + )?; + Self::try_from((item, mandate_id)) } - api::PaymentMethodData::Crypto(_) | api::PaymentMethodData::BankDebit(_) | api::PaymentMethodData::BankTransfer(_) - | api::PaymentMethodData::Reward(_) - | api::PaymentMethodData::MandatePayment => { - Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.payment_method), - connector: "Aci", - payment_experience: api_models::enums::PaymentExperience::RedirectToUrl - .to_string(), - })? - } - }; + | api::PaymentMethodData::Reward(_) => Err(errors::ConnectorError::NotSupported { + message: format!("{:?}", item.payment_method), + connector: "Aci", + payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(), + })?, + } + } +} - let auth = AciAuthType::try_from(&item.connector_auth_type)?; - let aci_payment_request = Self { - payment_method: payment_details, - entity_id: auth.entity_id, - amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, - currency: item.request.currency.to_string(), - payment_type: AciPaymentType::Debit, - }; - Ok(aci_payment_request) +impl + TryFrom<( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::WalletData, + )> for AciPaymentsRequest +{ + type Error = Error; + fn try_from( + value: ( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::WalletData, + ), + ) -> Result<Self, Self::Error> { + let (item, wallet_data) = value; + let txn_details = get_transaction_details(item)?; + let payment_method = PaymentDetails::try_from(wallet_data)?; + + Ok(Self { + txn_details, + payment_method, + instruction: None, + shopper_result_url: item.request.router_return_url.clone(), + }) + } +} + +impl + TryFrom<( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::BankRedirectData, + )> for AciPaymentsRequest +{ + type Error = Error; + fn try_from( + value: ( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::BankRedirectData, + ), + ) -> Result<Self, Self::Error> { + let (item, bank_redirect_data) = value; + let txn_details = get_transaction_details(item)?; + let payment_method = PaymentDetails::try_from((item, bank_redirect_data))?; + + Ok(Self { + txn_details, + payment_method, + instruction: None, + shopper_result_url: item.request.router_return_url.clone(), + }) + } +} + +impl + TryFrom<( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::PayLaterData, + )> for AciPaymentsRequest +{ + type Error = Error; + fn try_from( + value: ( + &types::PaymentsAuthorizeRouterData, + &api_models::payments::PayLaterData, + ), + ) -> Result<Self, Self::Error> { + let (item, _pay_later_data) = value; + let txn_details = get_transaction_details(item)?; + let payment_method = PaymentDetails::Klarna; + + Ok(Self { + txn_details, + payment_method, + instruction: None, + shopper_result_url: item.request.router_return_url.clone(), + }) } } +impl TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AciPaymentsRequest { + type Error = Error; + fn try_from( + value: (&types::PaymentsAuthorizeRouterData, &api::Card), + ) -> Result<Self, Self::Error> { + let (item, card_data) = value; + let txn_details = get_transaction_details(item)?; + let payment_method = PaymentDetails::try_from(card_data.clone())?; + let instruction = get_instruction_details(item); + + Ok(Self { + txn_details, + payment_method, + instruction, + shopper_result_url: None, + }) + } +} + +impl + TryFrom<( + &types::PaymentsAuthorizeRouterData, + api_models::payments::MandateIds, + )> for AciPaymentsRequest +{ + type Error = Error; + fn try_from( + value: ( + &types::PaymentsAuthorizeRouterData, + api_models::payments::MandateIds, + ), + ) -> Result<Self, Self::Error> { + let (item, _mandate_data) = value; + let instruction = get_instruction_details(item); + let txn_details = get_transaction_details(item)?; + + Ok(Self { + txn_details, + payment_method: PaymentDetails::Mandate, + instruction, + shopper_result_url: item.request.router_return_url.clone(), + }) + } +} + +fn get_transaction_details( + item: &types::PaymentsAuthorizeRouterData, +) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> { + let auth = AciAuthType::try_from(&item.connector_auth_type)?; + Ok(TransactionDetails { + entity_id: auth.entity_id, + amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + currency: item.request.currency.to_string(), + payment_type: AciPaymentType::Debit, + }) +} + +fn get_instruction_details(item: &types::PaymentsAuthorizeRouterData) -> Option<Instruction> { + if item.request.setup_mandate_details.is_some() { + return Some(Instruction { + mode: InstructionMode::Initial, + transaction_type: InstructionType::Unscheduled, + source: InstructionSource::Cit, + create_registration: Some(true), + }); + } else if item.request.mandate_id.is_some() { + return Some(Instruction { + mode: InstructionMode::Repeated, + transaction_type: InstructionType::Unscheduled, + source: InstructionSource::Mit, + create_registration: None, + }); + } + None +} + impl TryFrom<&types::PaymentsCancelRouterData> for AciCancelRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> { @@ -374,6 +586,7 @@ impl FromStr for AciPaymentStatus { #[serde(rename_all = "camelCase")] pub struct AciPaymentsResponse { id: String, + registration_id: Option<String>, // ndc is an internal unique identifier for the request. ndc: String, timestamp: String, @@ -437,6 +650,14 @@ impl<F, T> } }); + let mandate_reference = item + .response + .registration_id + .map(|id| types::MandateReference { + connector_mandate_id: Some(id), + payment_method_id: None, + }); + Ok(Self { status: { if redirection_data.is_some() { @@ -450,7 +671,7 @@ impl<F, T> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), redirection_data, - mandate_reference: None, + mandate_reference, connector_metadata: None, network_txn_id: None, }), diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index ffebb823f06..d41fe74a4b9 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -267,6 +267,8 @@ pub enum ConnectorError { FlowNotSupported { flow: String, connector: String }, #[error("Capture method not supported")] CaptureMethodNotSupported, + #[error("Missing connector mandate ID")] + MissingConnectorMandateID, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")]
feat
[ACI] implement Card Mandates for ACI (#1174)
b9f640bc9030984a9580ca00596b9d6a7e82e989
2024-11-11 21:38:30
Gnanasundari24
ci(Cypress): Enhance Cybersource Testcases (#6285)
false
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00021-CoreFlows.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00000-CoreFlows.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00021-CoreFlows.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00000-CoreFlows.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00000-AccountCreate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00001-AccountCreate.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00000-AccountCreate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00001-AccountCreate.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00001-CustomerCreate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00002-CustomerCreate.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00001-CustomerCreate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00002-CustomerCreate.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00002-ConnectorCreate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00003-ConnectorCreate.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00002-ConnectorCreate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00003-ConnectorCreate.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00003-NoThreeDSAutoCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00004-NoThreeDSAutoCapture.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00003-NoThreeDSAutoCapture.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00004-NoThreeDSAutoCapture.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00004-ThreeDSAutoCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00005-ThreeDSAutoCapture.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00004-ThreeDSAutoCapture.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00005-ThreeDSAutoCapture.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00005-NoThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00006-NoThreeDSManualCapture.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00005-NoThreeDSManualCapture.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00006-NoThreeDSManualCapture.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00006-VoidPayment.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00007-VoidPayment.cy.js similarity index 65% rename from cypress-tests/cypress/e2e/PaymentTest/00006-VoidPayment.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00007-VoidPayment.cy.js index c783f5e3d72..2b1295fd07c 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00006-VoidPayment.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00007-VoidPayment.cy.js @@ -123,68 +123,65 @@ describe("Card - NoThreeDS Manual payment flow test", () => { } ); - context( - "Card - void payment in Requires_payment_method state flow test", - () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails + context("Card - void payment in success state flow test", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails - beforeEach(function () { - if (!should_continue) { - this.skip(); - } - }); + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))[ - "card_pm" - ]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest( - fixtures.createPaymentBody, - req_data, - res_data, - "no_three_ds", - "manual", - globalState - ); - if (should_continue) - should_continue = utils.should_continue_further(res_data); - }); + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "manual", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); + it("payment_methods-call-test", () => { + cy.paymentMethodsCallTest(globalState); + }); - it("confirm-call-test", () => { - console.log("confirm -> " + globalState.get("connectorId")); - let data = getConnectorDetails(globalState.get("connectorId"))[ - "card_pm" - ]["No3DSManualCapture"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - console.log("det -> " + data.card); - cy.confirmCallTest( - fixtures.confirmBody, - req_data, - res_data, - false, - globalState - ); - if (should_continue) - should_continue = utils.should_continue_further(res_data); - }); + it("confirm-call-test", () => { + console.log("confirm -> " + globalState.get("connectorId")); + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSManualCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + console.log("det -> " + data.card); + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + false, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); - it("void-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))[ - "card_pm" - ]["VoidAfterConfirm"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.voidCallTest(fixtures.voidBody, req_data, res_data, globalState); - if (should_continue) - should_continue = utils.should_continue_further(res_data); - }); - } - ); + it("void-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "VoidAfterConfirm" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.voidCallTest(fixtures.voidBody, req_data, res_data, globalState); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); }); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00007-SyncPayment.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00008-SyncPayment.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00007-SyncPayment.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00008-SyncPayment.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00008-RefundPayment.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00009-RefundPayment.cy.js similarity index 99% rename from cypress-tests/cypress/e2e/PaymentTest/00008-RefundPayment.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00009-RefundPayment.cy.js index 70157e06ec6..9eb64c0acf2 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00008-RefundPayment.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00009-RefundPayment.cy.js @@ -421,7 +421,7 @@ describe("Card - Refund flow - No 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "Refund" + "manualPaymentRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -526,7 +526,7 @@ describe("Card - Refund flow - No 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "PartialRefund" + "manualPaymentPartialRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -542,7 +542,7 @@ describe("Card - Refund flow - No 3DS", () => { }); it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "PartialRefund" + "manualPaymentPartialRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -650,7 +650,7 @@ describe("Card - Refund flow - No 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "Refund" + "manualPaymentRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -755,7 +755,7 @@ describe("Card - Refund flow - No 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "PartialRefund" + "manualPaymentPartialRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -1297,7 +1297,7 @@ describe("Card - Refund flow - 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "Refund" + "manualPaymentRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -1405,7 +1405,7 @@ describe("Card - Refund flow - 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "Refund" + "manualPaymentPartialRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -1421,7 +1421,7 @@ describe("Card - Refund flow - 3DS", () => { }); it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "Refund" + "manualPaymentPartialRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -1529,7 +1529,7 @@ describe("Card - Refund flow - 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "Refund" + "manualPaymentRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; @@ -1637,7 +1637,7 @@ describe("Card - Refund flow - 3DS", () => { it("refund-call-test", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ - "Refund" + "manualPaymentRefund" ]; let req_data = data["Request"]; let res_data = data["Response"]; diff --git a/cypress-tests/cypress/e2e/PaymentTest/00009-SyncRefund.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00010-SyncRefund.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00009-SyncRefund.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00010-SyncRefund.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00010-CreateSingleuseMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00011-CreateSingleuseMandate.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00010-CreateSingleuseMandate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00011-CreateSingleuseMandate.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00011-CreateMultiuseMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00012-CreateMultiuseMandate.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00011-CreateMultiuseMandate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00012-CreateMultiuseMandate.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00012-ListAndRevokeMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00012-ListAndRevokeMandate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00013-SaveCardFlow.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00014-SaveCardFlow.cy.js similarity index 72% rename from cypress-tests/cypress/e2e/PaymentTest/00013-SaveCardFlow.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00014-SaveCardFlow.cy.js index e74c8fc9dd4..cbff06ed640 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00013-SaveCardFlow.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00014-SaveCardFlow.cy.js @@ -493,4 +493,191 @@ describe("Card - SaveCard payment flow test", () => { }); } ); + + context( + "Save card for NoThreeDS automatic capture payment - create and confirm [off_session]", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + saveCardBody = Cypress._.cloneDeep(fixtures.saveCardConfirmBody); + if (!should_continue) { + this.skip(); + } + }); + + it("customer-create-call-test", () => { + cy.createCustomerCallTest(fixtures.customerCreateBody, globalState); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntentOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSAutoCaptureOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-payment-call-test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("retrieve-customerPM-call-test", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntentOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-save-card-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardConfirmAutoCaptureOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.saveCardConfirmCallTest( + saveCardBody, + req_data, + res_data, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + } + ); + context( + "Use billing address from payment method during subsequent payment[off_session]", + () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + saveCardBody = Cypress._.cloneDeep(fixtures.saveCardConfirmBody); + if (!should_continue) { + this.skip(); + } + }); + + it("customer-create-call-test", () => { + cy.createCustomerCallTest(fixtures.customerCreateBody, globalState); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntentOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSAutoCaptureOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("retrieve-customerPM-call-test", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntentOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-save-card-payment-call-test-without-billing", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardConfirmAutoCaptureOffSessionWithoutBilling"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.saveCardConfirmCallTest( + saveCardBody, + req_data, + res_data, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + } + ); }); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00014-ZeroAuthMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00015-ZeroAuthMandate.cy.js similarity index 53% rename from cypress-tests/cypress/e2e/PaymentTest/00014-ZeroAuthMandate.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00015-ZeroAuthMandate.cy.js index a6e085658c6..b9083142727 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00014-ZeroAuthMandate.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00015-ZeroAuthMandate.cy.js @@ -108,4 +108,92 @@ describe("Card - SingleUse Mandates flow test", () => { }); } ); + + context("Card - Zero Auth Payment", () => { + let should_continue = true; // variable that will be used to skip tests if a previous test fails + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create No 3DS Payment Intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "ZeroAuthPaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm No 3DS payment", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "ZeroAuthConfirmPayment" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Retrieve Payment Call Test", () => { + cy.retrievePaymentCallTest(globalState); + }); + + it("Retrieve CustomerPM Call Test", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("Create Recurring Payment Intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntentOffSession" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm Recurring Payment", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SaveCardConfirmAutoCaptureOffSession" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + + cy.saveCardConfirmCallTest( + fixtures.saveCardConfirmBody, + req_data, + res_data, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + }); }); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00015-ThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00016-ThreeDSManualCapture.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00015-ThreeDSManualCapture.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00016-ThreeDSManualCapture.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00016-BankTransfers.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00017-BankTransfers.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00016-BankTransfers.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00017-BankTransfers.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00017-BankRedirect.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00018-BankRedirect.cy.js similarity index 82% rename from cypress-tests/cypress/e2e/PaymentTest/00017-BankRedirect.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00018-BankRedirect.cy.js index 85a63ca008c..f3c81c16ab2 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00017-BankRedirect.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00018-BankRedirect.cy.js @@ -196,71 +196,6 @@ describe("Bank Redirect tests", () => { }); }); - context("Giropay Create and Confirm flow test", () => { - let should_continue = true; // variable that will be used to skip tests if a previous test fails - - before("seed global state", () => { - cy.task("getGlobalState").then((state) => { - globalState = new State(state); - }); - }); - - beforeEach(function () { - if (!should_continue) { - this.skip(); - } - }); - it("create-payment-call-test", () => { - let data = getConnectorDetails(globalState.get("connectorId"))[ - "bank_redirect_pm" - ]["PaymentIntent"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.createPaymentIntentTest( - fixtures.createPaymentBody, - req_data, - res_data, - "three_ds", - "automatic", - globalState - ); - if (should_continue) - should_continue = utils.should_continue_further(res_data); - }); - - it("payment_methods-call-test", () => { - cy.paymentMethodsCallTest(globalState); - }); - - it("Confirm bank redirect", () => { - let data = getConnectorDetails(globalState.get("connectorId"))[ - "bank_redirect_pm" - ]["Giropay"]; - let req_data = data["Request"]; - let res_data = data["Response"]; - cy.confirmBankRedirectCallTest( - fixtures.confirmBody, - req_data, - res_data, - true, - globalState - ); - if (should_continue) - should_continue = utils.should_continue_further(res_data); - }); - - it("Handle bank redirect redirection", () => { - // return_url is a static url (https://hyperswitch.io) taken from confirm-body fixture and is not updated - let expected_redirection = fixtures.confirmBody["return_url"]; - let payment_method_type = globalState.get("paymentMethodType"); - cy.handleBankRedirectRedirection( - globalState, - payment_method_type, - expected_redirection - ); - }); - }); - context("Sofort Create and Confirm flow test", () => { let should_continue = true; // variable that will be used to skip tests if a previous test fails diff --git a/cypress-tests/cypress/e2e/PaymentTest/00018-MandatesUsingPMID.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00019-MandatesUsingPMID.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00018-MandatesUsingPMID.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00019-MandatesUsingPMID.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00019-UPI.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00020-UPI.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00019-UPI.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00020-UPI.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00020-Variations.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00021-Variations.cy.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentTest/00020-Variations.cy.js rename to cypress-tests/cypress/e2e/PaymentTest/00021-Variations.cy.js diff --git a/cypress-tests/cypress/e2e/PaymentTest/00022-PaymentMethods.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00022-PaymentMethods.cy.js new file mode 100644 index 00000000000..c27604a07d6 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00022-PaymentMethods.cy.js @@ -0,0 +1,108 @@ +import * as fixtures from "../../fixtures/imports"; +import State from "../../utils/State"; +import getConnectorDetails, * as utils from "../PaymentUtils/Utils"; + +let globalState; + +describe("Payment Methods Tests", () => { + let should_continue = true; + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + context("Create payment method for customer", () => { + let should_continue = true; + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create customer", () => { + cy.createCustomerCallTest(fixtures.customerCreateBody, globalState); + }); + + it("Create Payment Method", () => { + let data = getConnectorDetails("commons")["card_pm"]["PaymentMethod"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentMethodTest(globalState, req_data, res_data); + }); + + it("List PM for customer", () => { + cy.listCustomerPMCallTest(globalState); + }); + }); + + context("Set default payment method", () => { + let should_continue = true; + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("List PM for customer", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("Create Payment Method", () => { + let data = getConnectorDetails("commons")["card_pm"]["PaymentMethod"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentMethodTest(globalState, req_data, res_data); + }); + + it("create-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntentOffSession" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("confirm-payment-call-test", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SaveCardUseNo3DSAutoCaptureOffSession" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("List PM for customer", () => { + cy.listCustomerPMCallTest(globalState); + }); + + it("Set default payment method", () => { + cy.setDefaultPaymentMethodTest(globalState); + }); + }); +}); diff --git a/cypress-tests/cypress/e2e/PaymentTest/00023-ConnectorAgnostic.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00023-ConnectorAgnostic.cy.js new file mode 100644 index 00000000000..64abe296b29 --- /dev/null +++ b/cypress-tests/cypress/e2e/PaymentTest/00023-ConnectorAgnostic.cy.js @@ -0,0 +1,250 @@ +import * as fixtures from "../../fixtures/imports"; +import State from "../../utils/State"; +import { payment_methods_enabled } from "../PaymentUtils/Commons"; +import getConnectorDetails, * as utils from "../PaymentUtils/Utils"; +let globalState; +describe("Connector Agnostic Tests", () => { + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + context( + "Connector Agnostic Disabled for Profile 1 and Enabled for Profile 2", + () => { + let should_continue = true; + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create Business Profile", () => { + cy.createBusinessProfileTest( + fixtures.createBusinessProfile, + globalState + ); + }); + + it("connector-create-call-test", () => { + cy.createConnectorCallTest( + "payment_processor", + fixtures.createConnectorBody, + payment_methods_enabled, + globalState + ); + }); + + it("Create Customer", () => { + cy.createCustomerCallTest(fixtures.customerCreateBody, globalState); + }); + + it("Create Payment Intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntentOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm Payment", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["SaveCardUseNo3DSAutoCaptureOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("List Payment Method for Customer using Client Secret", () => { + cy.listCustomerPMByClientSecret(globalState); + }); + + it("Create Business Profile", () => { + cy.createBusinessProfileTest( + fixtures.createBusinessProfile, + globalState + ); + }); + + it("connector-create-call-test", () => { + cy.createConnectorCallTest( + "payment_processor", + fixtures.createConnectorBody, + payment_methods_enabled, + globalState + ); + }); + + it("Enable Connector Agnostic for Business Profile", () => { + cy.UpdateBusinessProfileTest( + fixtures.updateBusinessProfile, + true, + globalState + ); + }); + + it("Create Payment Intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["PaymentIntentOffSession"]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("List Payment Method for Customer", () => { + cy.listCustomerPMByClientSecret(globalState); + }); + } + ); + + context("Connector Agnostic Enabled for Profile 1 and Profile 2", () => { + let should_continue = true; + + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + it("Create Business Profile", () => { + cy.createBusinessProfileTest(fixtures.createBusinessProfile, globalState); + }); + + it("connector-create-call-test", () => { + cy.createConnectorCallTest( + "payment_processor", + fixtures.createConnectorBody, + payment_methods_enabled, + globalState + ); + }); + + it("Create Customer", () => { + cy.createCustomerCallTest(fixtures.customerCreateBody, globalState); + }); + + it("Enable Connector Agnostic for Business Profile", () => { + cy.UpdateBusinessProfileTest( + fixtures.updateBusinessProfile, + true, + globalState + ); + }); + + it("Create Payment Intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntentOffSession" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("Confirm Payment", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "SaveCardUseNo3DSAutoCaptureOffSession" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.confirmCallTest( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("List Payment Method for Customer using Client Secret", () => { + cy.listCustomerPMByClientSecret(globalState); + }); + + it("Create Business Profile", () => { + cy.createBusinessProfileTest(fixtures.createBusinessProfile, globalState); + }); + + it("connector-create-call-test", () => { + cy.createConnectorCallTest( + "payment_processor", + fixtures.createConnectorBody, + payment_methods_enabled, + globalState + ); + }); + + it("Enable Connector Agnostic for Business Profile", () => { + cy.UpdateBusinessProfileTest( + fixtures.updateBusinessProfile, + true, + globalState + ); + }); + + it("Create Payment Intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntentOffSession" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.createPaymentIntentTest( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + if (should_continue) + should_continue = utils.should_continue_further(res_data); + }); + + it("List Payment Method for Customer", () => { + cy.listCustomerPMByClientSecret(globalState); + }); + }); +}); diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js index e39838d03a8..9ce384c7a74 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js @@ -67,6 +67,8 @@ export const connectorDetails = { }, PaymentIntentOffSession: { Request: { + amount: 6500, + authentication_type: "no_three_ds", currency: "USD", customer_acceptance: null, setup_future_usage: "off_session", @@ -91,7 +93,7 @@ export const connectorDetails = { Response: { status: 200, body: { - status: "processing", + status: "requires_customer_action", }, }, }, @@ -178,7 +180,7 @@ export const connectorDetails = { }, }, }, - Void: { + VoidAfterConfirm: { Request: {}, Response: { status: 200, @@ -186,6 +188,12 @@ export const connectorDetails = { status: "processing", }, }, + ResponseCustom: { + status: 200, + body: { + status: "cancelled", + }, + }, }, Refund: { Request: { @@ -209,6 +217,48 @@ export const connectorDetails = { }, }, }, + manualPaymentRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", + code: "IR_14", + }, + }, + }, + }, + manualPaymentPartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", + code: "IR_14", + }, + }, + }, + }, SyncRefund: { Request: { currency: "USD", @@ -364,6 +414,37 @@ export const connectorDetails = { }, }, }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + setup_future_usage: "off_session", + }, + }, + }, SaveCardUseNo3DSAutoCapture: { Request: { payment_method: "card", @@ -391,6 +472,7 @@ export const connectorDetails = { SaveCardUseNo3DSAutoCaptureOffSession: { Request: { payment_method: "card", + payment_method_type: "debit", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -708,7 +790,10 @@ export const connectorDetails = { Response: { status: 200, body: { - status: "requires_customer_action", + status: "processing", + error_code: "905_1", + error_message: + "Could not find an acquirer account for the provided txvariant (giropay), currency (EUR), and action (AUTH).", }, }, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js index 17acf01e881..4a443e0962a 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js @@ -66,6 +66,8 @@ export const connectorDetails = { PaymentIntentOffSession: { Request: { currency: "USD", + amount: 6500, + authentication_type: "no_three_ds", customer_acceptance: null, setup_future_usage: "off_session", }, @@ -200,6 +202,7 @@ export const connectorDetails = { }, }, }, + PartialRefund: { Request: { payment_method: "card", @@ -216,6 +219,38 @@ export const connectorDetails = { }, }, }, + manualPaymentRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + manualPaymentPartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, SyncRefund: { Request: { payment_method: "card", @@ -376,6 +411,37 @@ export const connectorDetails = { }, }, }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + setup_future_usage: "off_session", + }, + }, + }, SaveCardUseNo3DSAutoCapture: { Request: { payment_method: "card", @@ -403,6 +469,7 @@ export const connectorDetails = { SaveCardUseNo3DSAutoCaptureOffSession: { Request: { payment_method: "card", + payment_method_type: "debit", payment_method_data: { card: successfulNo3DSCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js b/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js index 74548be9d41..6dfe0131bc3 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Bluesnap.js @@ -43,7 +43,7 @@ export const connectorDetails = { status: 200, trigger_skip: true, body: { - status: "requires_capture", + status: "requires_customer_action", }, }, }, @@ -171,6 +171,38 @@ export const connectorDetails = { }, }, }, + manualPaymentRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + manualPaymentPartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, SyncRefund: { Request: { payment_method: "card", @@ -199,6 +231,40 @@ export const connectorDetails = { }, }, }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 501, + body: { + error: { + type: "invalid_request", + message: "Setup Mandate flow for Bluesnap is not implemented", + code: "IR_00", + }, + }, + }, + }, SaveCardUseNo3DSAutoCapture: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Commons.js b/cypress-tests/cypress/e2e/PaymentUtils/Commons.js index 01905ee0532..41de9bf2ff4 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Commons.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Commons.js @@ -56,6 +56,13 @@ const successfulThreeDSTestCardDetails = { card_cvc: "999", }; +const PaymentMethodCardDetails = { + card_number: "4111111145551142", + card_exp_month: "03", + card_exp_year: "30", + card_holder_name: "Joseph Doe", +}; + const singleUseMandateData = { customer_acceptance: { acceptance_type: "offline", @@ -707,6 +714,38 @@ export const connectorDetails = { }, }, }), + manualPaymentRefund: getCustomExchange({ + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }), + manualPaymentPartialRefund: getCustomExchange({ + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }), PartialRefund: getCustomExchange({ Request: { payment_method: "card", @@ -817,6 +856,23 @@ export const connectorDetails = { mandate_data: singleUseMandateData, }, }), + ZeroAuthPaymentIntent: getCustomExchange({ + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + payment_type: "setup_mandate", + }, + }), + ZeroAuthConfirmPayment: getCustomExchange({ + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + }), SaveCardUseNo3DSAutoCapture: getCustomExchange({ Request: { payment_method: "card", @@ -879,6 +935,19 @@ export const connectorDetails = { setup_future_usage: "off_session", }, }), + SaveCardConfirmAutoCaptureOffSessionWithoutBilling: { + Request: { + setup_future_usage: "off_session", + billing: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + billing: null, + }, + }, + }, SaveCardUseNo3DSManualCapture: getCustomExchange({ Request: { payment_method: "card", @@ -897,6 +966,19 @@ export const connectorDetails = { }, }, }), + PaymentMethod: { + Request: { + payment_method: "card", + payment_method_type: "credit", + payment_method_issuer: "Gpay", + payment_method_issuer_code: "jp_hdfc", + card: PaymentMethodCardDetails, + }, + Response: { + status: 200, + body: {}, + }, + }, PaymentMethodIdMandateNo3DSAutoCapture: getCustomExchange({ Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js index d71f11b4e6e..ca24a50bcef 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js @@ -48,6 +48,48 @@ const multiUseMandateData = { }, }; +const payment_method_data_no3ds = { + card: { + last4: "4242", + card_type: "CREDIT", + card_network: "Visa", + card_issuer: "STRIPE PAYMENTS UK LIMITED", + card_issuing_country: "UNITEDKINGDOM", + card_isin: "424242", + card_extended_bin: null, + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: null, + payment_checks: { + avs_response: { + code: "Y", + codeRaw: "Y", + }, + card_verification: null, + }, + authentication_data: null, + }, + billing: null, +}; + +const payment_method_data_3ds = { + card: { + last4: "1091", + card_type: "CREDIT", + card_network: "Visa", + card_issuer: "INTL HDQTRS-CENTER OWNED", + card_issuing_country: "UNITEDSTATES", + card_isin: "400000", + card_extended_bin: null, + card_exp_month: "01", + card_exp_year: "25", + card_holder_name: null, + payment_checks: null, + authentication_data: null, + }, + billing: null, +}; + export const connectorDetails = { card_pm: { PaymentIntent: { @@ -60,12 +102,15 @@ export const connectorDetails = { status: 200, body: { status: "requires_payment_method", + setup_future_usage: "on_session", }, }, }, PaymentIntentOffSession: { Request: { currency: "USD", + amount: 6500, + authentication_type: "no_three_ds", customer_acceptance: null, setup_future_usage: "off_session", }, @@ -73,6 +118,7 @@ export const connectorDetails = { status: 200, body: { status: "requires_payment_method", + setup_future_usage: "off_session", }, }, }, @@ -89,7 +135,9 @@ export const connectorDetails = { Response: { status: 200, body: { - status: "requires_capture", + status: "requires_customer_action", + setup_future_usage: "on_session", + payment_method_data: payment_method_data_3ds, }, }, }, @@ -107,6 +155,8 @@ export const connectorDetails = { status: 200, body: { status: "requires_customer_action", + setup_future_usage: "on_session", + payment_method_data: payment_method_data_3ds, }, }, }, @@ -124,6 +174,9 @@ export const connectorDetails = { status: 200, body: { status: "requires_capture", + payment_method: "card", + attempt_count: 1, + payment_method_data: payment_method_data_no3ds, }, }, }, @@ -141,6 +194,9 @@ export const connectorDetails = { status: 200, body: { status: "succeeded", + payment_method: "card", + attempt_count: 1, + payment_method_data: payment_method_data_no3ds, }, }, }, @@ -200,6 +256,48 @@ export const connectorDetails = { }, }, }, + manualPaymentRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", + code: "IR_14", + }, + }, + }, + }, + manualPaymentPartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: + "This Payment could not be refund because it has a status of processing. The expected state is succeeded, partially_captured", + code: "IR_14", + }, + }, + }, + }, PartialRefund: { Request: { payment_method: "card", @@ -376,9 +474,41 @@ export const connectorDetails = { }, }, }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + setup_future_usage: "off_session", + }, + }, + }, SaveCardUseNo3DSAutoCapture: { Request: { payment_method: "card", + payment_method_type: "debit", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -403,6 +533,7 @@ export const connectorDetails = { SaveCardUseNo3DSAutoCaptureOffSession: { Request: { payment_method: "card", + payment_method_type: "debit", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -426,6 +557,7 @@ export const connectorDetails = { SaveCardUseNo3DSManualCaptureOffSession: { Request: { payment_method: "card", + payment_method_type: "debit", payment_method_data: { card: successfulNo3DSCardDetails, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js b/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js index 30a9e3eb9b2..f6350ac84bd 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Nmi.js @@ -14,6 +14,15 @@ const successfulThreeDSTestCardDetails = { card_cvc: "999", }; +const customerAcceptance = { + acceptance_type: "offline", + accepted_at: "1963-05-03T04:07:52.723Z", + online: { + ip_address: "127.0.0.1", + user_agent: "amet irure esse", + }, +}; + export const connectorDetails = { card_pm: { PaymentIntent: { @@ -35,7 +44,6 @@ export const connectorDetails = { payment_method_data: { card: successfulThreeDSTestCardDetails, }, - currency: "USD", customer_acceptance: null, setup_future_usage: "on_session", }, @@ -52,7 +60,6 @@ export const connectorDetails = { payment_method_data: { card: successfulThreeDSTestCardDetails, }, - currency: "USD", customer_acceptance: null, setup_future_usage: "on_session", }, @@ -69,7 +76,6 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", customer_acceptance: null, setup_future_usage: "on_session", }, @@ -86,7 +92,6 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", customer_acceptance: null, setup_future_usage: "on_session", }, @@ -103,7 +108,6 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", customer_acceptance: null, }, Response: { @@ -127,6 +131,15 @@ export const connectorDetails = { }, }, Void: { + Request: {}, + Response: { + status: 200, + body: { + status: "cancelled", + }, + }, + }, + VoidAfterConfirm: { Request: {}, Response: { status: 400, @@ -140,13 +153,13 @@ export const connectorDetails = { }, }, }, + Refund: { Request: { payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", customer_acceptance: null, }, Response: { @@ -162,7 +175,36 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + manualPaymentRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "pending", + }, + }, + }, + manualPaymentPartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, customer_acceptance: null, }, Response: { @@ -178,7 +220,6 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", customer_acceptance: null, }, Response: { @@ -200,23 +241,48 @@ export const connectorDetails = { }, }, }, - SaveCardUseNo3DSAutoCapture: { + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { Request: { + payment_type: "setup_mandate", payment_method: "card", payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", - setup_future_usage: "on_session", - customer_acceptance: { - acceptance_type: "offline", - accepted_at: "1963-05-03T04:07:52.723Z", - online: { - ip_address: "127.0.0.1", - user_agent: "amet irure esse", + }, + Response: { + status: 501, + body: { + error: { + type: "invalid_request", + message: "Setup Mandate flow for Nmi is not implemented", + code: "IR_00", }, }, }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + setup_future_usage: "on_session", + customer_acceptance: customerAcceptance, + }, Response: { status: 200, body: { @@ -230,16 +296,8 @@ export const connectorDetails = { payment_method_data: { card: successfulNo3DSCardDetails, }, - currency: "USD", setup_future_usage: "on_session", - customer_acceptance: { - acceptance_type: "offline", - accepted_at: "1963-05-03T04:07:52.723Z", - online: { - ip_address: "127.0.0.1", - user_agent: "amet irure esse", - }, - }, + customer_acceptance: customerAcceptance, }, Response: { status: 200, @@ -248,5 +306,42 @@ export const connectorDetails = { }, }, }, + PaymentMethodIdMandate3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + mandate_data: null, + authentication_type: "three_ds", + customer_acceptance: customerAcceptance, + }, + Response: { + // Skipping redirection here for mandate 3ds auto capture as it requires changes from the core + trigger_skip: true, + status: 200, + body: { + status: "requires_customer_action", + }, + }, + }, + PaymentMethodIdMandate3DSManualCapture: { + Request: { + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + mandate_data: null, + authentication_type: "three_ds", + customer_acceptance: customerAcceptance, + }, + Response: { + trigger_skip: true, + + status: 200, + body: { + status: "requires_customer_action", + }, + }, + }, }, }; diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js index 1c64393dda2..269fd3ea0b8 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Paypal.js @@ -45,7 +45,7 @@ export const connectorDetails = { status: 200, trigger_skip: true, body: { - status: "requires_capture", + status: "requires_customer_action", }, }, }, @@ -173,6 +173,38 @@ export const connectorDetails = { }, }, }, + manualPaymentRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + manualPaymentPartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, SyncRefund: { Request: { payment_method: "card", @@ -201,6 +233,40 @@ export const connectorDetails = { }, }, }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 501, + body: { + error: { + type: "invalid_request", + message: "Setup Mandate flow for Paypal is not implemented", + code: "IR_00", + }, + }, + }, + }, SaveCardUseNo3DSAutoCapture: { Request: { payment_method: "card", @@ -333,7 +399,7 @@ export const connectorDetails = { status: 200, body: { status: "failed", - error_code: "NOT_AUTHORIZED", + error_code: "PERMISSION_DENIED", }, }, }, @@ -370,7 +436,7 @@ export const connectorDetails = { status: 200, body: { status: "failed", - error_code: "NOT_AUTHORIZED", + error_code: "PERMISSION_DENIED", }, }, }, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js index 3b44f0e4e1e..98af56b882c 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js @@ -110,6 +110,8 @@ export const connectorDetails = { Request: { currency: "USD", customer_acceptance: null, + amount: 6500, + authentication_type: "no_three_ds", setup_future_usage: "off_session", }, Response: { @@ -255,6 +257,37 @@ export const connectorDetails = { }, }, }, + manualPaymentRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + manualPaymentPartialRefund: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "USD", + customer_acceptance: null, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, PartialRefund: { Request: { payment_method: "card", @@ -431,6 +464,37 @@ export const connectorDetails = { }, }, }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 200, + body: { + status: "succeeded", + setup_future_usage: "off_session", + }, + }, + }, SaveCardUseNo3DSAutoCapture: { Request: { payment_method: "card", @@ -506,6 +570,7 @@ export const connectorDetails = { SaveCardUseNo3DSAutoCaptureOffSession: { Request: { payment_method: "card", + payment_method_type: "debit", payment_method_data: { card: successfulNo3DSCardDetails, }, @@ -575,6 +640,20 @@ export const connectorDetails = { }, }, }, + SaveCardConfirmAutoCaptureOffSessionWithoutBilling: { + Request: { + setup_future_usage: "off_session", + billing: null, + }, + Response: { + status: 200, + body: { + status: "failed", + error_message: + "You cannot confirm with `off_session=true` when `setup_future_usage` is also set on the PaymentIntent. The customer needs to be on-session to perform the steps which may be required to set up the PaymentMethod for future usage. Please confirm this PaymentIntent with your customer on-session.", + }, + }, + }, PaymentMethodIdMandateNo3DSManualCapture: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js b/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js index c209fe5a6dc..36d8906fadb 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Trustpay.js @@ -214,6 +214,40 @@ export const connectorDetails = { }, }, }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "USD", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 501, + body: { + error: { + type: "invalid_request", + message: "Setup Mandate flow for Trustpay is not implemented", + code: "IR_00", + }, + }, + }, + }, SaveCardUseNo3DSAutoCapture: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/fixtures/create-business-profile.json b/cypress-tests/cypress/fixtures/create-business-profile.json new file mode 100644 index 00000000000..cdce8636157 --- /dev/null +++ b/cypress-tests/cypress/fixtures/create-business-profile.json @@ -0,0 +1,3 @@ +{ + "profile_name": "default" +} \ No newline at end of file diff --git a/cypress-tests/cypress/fixtures/create-connector-body.json b/cypress-tests/cypress/fixtures/create-connector-body.json index 54a96d8f6ee..724119e0dfc 100644 --- a/cypress-tests/cypress/fixtures/create-connector-body.json +++ b/cypress-tests/cypress/fixtures/create-connector-body.json @@ -1,7 +1,6 @@ { "connector_name": "stripe", - "business_country": "US", - "business_label": "default", + "profile_id": "{{profile_id}}", "connector_account_details": { "auth_type": "BodyKey", "api_key": "api-key", diff --git a/cypress-tests/cypress/fixtures/create-payment-body.json b/cypress-tests/cypress/fixtures/create-payment-body.json index c9982e4d755..ea1d22d364e 100644 --- a/cypress-tests/cypress/fixtures/create-payment-body.json +++ b/cypress-tests/cypress/fixtures/create-payment-body.json @@ -5,6 +5,7 @@ "description": "Joseph First Crypto", "email": "[email protected]", "setup_future_usage": null, + "profile_id": "{{profile_id}}", "connector_metadata": { "noon": { "order_category": "applepay" diff --git a/cypress-tests/cypress/fixtures/imports.js b/cypress-tests/cypress/fixtures/imports.js index d5cc66b7d29..900e4f4ea3a 100644 --- a/cypress-tests/cypress/fixtures/imports.js +++ b/cypress-tests/cypress/fixtures/imports.js @@ -2,6 +2,7 @@ import captureBody from "./capture-flow-body.json"; import configs from "./configs.json"; import confirmBody from "./confirm-body.json"; import apiKeyCreateBody from "./create-api-key-body.json"; +import createBusinessProfile from "./create-business-profile.json"; import createConfirmPaymentBody from "./create-confirm-body.json"; import createConnectorBody from "./create-connector-body.json"; import customerCreateBody from "./create-customer-body.json"; @@ -17,7 +18,9 @@ import merchantUpdateBody from "./merchant-update-body.json"; import refundBody from "./refund-flow-body.json"; import routingConfigBody from "./routing-config-body.json"; import saveCardConfirmBody from "./save-card-confirm-body.json"; +import sessionTokenBody from "./session-token.json"; import apiKeyUpdateBody from "./update-api-key-body.json"; +import updateBusinessProfile from "./update-business-profile.json"; import updateConnectorBody from "./update-connector-body.json"; import customerUpdateBody from "./update-customer-body.json"; import voidBody from "./void-payment-body.json"; @@ -29,6 +32,7 @@ export { citConfirmBody, configs, confirmBody, + createBusinessProfile, createConfirmPaymentBody, createConnectorBody, createPaymentBody, @@ -44,6 +48,8 @@ export { refundBody, routingConfigBody, saveCardConfirmBody, + sessionTokenBody, + updateBusinessProfile, updateConnectorBody, voidBody, }; diff --git a/cypress-tests/cypress/fixtures/session-token.json b/cypress-tests/cypress/fixtures/session-token.json new file mode 100644 index 00000000000..84d5be3ff75 --- /dev/null +++ b/cypress-tests/cypress/fixtures/session-token.json @@ -0,0 +1,5 @@ +{ + "payment_id": "{{payment_id}}", + "client_secret": "{{client_secret}}", + "wallets": [] +} diff --git a/cypress-tests/cypress/fixtures/update-business-profile.json b/cypress-tests/cypress/fixtures/update-business-profile.json new file mode 100644 index 00000000000..9d69534bae6 --- /dev/null +++ b/cypress-tests/cypress/fixtures/update-business-profile.json @@ -0,0 +1,3 @@ +{ + "is_connector_agnostic_mit_enabled": true +} diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js index 5b2ae9bb8ad..6204c86f44a 100644 --- a/cypress-tests/cypress/support/commands.js +++ b/cypress-tests/cypress/support/commands.js @@ -57,6 +57,7 @@ Cypress.Commands.add( logRequestId(response.headers["x-request-id"]); // Handle the response as needed + globalState.set("profileId", response.body.default_profile); globalState.set("publishableKey", response.body.publishable_key); globalState.set("merchantDetails", response.body.merchant_details); }); @@ -163,6 +164,59 @@ Cypress.Commands.add( } ); +Cypress.Commands.add( + "createBusinessProfileTest", + (createBusinessProfile, globalState) => { + const merchant_id = globalState.get("merchantId"); + const randomProfileName = `profile_${Math.random().toString(36).substring(7)}`; + createBusinessProfile.profile_name = randomProfileName; + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/account/${merchant_id}/business_profile`, + headers: { + Accept: "application/json", + "Content-Type": "application/json", + "api-key": globalState.get("adminApiKey"), + }, + body: createBusinessProfile, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + globalState.set("profileId", response.body.profile_id); + if (response.status === 200) { + expect(response.body.profile_id).to.not.to.be.null; + } else { + throw new Error( + `Business Profile call failed ${response.body.error.message}` + ); + } + }); + } +); + +Cypress.Commands.add( + "UpdateBusinessProfileTest", + (updateBusinessProfile, is_connector_agnostic_mit_enabled, globalState) => { + updateBusinessProfile.is_connector_agnostic_mit_enabled = + is_connector_agnostic_mit_enabled; + const merchant_id = globalState.get("merchantId"); + const profile_id = globalState.get("profileId"); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/account/${merchant_id}/business_profile/${profile_id}`, + headers: { + Accept: "application/json", + "Content-Type": "application/json", + "api-key": globalState.get("adminApiKey"), + }, + body: updateBusinessProfile, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + }); + } +); + Cypress.Commands.add("apiKeyCreateTest", (apiKeyCreateBody, globalState) => { cy.request({ method: "POST", @@ -353,6 +407,7 @@ Cypress.Commands.add( ) => { const merchantId = globalState.get("merchantId"); createConnectorBody.connector_type = connectorType; + createConnectorBody.profile_id = globalState.get("profileId"); createConnectorBody.connector_name = globalState.get("connectorId"); createConnectorBody.payment_methods_enabled = payment_methods_enabled; // readFile is used to read the contents of the file and it always returns a promise ([Object Object]) due to its asynchronous nature @@ -390,6 +445,7 @@ Cypress.Commands.add( expect(globalState.get("connectorId")).to.equal( response.body.connector_name ); + globalState.set("profileId", response.body.profile_id); globalState.set( "merchantConnectorId", response.body.merchant_connector_id @@ -418,6 +474,8 @@ Cypress.Commands.add( createConnectorBody.connector_type = connectorType; createConnectorBody.connector_name = connectorName; createConnectorBody.connector_type = "payout_processor"; + createConnectorBody.profile_id = globalState.get("profileId"); + // readFile is used to read the contents of the file and it always returns a promise ([Object Object]) due to its asynchronous nature // it is best to use then() to handle the response within the same block of code cy.readFile(globalState.get("connectorAuthFilePath")).then( @@ -588,9 +646,22 @@ Cypress.Commands.add( }, body: customerCreateBody, }).then((response) => { - logRequestId(response.headers["x-request-id"]); - expect(response.body.customer_id).to.not.be.empty; globalState.set("customerId", response.body.customer_id); + logRequestId(response.headers["x-request-id"]); + expect(response.body.customer_id, "customer_id").to.not.be.empty; + expect(customerCreateBody.email, "email").to.equal(response.body.email); + expect(customerCreateBody.name, "name").to.equal(response.body.name); + expect(customerCreateBody.phone, "phone").to.equal(response.body.phone); + expect(customerCreateBody.metadata, "metadata").to.deep.equal( + response.body.metadata + ); + expect(customerCreateBody.address, "address").to.deep.equal( + response.body.address + ); + expect( + customerCreateBody.phone_country_code, + "phone_country_code" + ).to.equal(response.body.phone_country_code); }); } ); @@ -772,6 +843,22 @@ Cypress.Commands.add( } ); +Cypress.Commands.add("sessionTokenCall", (apiKeyCreateBody, globalState) => { + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/payments/session_tokens`, + headers: { + Accept: "application/json", + "Content-Type": "application/json", + "api-key": globalState.get("publishableKey"), + }, + body: sessionTokenBody, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + }); +}); + Cypress.Commands.add( "createPaymentIntentTest", ( @@ -796,9 +883,9 @@ Cypress.Commands.add( createPaymentBody[key] = req_data[key]; } createPaymentBody.authentication_type = authentication_type; - createPaymentBody.capture_method = capture_method; createPaymentBody.customer_id = globalState.get("customerId"); + createPaymentBody.profile_id = globalState.get("profileId"); globalState.set("paymentAmount", createPaymentBody.amount); cy.request({ method: "POST", @@ -827,6 +914,8 @@ Cypress.Commands.add( `Expected ${res_data.body[key]} but got ${response.body[key]}` ); } + expect(response.body.payment_id, "payment_id").to.not.be.null; + expect(response.body.merchant_id, "merchant_id").to.not.be.null; expect(createPaymentBody.amount, "amount").to.equal( response.body.amount ); @@ -916,23 +1005,39 @@ Cypress.Commands.add( "createPaymentMethodTest", (globalState, req_data, res_data) => { req_data.customer_id = globalState.get("customerId"); + const merchant_id = globalState.get("merchantId"); cy.request({ method: "POST", url: `${globalState.get("baseUrl")}/payment_methods`, - body: req_data, headers: { "Content-Type": "application/json", Accept: "application/json", "api-key": globalState.get("apiKey"), }, + body: req_data, + failOnStatusCode: false, }).then((response) => { logRequestId(response.headers["x-request-id"]); expect(response.headers["content-type"]).to.include("application/json"); if (response.status === 200) { - expect(response.body).to.have.property("payment_method_id"); - expect(response.body).to.have.property("client_secret"); + expect(response.body.client_secret, "client_secret").to.include( + "_secret_" + ).and.to.not.be.null; + expect(response.body.payment_method_id, "payment_method_id").to.not.be + .null; + expect(response.body.merchant_id, "merchant_id").to.equal(merchant_id); + expect(req_data.payment_method_type, "payment_method_type").to.equal( + response.body.payment_method_type + ); + expect(req_data.payment_method, "payment_method").to.equal( + response.body.payment_method + ); + expect(response.body.last_used_at, "last_used_at").to.not.be.null; + expect(req_data.customer_id, "customer_id").to.equal( + response.body.customer_id + ); globalState.set("paymentMethodId", response.body.payment_method_id); } else { defaultErrorHandler(response, res_data); @@ -941,6 +1046,54 @@ Cypress.Commands.add( } ); +Cypress.Commands.add("deletePaymentMethodTest", (globalState, res_data) => { + const payment_method_id = globalState.get("paymentMethodId"); + cy.request({ + method: "DELETE", + url: `${globalState.get("baseUrl")}/payment_methods/${payment_method_id}`, + headers: { + Accept: "application/json", + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(response.headers["content-type"]).to.include("application/json"); + + if (response.status === 200) { + expect(response.body.payment_method_id).to.equal(payment_method_id); + expect(response.body.deleted).to.be.true; + } else { + defaultErrorHandler(response, res_data); + } + }); +}); + +Cypress.Commands.add("setDefaultPaymentMethodTest", (globalState) => { + const payment_method_id = globalState.get("paymentMethodId"); + const customer_id = globalState.get("customerId"); + cy.request({ + method: "POST", + url: `${globalState.get("baseUrl")}/customers/${customer_id}/payment_methods/${payment_method_id}/default`, + headers: { + "api-key": globalState.get("apiKey"), + }, + failOnStatusCode: false, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(response.headers["content-type"]).to.include("application/json"); + if (response.status === 200) { + expect(response.body).to.have.property( + "default_payment_method_id", + payment_method_id + ); + expect(response.body).to.have.property("customer_id", customer_id); + } else { + defaultErrorHandler(response); + } + }); +}); + Cypress.Commands.add( "confirmCallTest", (confirmBody, req_data, res_data, confirm, globalState) => { @@ -968,21 +1121,18 @@ Cypress.Commands.add( expect(response.body.connector, "connector").to.equal( globalState.get("connectorId") ); - expect(response.body.payment_id, "payment_id").to.equal( - paymentIntentID + expect(paymentIntentID, "payment_id").to.equal( + response.body.payment_id ); expect(response.body.payment_method_data, "payment_method_data").to.not .be.empty; - expect(response.body.merchant_connector_id, "connector_id").to.equal( - globalState.get("merchantConnectorId") + expect(globalState.get("merchantConnectorId"), "connector_id").to.equal( + response.body.merchant_connector_id ); expect(response.body.customer, "customer").to.not.be.empty; expect(response.body.billing, "billing_address").to.not.be.empty; expect(response.body.profile_id, "profile_id").to.not.be.null; - expect( - response.body.connector_transaction_id, - "connector_transaction_id" - ).to.not.be.null; + if (response.body.capture_method === "automatic") { if (response.body.authentication_type === "three_ds") { expect(response.body) @@ -1279,6 +1429,7 @@ Cypress.Commands.add( createConfirmPaymentBody.authentication_type = authentication_type; createConfirmPaymentBody.capture_method = capture_method; createConfirmPaymentBody.customer_id = globalState.get("customerId"); + createConfirmPaymentBody.profile_id = globalState.get("profileId"); for (const key in req_data) { createConfirmPaymentBody[key] = req_data[key]; } @@ -1293,6 +1444,7 @@ Cypress.Commands.add( body: createConfirmPaymentBody, }).then((response) => { logRequestId(response.headers["x-request-id"]); + globalState.set("clientSecret", response.body.client_secret); expect(response.headers["content-type"]).to.include("application/json"); if (response.status === 200) { globalState.set("paymentAmount", createConfirmPaymentBody.amount); @@ -1311,10 +1463,6 @@ Cypress.Commands.add( expect(response.body.customer, "customer").to.not.be.empty; expect(response.body.billing, "billing_address").to.not.be.empty; expect(response.body.profile_id, "profile_id").to.not.be.null; - expect( - response.body.connector_transaction_id, - "connector_transaction_id" - ).to.not.be.null; expect(response.body).to.have.property("status"); if (response.body.capture_method === "automatic") { if (response.body.authentication_type === "three_ds") { @@ -1384,6 +1532,9 @@ Cypress.Commands.add( } saveCardConfirmBody.payment_token = globalState.get("paymentToken"); saveCardConfirmBody.client_secret = globalState.get("clientSecret"); + for (const key in req_data) { + saveCardConfirmBody[key] = req_data[key]; + } cy.request({ method: "POST", url: `${globalState.get("baseUrl")}/payments/${paymentIntentID}/confirm`, @@ -1399,6 +1550,27 @@ Cypress.Commands.add( expect(response.headers["content-type"]).to.include("application/json"); if (response.status === 200) { globalState.set("paymentID", paymentIntentID); + + globalState.set("paymentID", paymentIntentID); + globalState.set("connectorId", response.body.connector); + expect(response.body.connector, "connector").to.equal( + globalState.get("connectorId") + ); + expect(paymentIntentID, "payment_id").to.equal( + response.body.payment_id + ); + expect(response.body.payment_method_data, "payment_method_data").to.not + .be.empty; + expect(globalState.get("merchantConnectorId"), "connector_id").to.equal( + response.body.merchant_connector_id + ); + expect(response.body.customer, "customer").to.not.be.empty; + if (req_data.billing !== null) { + expect(response.body.billing, "billing_address").to.not.be.empty; + } + expect(response.body.profile_id, "profile_id").to.not.be.null; + expect(response.body.payment_token, "payment_token").to.not.be.null; + if (response.body.capture_method === "automatic") { if (response.body.authentication_type === "three_ds") { expect(response.body) @@ -1543,10 +1715,6 @@ Cypress.Commands.add( expect(response.body.merchant_connector_id, "connector_id").to.equal( globalState.get("merchantConnectorId") ); - expect( - response.body.connector_transaction_id, - "connector_transaction_id" - ).to.not.be.null; } if (autoretries) { @@ -1671,6 +1839,19 @@ Cypress.Commands.add( if (response.status === 200) { globalState.set("paymentID", response.body.payment_id); + expect(response.body.payment_method_data, "payment_method_data").to.not + .be.empty; + expect(response.body.connector, "connector").to.equal( + globalState.get("connectorId") + ); + expect(globalState.get("merchantConnectorId"), "connector_id").to.equal( + response.body.merchant_connector_id + ); + expect(response.body.customer, "customer").to.not.be.empty; + expect(response.body.profile_id, "profile_id").to.not.be.null; + expect(response.body.payment_method_id, "payment_method_id").to.not.be + .null; + if (requestBody.mandate_data === null) { expect(response.body).to.have.property("payment_method_id"); globalState.set("paymentMethodId", response.body.payment_method_id); @@ -1761,6 +1942,18 @@ Cypress.Commands.add( expect(response.headers["content-type"]).to.include("application/json"); if (response.status === 200) { globalState.set("paymentID", response.body.payment_id); + expect(response.body.payment_method_data, "payment_method_data").to.not + .be.empty; + expect(response.body.connector, "connector").to.equal( + globalState.get("connectorId") + ); + expect(globalState.get("merchantConnectorId"), "connector_id").to.equal( + response.body.merchant_connector_id + ); + expect(response.body.customer, "customer").to.not.be.empty; + expect(response.body.profile_id, "profile_id").to.not.be.null; + expect(response.body.payment_method_id, "payment_method_id").to.not.be + .null; if (response.body.capture_method === "automatic") { if (response.body.authentication_type === "three_ds") { expect(response.body) @@ -2022,7 +2215,61 @@ Cypress.Commands.add("listCustomerPMCallTest", (globalState) => { if (response.body.customer_payment_methods[0]?.payment_token) { const paymentToken = response.body.customer_payment_methods[0].payment_token; + const paymentMethodId = + response.body.customer_payment_methods[0].payment_method_id; globalState.set("paymentToken", paymentToken); // Set paymentToken in globalState + globalState.set("paymentMethodId", paymentMethodId); // Set paymentMethodId in globalState + } else { + // We only get an empty array if something's wrong. One exception is a 4xx when no customer exist but it is handled in the test + expect(response.body) + .to.have.property("customer_payment_methods") + .to.be.an("array").and.empty; + } + expect(globalState.get("customerId"), "customer_id").to.equal( + response.body.customer_payment_methods[0].customer_id + ); + expect( + response.body.customer_payment_methods[0].payment_token, + "payment_token" + ).to.not.be.null; + expect( + response.body.customer_payment_methods[0].payment_method_id, + "payment_method_id" + ).to.not.be.null; + expect( + response.body.customer_payment_methods[0].payment_method, + "payment_method" + ).to.not.be.null; + expect( + response.body.customer_payment_methods[0].payment_method_type, + "payment_method_type" + ).to.not.be.null; + }); +}); + +Cypress.Commands.add("listCustomerPMByClientSecret", (globalState) => { + const clientSecret = globalState.get("clientSecret"); + cy.request({ + method: "GET", + url: `${globalState.get("baseUrl")}/customers/payment_methods?client_secret=${clientSecret}`, + headers: { + "Content-Type": "application/json", + "api-key": globalState.get("publishableKey"), + }, + }).then((response) => { + logRequestId(response.headers["x-request-id"]); + expect(response.headers["content-type"]).to.include("application/json"); + if (response.body.customer_payment_methods[0]?.payment_token) { + const paymentToken = + response.body.customer_payment_methods[0].payment_token; + const paymentMethodId = + response.body.customer_payment_methods[0].payment_method_id; + globalState.set("paymentToken", paymentToken); + globalState.set("paymentMethodId", paymentMethodId); + expect( + response.body.customer_payment_methods[0].payment_method_id, + "payment_method_id" + ).to.not.be.null; } else { // We only get an empty array if something's wrong. One exception is a 4xx when no customer exist but it is handled in the test expect(response.body)
ci
Enhance Cybersource Testcases (#6285)
9a59d0a5ff682cd7a983a63e90113afc846aeac6
2024-12-02 20:00:44
Sanchith Hegde
chore: address Rust 1.83.0 clippy lints and enable more clippy lints (#6705)
false
diff --git a/.clippy.toml b/.clippy.toml new file mode 100644 index 00000000000..4296655a040 --- /dev/null +++ b/.clippy.toml @@ -0,0 +1 @@ +allow-dbg-in-tests = true diff --git a/Cargo.toml b/Cargo.toml index 90eb996b82b..38d895d767a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,12 +18,16 @@ unused_qualifications = "warn" [workspace.lints.clippy] as_conversions = "warn" +cloned_instead_of_copied = "warn" +dbg_macro = "warn" expect_used = "warn" +fn_params_excessive_bools = "warn" index_refutable_slice = "warn" indexing_slicing = "warn" large_futures = "warn" match_on_vec_items = "warn" missing_panics_doc = "warn" +mod_module_files = "warn" out_of_bounds_indexing = "warn" panic = "warn" panic_in_result_fn = "warn" @@ -32,10 +36,12 @@ print_stderr = "warn" print_stdout = "warn" todo = "warn" unimplemented = "warn" +unnecessary_self_imports = "warn" unreachable = "warn" unwrap_in_result = "warn" unwrap_used = "warn" use_self = "warn" +wildcard_dependencies = "warn" # Lints to allow option_map_unit_fn = "allow" diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index e3f54813a43..d8ab5a7a20d 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -4176,7 +4176,7 @@ }, "bank_account_bic": { "type": "string", - "description": "Bank account details for Giropay\nBank account bic code", + "description": "Bank account bic code", "nullable": true }, "bank_account_iban": { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 25ed2648cd4..f903879c483 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -867,7 +867,6 @@ "Payments" ], "summary": "Payments - Complete Authorize", - "description": "\n", "operationId": "Complete Authorize a Payment", "parameters": [ { @@ -918,7 +917,6 @@ "Payments" ], "summary": "Payments - Post Session Tokens", - "description": "\n", "operationId": "Create Post Session Tokens for a Payment", "requestBody": { "content": { @@ -6757,7 +6755,7 @@ }, "bank_account_bic": { "type": "string", - "description": "Bank account details for Giropay\nBank account bic code", + "description": "Bank account bic code", "nullable": true }, "bank_account_iban": { diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/disputes/metrics/sessionized_metrics.rs diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/payment_intents/metrics/sessionized_metrics.rs diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payments/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/payments/metrics/sessionized_metrics.rs diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/refunds/metrics/sessionized_metrics.rs diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 7e1465c9d92..f0a8c999438 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1531,7 +1531,6 @@ pub struct MerchantConnectorUpdate { #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] - pub struct ConnectorWalletDetails { /// This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index d25f35589b6..b6d4044c5f3 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -277,7 +277,6 @@ pub struct PaymentIntentFilterValue { #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] - pub struct GetRefundFilterRequest { pub time_range: TimeRange, #[serde(default)] @@ -292,7 +291,6 @@ pub struct RefundFiltersResponse { #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] - pub struct RefundFilterValue { pub dimension: RefundDimensions, pub values: Vec<String>, @@ -435,7 +433,6 @@ pub struct DisputeFiltersResponse { #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] - pub struct DisputeFilterValue { pub dimension: DisputeDimensions, pub values: Vec<String>, diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs index d25cd989b0f..3c4d566f235 100644 --- a/crates/api_models/src/api_keys.rs +++ b/crates/api_models/src/api_keys.rs @@ -212,7 +212,7 @@ mod never { { struct NeverVisitor; - impl<'de> serde::de::Visitor<'de> for NeverVisitor { + impl serde::de::Visitor<'_> for NeverVisitor { type Value = (); fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { diff --git a/crates/api_models/src/conditional_configs.rs b/crates/api_models/src/conditional_configs.rs index 555e7bd955f..3aed34e47a7 100644 --- a/crates/api_models/src/conditional_configs.rs +++ b/crates/api_models/src/conditional_configs.rs @@ -92,7 +92,6 @@ pub struct ConditionalConfigReq { pub algorithm: Option<Program<ConditionalConfigs>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] - pub struct DecisionManagerRequest { pub name: Option<String>, pub program: Option<Program<ConditionalConfigs>>, diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 646ad122d7c..c00afac6462 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -141,7 +141,6 @@ pub enum FrmConnectors { )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] - pub enum TaxConnectors { Taxjar, } diff --git a/crates/api_models/src/errors/mod.rs b/crates/api_models/src/errors.rs similarity index 100% rename from crates/api_models/src/errors/mod.rs rename to crates/api_models/src/errors.rs diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index fb60937e9b1..f46fd450bd4 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2457,7 +2457,6 @@ pub enum AdditionalPaymentData { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] - pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } @@ -2504,7 +2503,6 @@ pub enum BankRedirectData { Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, - /// Bank account details for Giropay #[schema(value_type = Option<String>)] /// Bank account bic code @@ -3682,7 +3680,6 @@ pub enum WalletResponseData { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] - pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } @@ -4196,7 +4193,6 @@ pub struct ReceiverDetails { #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] - pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. @@ -6355,7 +6351,7 @@ mod payment_id_type { struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; - impl<'de> Visitor<'de> for PaymentIdVisitor { + impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -6433,7 +6429,7 @@ mod payment_id_type { struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; - impl<'de> Visitor<'de> for PaymentIdVisitor { + impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -6507,7 +6503,7 @@ pub mod amount { // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally - impl<'de> de::Visitor<'de> for AmountVisitor { + impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -6707,7 +6703,6 @@ pub struct PaymentLinkStatusDetails { #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] - pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs index 8ed52907da8..e97efcf92d3 100644 --- a/crates/api_models/src/pm_auth.rs +++ b/crates/api_models/src/pm_auth.rs @@ -22,7 +22,6 @@ pub struct LinkTokenCreateResponse { #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] - pub struct ExchangeTokenCreateRequest { pub public_token: String, pub client_secret: Option<String>, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 389af3dab7b..dbfa770cbf1 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -473,7 +473,6 @@ impl RoutingAlgorithmRef { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] - pub struct RoutingDictionaryRecord { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, diff --git a/crates/api_models/src/user/sample_data.rs b/crates/api_models/src/user/sample_data.rs index dc95de913fa..bfcbcb046c5 100644 --- a/crates/api_models/src/user/sample_data.rs +++ b/crates/api_models/src/user/sample_data.rs @@ -1,5 +1,4 @@ use common_enums::{AuthenticationType, CountryAlpha2}; -use common_utils::{self}; use time::PrimitiveDateTime; use crate::enums::Connector; diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index d3515ef02f0..d3a27da4823 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -10,14 +10,10 @@ use router_env::{logger, which as router_env_which, Env}; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; -/// /// Minimum limit of a card number will not be less than 8 by ISO standards -/// pub const MIN_CARD_NUMBER_LENGTH: usize = 8; -/// /// Maximum limit of a card number will not exceed 19 by ISO standards -/// pub const MAX_CARD_NUMBER_LENGTH: usize = 19; #[derive(Debug, Deserialize, Serialize, Error)] @@ -138,11 +134,9 @@ pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidat Ok(is_card_number_valid) } -/// /// # Panics /// /// Never, as a single character will never be greater than 10, or `u8` -/// pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> { let data = number.chars().try_fold( Vec::with_capacity(MAX_CARD_NUMBER_LENGTH), diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index f5f7ba3decd..ddf55d29371 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1914,7 +1914,7 @@ mod custom_serde { struct FieldVisitor; - impl<'de> Visitor<'de> for FieldVisitor { + impl Visitor<'_> for FieldVisitor { type Value = CountryAlpha2; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { @@ -1946,7 +1946,7 @@ mod custom_serde { struct FieldVisitor; - impl<'de> Visitor<'de> for FieldVisitor { + impl Visitor<'_> for FieldVisitor { type Value = CountryAlpha3; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { @@ -1978,7 +1978,7 @@ mod custom_serde { struct FieldVisitor; - impl<'de> Visitor<'de> for FieldVisitor { + impl Visitor<'_> for FieldVisitor { type Value = u32; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs index c7f1c286c59..e8c2b2d5a0b 100644 --- a/crates/common_utils/src/crypto.rs +++ b/crates/common_utils/src/crypto.rs @@ -238,7 +238,6 @@ impl VerifySignature for HmacSha512 { } } -/// /// Blake3 #[derive(Debug)] pub struct Blake3(String); @@ -437,9 +436,7 @@ pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; bytes } -/// /// A wrapper type to store the encrypted data for sensitive pii domain data types -/// #[derive(Debug, Clone)] pub struct Encryptable<T: Clone> { inner: T, @@ -447,9 +444,7 @@ pub struct Encryptable<T: Clone> { } impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> { - /// /// constructor function to be used by the encryptor and decryptor to generate the data type - /// pub fn new( masked_data: Secret<T, S>, encrypted_data: Secret<Vec<u8>, EncryptionStrategy>, @@ -462,33 +457,25 @@ impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> { } impl<T: Clone> Encryptable<T> { - /// /// Get the inner data while consuming self - /// #[inline] pub fn into_inner(self) -> T { self.inner } - /// /// Get the reference to inner value - /// #[inline] pub fn get_inner(&self) -> &T { &self.inner } - /// /// Get the inner encrypted data while consuming self - /// #[inline] pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.encrypted } - /// /// Deserialize inner value and return new Encryptable object - /// pub fn deserialize_inner_value<U, F>( self, f: F, diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs index 79e0c5b85e7..63ef30011f7 100644 --- a/crates/common_utils/src/custom_serde.rs +++ b/crates/common_utils/src/custom_serde.rs @@ -202,7 +202,6 @@ pub mod timestamp { } /// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860> - pub mod json_string { use serde::de::{self, Deserialize, DeserializeOwned, Deserializer}; use serde_json; diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index 38b89cbfaf7..e62606b4585 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -7,7 +7,6 @@ use crate::types::MinorUnit; /// error_stack::Report<E> specific extendability /// /// Effectively, equivalent to `Result<T, error_stack::Report<E>>` -/// pub type CustomResult<T, E> = error_stack::Result<T, E>; /// Parsing Errors diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 5ad53ec8533..945056aafef 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -1,7 +1,5 @@ -//! //! This module holds traits for extending functionalities for existing datatypes //! & inbuilt datatypes. -//! use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, Strategy}; @@ -14,10 +12,8 @@ use crate::{ fp_utils::when, }; -/// /// Encode interface /// An interface for performing type conversions and serialization -/// pub trait Encode<'e> where Self: 'e + std::fmt::Debug, @@ -27,62 +23,49 @@ where /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically to convert into json, by using `serde_json` - /// fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; - /// /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` - /// fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; - /// /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` - /// fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into JSON `String`. - /// fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. - /// fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` - /// fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize` - /// fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize; @@ -165,13 +148,9 @@ where } } -/// /// Extending functionalities of `bytes::Bytes` -/// pub trait BytesExt { - /// /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` - /// fn parse_struct<'de, T>( &'de self, type_name: &'static str, @@ -199,13 +178,9 @@ impl BytesExt for bytes::Bytes { } } -/// /// Extending functionalities of `[u8]` for performing parsing -/// pub trait ByteSliceExt { - /// /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` - /// fn parse_struct<'de, T>( &'de self, type_name: &'static str, @@ -229,13 +204,9 @@ impl ByteSliceExt for [u8] { } } -/// /// Extending functionalities of `serde_json::Value` for performing parsing -/// pub trait ValueExt { - /// /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` - /// fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned; @@ -277,22 +248,16 @@ impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> { } } -/// /// Extending functionalities of `String` for performing parsing -/// pub trait StringExt<T> { - /// /// Convert `String` into type `<T>` (which being an `enum`) - /// fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; - /// /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` - /// fn parse_struct<'de>( &'de self, type_name: &'static str, @@ -327,25 +292,20 @@ impl<T> StringExt<T> for String { } } -/// /// Extending functionalities of Wrapper types for idiomatic -/// #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] pub trait AsyncExt<A, B> { /// Output type of the map function type WrappedSelf<T>; - /// + /// Extending map by allowing functions which are async - /// async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send; - /// /// Extending the `and_then` by allowing functions which are async - /// async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, @@ -469,9 +429,7 @@ where /// Extension trait for deserializing XML strings using `quick-xml` crate pub trait XmlExt { - /// /// Deserialize an XML string into the specified type `<T>`. - /// fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned; diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index 9d4b96200ba..5fd0e8078a2 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -348,7 +348,6 @@ where } /// Strategy for masking UPI VPA's - #[derive(Debug)] pub enum UpiVpaMaskingStrategy {} diff --git a/crates/common_utils/src/signals.rs b/crates/common_utils/src/signals.rs index 5bde366bf3c..d008aef290e 100644 --- a/crates/common_utils/src/signals.rs +++ b/crates/common_utils/src/signals.rs @@ -6,10 +6,8 @@ use futures::StreamExt; use router_env::logger; use tokio::sync::mpsc; -/// /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received -/// #[cfg(not(target_os = "windows"))] pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) { if let Some(signal) = sig.next().await { @@ -34,47 +32,35 @@ pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::S } } -/// /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received -/// #[cfg(target_os = "windows")] pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {} -/// /// This function is used to generate a list of signals that the signal_handler should listen for -/// #[cfg(not(target_os = "windows"))] pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> { signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT]) } -/// /// This function is used to generate a list of signals that the signal_handler should listen for -/// #[cfg(target_os = "windows")] pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> { Ok(DummySignal) } -/// /// Dummy Signal Handler for windows -/// #[cfg(target_os = "windows")] #[derive(Debug, Clone)] pub struct DummySignal; #[cfg(target_os = "windows")] impl DummySignal { - /// /// Dummy handler for signals in windows (empty) - /// pub fn handle(&self) -> Self { self.clone() } - /// /// Hollow implementation, for windows compatibility - /// pub fn close(self) {} } diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 2a271acb62b..1e547a49713 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -334,7 +334,6 @@ impl AmountConvertor for FloatMajorUnitForConnector { } /// Connector required amount type - #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct MinorUnitForConnector; @@ -503,7 +502,6 @@ impl Sum for MinorUnit { } /// Connector specific types to send - #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq)] pub struct StringMinorUnit(String); @@ -749,7 +747,7 @@ mod client_secret_type { { struct ClientSecretVisitor; - impl<'de> Visitor<'de> for ClientSecretVisitor { + impl Visitor<'_> for ClientSecretVisitor { type Value = ClientSecret; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs index 078f1f3fcd8..09d26bd91ef 100644 --- a/crates/common_utils/src/types/keymanager.rs +++ b/crates/common_utils/src/types/keymanager.rs @@ -393,7 +393,7 @@ impl<'de> Deserialize<'de> for DecryptedData { { struct DecryptedDataVisitor; - impl<'de> Visitor<'de> for DecryptedDataVisitor { + impl Visitor<'_> for DecryptedDataVisitor { type Value = DecryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -449,7 +449,7 @@ impl<'de> Deserialize<'de> for EncryptedData { { struct EncryptedDataVisitor; - impl<'de> Visitor<'de> for EncryptedDataVisitor { + impl Visitor<'_> for EncryptedDataVisitor { type Value = EncryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index 26c9d33f405..8f6e03fb398 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -106,7 +106,6 @@ pub struct ApiModelMetaData { #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] - pub enum KlarnaEndpoint { Europe, NorthAmerica, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 0e68b04d27b..524bfa71709 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -73,7 +73,6 @@ pub enum ApplePayTomlConfig { #[serde_with::skip_serializing_none] #[derive(Debug, Clone, serde::Serialize, Deserialize)] - pub enum KlarnaEndpoint { Europe, NorthAmerica, diff --git a/crates/diesel_models/src/configs.rs b/crates/diesel_models/src/configs.rs index 2b30aa6a972..37381961d96 100644 --- a/crates/diesel_models/src/configs.rs +++ b/crates/diesel_models/src/configs.rs @@ -7,7 +7,6 @@ use crate::schema::configs; #[derive(Default, Clone, Debug, Insertable, Serialize, Deserialize)] #[diesel(table_name = configs)] - pub struct ConfigNew { pub key: String, pub config: String, diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index c7a3818d5fe..7e476662ea7 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -75,7 +75,6 @@ pub use self::{ /// `Option<T>` values. /// /// [diesel-2.0-array-nullability]: https://diesel.rs/guides/migration_guide.html#2-0-0-nullability-of-array-elements - #[doc(hidden)] pub(crate) mod diesel_impl { use diesel::{ diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs index bd4fd119201..6a3cad24e1c 100644 --- a/crates/diesel_models/src/organization.rs +++ b/crates/diesel_models/src/organization.rs @@ -197,8 +197,8 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal { } } } -#[cfg(feature = "v2")] +#[cfg(feature = "v2")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 7760ea76c50..6ddc26d49bd 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -6,7 +6,7 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::enums::{self as storage_enums}; +use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::payment_attempt; #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/reverse_lookup.rs b/crates/diesel_models/src/reverse_lookup.rs index 87fca344078..974851f966a 100644 --- a/crates/diesel_models/src/reverse_lookup.rs +++ b/crates/diesel_models/src/reverse_lookup.rs @@ -2,7 +2,6 @@ use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::reverse_lookup; -/// /// This reverse lookup table basically looks up id's and get result_id that you want. This is /// useful for KV where you can't lookup without key #[derive( diff --git a/crates/diesel_models/src/services/logger.rs b/crates/diesel_models/src/services/logger.rs deleted file mode 100644 index 9c1b20c9d28..00000000000 --- a/crates/diesel_models/src/services/logger.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! -//! Logger of the system. -//! - -pub use crate::env::logger::*; diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 55ffe0c4e7f..87057ebeff2 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -29,7 +29,6 @@ impl Store { /// /// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration. /// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client. - /// pub async fn new(config: &crate::Settings, test_transaction: bool, tenant: &Tenant) -> Self { let redis_conn = crate::connection::redis_connection(config).await; Self { diff --git a/crates/euclid/src/dssa/analyzer.rs b/crates/euclid/src/dssa/analyzer.rs index a81e7be351f..7aeb850e1bb 100644 --- a/crates/euclid/src/dssa/analyzer.rs +++ b/crates/euclid/src/dssa/analyzer.rs @@ -87,7 +87,7 @@ pub fn analyze_exhaustive_negations( .cloned() .unwrap_or_default() .iter() - .cloned() + .copied() .cloned() .collect(), }; @@ -121,12 +121,12 @@ fn analyze_negated_assertions( value: (*val).clone(), assertion_metadata: assertion_metadata .get(*val) - .cloned() + .copied() .cloned() .unwrap_or_default(), negation_metadata: negation_metadata .get(*val) - .cloned() + .copied() .cloned() .unwrap_or_default(), }; diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 30d71090f36..7ef9bb244d9 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -421,7 +421,7 @@ impl CgraphExt for cgraph::ConstraintGraph<dir::DirValue> { for (key, negation_set) in keywise_negation { let all_metadata = keywise_metadata.remove(&key).unwrap_or_default(); - let first_metadata = all_metadata.first().cloned().cloned().unwrap_or_default(); + let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default(); self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?; diff --git a/crates/euclid/src/dssa/types.rs b/crates/euclid/src/dssa/types.rs index df54de2dd99..f8340c31509 100644 --- a/crates/euclid/src/dssa/types.rs +++ b/crates/euclid/src/dssa/types.rs @@ -18,7 +18,7 @@ pub enum CtxValueKind<'a> { Negation(&'a [dir::DirValue]), } -impl<'a> CtxValueKind<'a> { +impl CtxValueKind<'_> { pub fn get_assertion(&self) -> Option<&dir::DirValue> { if let Self::Assertion(val) = self { Some(val) diff --git a/crates/euclid/src/frontend/ast.rs b/crates/euclid/src/frontend/ast.rs index 5a7b88acfbc..7c75ad000bf 100644 --- a/crates/euclid/src/frontend/ast.rs +++ b/crates/euclid/src/frontend/ast.rs @@ -135,7 +135,6 @@ pub struct IfStatement { /// } /// } /// ``` - #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)] diff --git a/crates/euclid/src/frontend/ast/lowering.rs b/crates/euclid/src/frontend/ast/lowering.rs index 24fc1e80428..ec629358d5f 100644 --- a/crates/euclid/src/frontend/ast/lowering.rs +++ b/crates/euclid/src/frontend/ast/lowering.rs @@ -25,7 +25,6 @@ use crate::{ /// This serves for the purpose were we have the DirKey as an explicit Enum type and value as one /// of the member of the same Enum. /// So particularly it lowers a predefined Enum from DirKey to an Enum of DirValue. - macro_rules! lower_enum { ($key:ident, $value:ident) => { match $value { @@ -70,7 +69,6 @@ macro_rules! lower_enum { /// This is for the cases in which there are numerical values involved and they are lowered /// accordingly on basis of the supplied key, currently payment_amount is the only key having this /// use case - macro_rules! lower_number { ($key:ident, $value:ident, $comp:ident) => { match $value { @@ -117,7 +115,6 @@ macro_rules! lower_number { /// /// This serves for the purpose were we have the DirKey as Card_bin and value as an arbitrary string /// So particularly it lowers an arbitrary value to a predefined key. - macro_rules! lower_str { ($key:ident, $value:ident $(, $validation_closure:expr)?) => { match $value { @@ -155,7 +152,6 @@ macro_rules! lower_metadata { /// by throwing required errors for comparisons that can't be performed for a certain value type /// for example /// can't have greater/less than operations on enum types - fn lower_comparison_inner<O: EuclidDirFilter>( comp: ast::Comparison, ) -> Result<Vec<dir::DirValue>, AnalysisErrorType> { diff --git a/crates/euclid/src/frontend/ast/parser.rs b/crates/euclid/src/frontend/ast/parser.rs index 0c586e178e6..63a0ea08b8b 100644 --- a/crates/euclid/src/frontend/ast/parser.rs +++ b/crates/euclid/src/frontend/ast/parser.rs @@ -51,9 +51,9 @@ impl EuclidParsable for DummyOutput { )(input) } } -pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&str, O> +pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&'a str, O> where - F: FnMut(&'a str) -> ParseResult<&str, O> + 'a, + F: FnMut(&'a str) -> ParseResult<&'a str, O> + 'a, { sequence::preceded(pchar::multispace0, inner) } diff --git a/crates/events/src/lib.rs b/crates/events/src/lib.rs index 3d333ec54b9..38a597e030b 100644 --- a/crates/events/src/lib.rs +++ b/crates/events/src/lib.rs @@ -2,14 +2,12 @@ #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![warn(missing_docs)] -//! //! A generic event handler system. //! This library consists of 4 parts: //! Event Sink: A trait that defines how events are published. This could be a simple logger, a message queue, or a database. //! EventContext: A struct that holds the event sink and metadata about the event. This is used to create events. This can be used to add metadata to all events, such as the user who triggered the event. //! EventInfo: A trait that defines the metadata that is sent with the event. It works with the EventContext to add metadata to all events. //! Event: A trait that defines the event itself. This trait is used to define the data that is sent with the event and defines the event's type & identifier. -//! mod actix; diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs index e551cfee2af..479b7c5f386 100644 --- a/crates/external_services/src/file_storage.rs +++ b/crates/external_services/src/file_storage.rs @@ -1,6 +1,4 @@ -//! //! Module for managing file storage operations with support for multiple storage schemes. -//! use std::{ fmt::{Display, Formatter}, diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs index e3986abf0f8..19b3185e81b 100644 --- a/crates/external_services/src/file_storage/file_system.rs +++ b/crates/external_services/src/file_storage/file_system.rs @@ -1,6 +1,4 @@ -//! //! Module for local file system storage operations -//! use std::{ fs::{remove_file, File}, diff --git a/crates/external_services/src/hashicorp_vault/core.rs b/crates/external_services/src/hashicorp_vault/core.rs index 15edcb6418c..3cc03b4330b 100644 --- a/crates/external_services/src/hashicorp_vault/core.rs +++ b/crates/external_services/src/hashicorp_vault/core.rs @@ -103,7 +103,6 @@ impl HashiCorpVault { /// # Parameters /// /// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details. - /// pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> { VaultClient::new( VaultClientSettingsBuilder::default() @@ -129,7 +128,6 @@ impl HashiCorpVault { /// /// - `En`: The engine type that implements the `Engine` trait. /// - `I`: The type that can be constructed from the retrieved encoded data. - /// pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError> where for<'a> En: Engine< diff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rs index 678239c60b1..a0add638235 100644 --- a/crates/external_services/src/managers/encryption_management.rs +++ b/crates/external_services/src/managers/encryption_management.rs @@ -1,6 +1,4 @@ -//! //! Encryption management util module -//! use std::sync::Arc; diff --git a/crates/external_services/src/managers/secrets_management.rs b/crates/external_services/src/managers/secrets_management.rs index b79046b4c75..7b27e74bf34 100644 --- a/crates/external_services/src/managers/secrets_management.rs +++ b/crates/external_services/src/managers/secrets_management.rs @@ -1,6 +1,4 @@ -//! //! Secrets management util module -//! use common_utils::errors::CustomResult; #[cfg(feature = "hashicorp-vault")] diff --git a/crates/external_services/src/no_encryption.rs b/crates/external_services/src/no_encryption.rs index 17c29618f89..6f805fc7a10 100644 --- a/crates/external_services/src/no_encryption.rs +++ b/crates/external_services/src/no_encryption.rs @@ -1,6 +1,4 @@ -//! //! No encryption functionalities -//! pub mod core; diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 180db626864..479abf13b13 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -916,7 +916,6 @@ pub struct Data { } #[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] - pub struct MultisafepayPaymentDetails { pub account_holder_name: Option<Secret<String>>, pub account_id: Option<Secret<String>>, diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs index 6297b97ee98..8d6dc42926b 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs @@ -122,7 +122,6 @@ pub struct NexinetsBankRedirects { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] - pub struct NexinetsAsyncDetails { pub success_url: Option<String>, pub cancel_url: Option<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index b2bf76944c0..18783c64a01 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -80,7 +80,6 @@ pub struct NovalnetPaymentsRequestCustomer { no_nc: i64, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] - pub struct NovalnetCard { card_number: CardNumber, card_expiry_month: Secret<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs index 3b2164dfc97..c799cf2594e 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs @@ -58,7 +58,6 @@ pub struct RazorpayPaymentsRequest { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] - pub struct SecondFactor { txn_id: String, id: String, @@ -981,7 +980,6 @@ pub struct RazorpaySyncResponse { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] - pub enum PsyncStatus { Charged, Pending, @@ -1054,7 +1052,6 @@ pub struct Refund { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] - pub enum RefundStatus { Success, Failure, @@ -1221,7 +1218,6 @@ impl From<RefundStatus> for enums::RefundStatus { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] - pub struct RefundResponse { txn_id: Option<String>, refund: RefundRes, diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index cd9fe63e4a7..27b9daaa579 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -457,7 +457,6 @@ pub struct TsysCaptureRequest { #[derive(Debug, Serialize)] #[serde(rename_all = "PascalCase")] - pub struct TsysPaymentsCaptureRequest { capture: TsysCaptureRequest, } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index be8f9bca352..266fcc7d659 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -54,8 +54,8 @@ use response::{ WP_CORRELATION_ID, }; use ring::hmac; -use transformers::{self as worldpay}; +use self::transformers as worldpay; use crate::{ constants::headers, types::ResponseRouterData, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index a7fe1cc4cd9..181f46a2052 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -119,7 +119,7 @@ where pub(crate) fn missing_field_err( message: &'static str, -) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + '_> { +) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs index 7c435fee290..8d56406d2a3 100644 --- a/crates/hyperswitch_constraint_graph/src/graph.rs +++ b/crates/hyperswitch_constraint_graph/src/graph.rs @@ -120,7 +120,7 @@ where already_memo .clone() .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) - } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).cloned() + } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).copied() { let strength_relation = Strength::get_resolved_strength(initial_strength, strength); let relation_resolve = @@ -197,7 +197,7 @@ where if !unsatisfied.is_empty() { let err = Arc::new(AnalysisTrace::AllAggregation { unsatisfied, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -264,7 +264,7 @@ where } else { let err = Arc::new(AnalysisTrace::AnyAggregation { unsatisfied: unsatisfied.clone(), - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -305,7 +305,7 @@ where expected: expected.iter().cloned().collect(), found: None, relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -324,7 +324,7 @@ where expected: expected.iter().cloned().collect(), found: Some(ctx_value.clone()), relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -402,7 +402,7 @@ where let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new( trace.get_analysis_trace()?, @@ -437,7 +437,7 @@ where let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())), }); @@ -469,7 +469,7 @@ where value: val.clone(), relation, predecessors: None, - info: self.node_info.get(node_id).cloned().flatten(), + info: self.node_info.get(node_id).copied().flatten(), metadata: self.node_metadata.get(node_id).cloned().flatten(), }); memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index 1e3302dab4a..a6d2114f0fe 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -255,7 +255,6 @@ pub enum MerchantAccountUpdate { } #[cfg(feature = "v1")] - impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { fn from(merchant_account_update: MerchantAccountUpdate) -> Self { let now = date_time::now(); diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index ea994946ca8..820959a5963 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -161,7 +161,6 @@ pub enum PayLaterData { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] - pub enum WalletData { AliPayQr(Box<AliPayQr>), AliPayRedirect(AliPayRedirection), @@ -234,7 +233,6 @@ pub struct SamsungPayTokenData { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] - pub struct GooglePayWalletData { /// The type of payment method pub pm_type: String, @@ -304,7 +302,6 @@ pub struct MobilePayRedirection {} pub struct MbWayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] - pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, @@ -361,7 +358,6 @@ pub struct ApplepayPaymentMethod { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] - pub enum RealTimePaymentData { DuitNow {}, Fps {}, @@ -370,7 +366,6 @@ pub enum RealTimePaymentData { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] - pub enum BankRedirectData { BancontactCard { card_number: Option<cards::CardNumber>, diff --git a/crates/hyperswitch_interfaces/src/secrets_interface.rs b/crates/hyperswitch_interfaces/src/secrets_interface.rs index 761981bedda..6944729191a 100644 --- a/crates/hyperswitch_interfaces/src/secrets_interface.rs +++ b/crates/hyperswitch_interfaces/src/secrets_interface.rs @@ -10,11 +10,13 @@ use masking::Secret; /// Trait defining the interface for managing application secrets #[async_trait::async_trait] pub trait SecretManagementInterface: Send + Sync { + /* /// Given an input, encrypt/store the secret - // async fn store_secret( - // &self, - // input: Secret<String>, - // ) -> CustomResult<String, SecretsManagementError>; + async fn store_secret( + &self, + input: Secret<String>, + ) -> CustomResult<String, SecretsManagementError>; + */ /// Given an input, decrypt/retrieve the secret async fn get_secret( diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs index d1da6a8c8b6..9573dfa12cb 100644 --- a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs +++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs @@ -26,17 +26,13 @@ pub struct SecretStateContainer<T, S: SecretState> { } impl<T: Clone, S: SecretState> SecretStateContainer<T, S> { - /// /// Get the inner data while consuming self - /// #[inline] pub fn into_inner(self) -> T { self.inner } - /// /// Get the reference to inner value - /// #[inline] pub fn get_inner(&self) -> &T { &self.inner diff --git a/crates/kgraph_utils/src/types.rs b/crates/kgraph_utils/src/types.rs index 26f27896e0a..9ff55b68ab7 100644 --- a/crates/kgraph_utils/src/types.rs +++ b/crates/kgraph_utils/src/types.rs @@ -2,8 +2,8 @@ use std::collections::{HashMap, HashSet}; use api_models::enums as api_enums; use serde::Deserialize; -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone, Default)] pub struct CountryCurrencyFilter { pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>, pub default_configs: Option<PaymentMethodFilters>, diff --git a/crates/masking/src/abs.rs b/crates/masking/src/abs.rs index f50725d9f23..6501f89c9db 100644 --- a/crates/masking/src/abs.rs +++ b/crates/masking/src/abs.rs @@ -1,6 +1,4 @@ -//! //! Abstract data types. -//! use crate::Secret; diff --git a/crates/masking/src/boxed.rs b/crates/masking/src/boxed.rs index 67397ec3c07..42dda0873a1 100644 --- a/crates/masking/src/boxed.rs +++ b/crates/masking/src/boxed.rs @@ -1,4 +1,3 @@ -//! //! `Box` types containing secrets //! //! There is not alias type by design. diff --git a/crates/masking/src/diesel.rs b/crates/masking/src/diesel.rs index ea60a861c9d..148e50ed823 100644 --- a/crates/masking/src/diesel.rs +++ b/crates/masking/src/diesel.rs @@ -1,6 +1,4 @@ -//! //! Diesel-related. -//! use diesel::{ backend::Backend, @@ -13,7 +11,7 @@ use diesel::{ use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret}; -impl<'expr, S, I, T> AsExpression<T> for &'expr Secret<S, I> +impl<S, I, T> AsExpression<T> for &Secret<S, I> where T: sql_types::SingleValue, I: Strategy<S>, @@ -24,7 +22,7 @@ where } } -impl<'expr2, 'expr, S, I, T> AsExpression<T> for &'expr2 &'expr Secret<S, I> +impl<S, I, T> AsExpression<T> for &&Secret<S, I> where T: sql_types::SingleValue, I: Strategy<S>, @@ -81,7 +79,7 @@ where } } -impl<'expr, S, I, T> AsExpression<T> for &'expr StrongSecret<S, I> +impl<S, I, T> AsExpression<T> for &StrongSecret<S, I> where T: sql_types::SingleValue, S: ZeroizableSecret, @@ -93,7 +91,7 @@ where } } -impl<'expr2, 'expr, S, I, T> AsExpression<T> for &'expr2 &'expr StrongSecret<S, I> +impl<S, I, T> AsExpression<T> for &&StrongSecret<S, I> where T: sql_types::SingleValue, S: ZeroizableSecret, diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index d376e935bd6..49e9cbf54f7 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -2,10 +2,8 @@ #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![warn(missing_docs)] -//! //! Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped. //! Secret-keeping library inspired by secrecy. -//! #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] @@ -49,7 +47,6 @@ pub use crate::serde::{ /// This module should be included with asterisk. /// /// `use masking::prelude::*;` -/// pub mod prelude { pub use super::{ExposeInterface, ExposeOptionInterface, PeekInterface}; } diff --git a/crates/masking/src/maskable.rs b/crates/masking/src/maskable.rs index 7969c9ab8e4..e957e89b351 100644 --- a/crates/masking/src/maskable.rs +++ b/crates/masking/src/maskable.rs @@ -1,13 +1,9 @@ -//! //! This module contains Masking objects and traits -//! use crate::{ExposeInterface, Secret}; -/// /// An Enum that allows us to optionally mask data, based on which enum variant that data is stored /// in. -/// #[derive(Clone, Eq, PartialEq)] pub enum Maskable<T: Eq + PartialEq + Clone> { /// Variant which masks the data by wrapping in a Secret @@ -35,9 +31,7 @@ impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T } impl<T: Eq + PartialEq + Clone> Maskable<T> { - /// /// Get the inner data while consuming self - /// pub fn into_inner(self) -> T { match self { Self::Masked(inner_secret) => inner_secret.expose(), @@ -45,49 +39,37 @@ impl<T: Eq + PartialEq + Clone> Maskable<T> { } } - /// /// Create a new Masked data - /// pub fn new_masked(item: Secret<T>) -> Self { Self::Masked(item) } - /// /// Create a new non-masked data - /// pub fn new_normal(item: T) -> Self { Self::Normal(item) } - /// /// Checks whether the data is masked. /// Returns `true` if the data is wrapped in the `Masked` variant, /// returns `false` otherwise. - /// pub fn is_masked(&self) -> bool { matches!(self, Self::Masked(_)) } - /// /// Checks whether the data is normal (not masked). /// Returns `true` if the data is wrapped in the `Normal` variant, /// returns `false` otherwise. - /// pub fn is_normal(&self) -> bool { matches!(self, Self::Normal(_)) } } /// Trait for providing a method on custom types for constructing `Maskable` - pub trait Mask { /// The type returned by the `into_masked()` method. Must implement `PartialEq`, `Eq` and `Clone` - type Output: Eq + Clone + PartialEq; - /// /// Construct a `Maskable` instance that wraps `Self::Output` by consuming `self` - /// fn into_masked(self) -> Maskable<Self::Output>; } diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index a813829d63d..0bd28c3af92 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -1,12 +1,9 @@ -//! //! Structure describing secret. -//! use std::{fmt, marker::PhantomData}; use crate::{strategy::Strategy, PeekInterface, StrongSecret}; -/// /// Secret thing. /// /// To get access to value use method `expose()` of trait [`crate::ExposeInterface`]. @@ -39,7 +36,6 @@ use crate::{strategy::Strategy, PeekInterface, StrongSecret}; /// /// assert_eq!("hello", &format!("{:?}", my_secret)); /// ``` -/// pub struct Secret<Secret, MaskingStrategy = crate::WithType> where MaskingStrategy: Strategy<Secret>, diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index 0c5782ae04d..48514df8c6c 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -1,6 +1,4 @@ -//! //! Serde-related. -//! pub use erased_serde::Serialize as ErasedSerialize; pub use serde::{de, Deserialize, Serialize, Serializer}; @@ -17,7 +15,6 @@ use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret}; /// /// This is done deliberately to prevent accidental exfiltration of secrets /// via `serde` serialization. -/// #[cfg_attr(docsrs, cfg(feature = "serde"))] pub trait SerializableSecret: Serialize {} @@ -87,7 +84,6 @@ where } } -/// /// Masked serialization. /// /// the default behaviour for secrets is to serialize in exposed format since the common use cases @@ -99,7 +95,6 @@ pub fn masked_serialize<T: Serialize>(value: &T) -> Result<Value, serde_json::Er }) } -/// /// Masked serialization. /// /// Trait object for supporting serialization to Value while accounting for masking @@ -118,7 +113,7 @@ impl<T: Serialize + ErasedSerialize> ErasedMaskSerialize for T { } } -impl<'a> Serialize for dyn ErasedMaskSerialize + 'a { +impl Serialize for dyn ErasedMaskSerialize + '_ { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, @@ -127,7 +122,7 @@ impl<'a> Serialize for dyn ErasedMaskSerialize + 'a { } } -impl<'a> Serialize for dyn ErasedMaskSerialize + 'a + Send { +impl Serialize for dyn ErasedMaskSerialize + '_ + Send { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, diff --git a/crates/masking/src/string.rs b/crates/masking/src/string.rs index 2638fbd282e..be6e90a2155 100644 --- a/crates/masking/src/string.rs +++ b/crates/masking/src/string.rs @@ -1,4 +1,3 @@ -//! //! Secret strings //! //! There is not alias type by design. diff --git a/crates/masking/src/strong_secret.rs b/crates/masking/src/strong_secret.rs index 51c0f2cb3fe..300b5463d25 100644 --- a/crates/masking/src/strong_secret.rs +++ b/crates/masking/src/strong_secret.rs @@ -1,6 +1,4 @@ -//! //! Structure describing secret. -//! use std::{fmt, marker::PhantomData}; @@ -9,11 +7,9 @@ use zeroize::{self, Zeroize as ZeroizableSecret}; use crate::{strategy::Strategy, PeekInterface}; -/// /// Secret thing. /// /// To get access to value use method `expose()` of trait [`crate::ExposeInterface`]. -/// pub struct StrongSecret<Secret: ZeroizableSecret, MaskingStrategy = crate::WithType> { /// Inner secret value pub(crate) inner_secret: Secret, diff --git a/crates/masking/src/vec.rs b/crates/masking/src/vec.rs index 1f8c1c671e0..2a077be9943 100644 --- a/crates/masking/src/vec.rs +++ b/crates/masking/src/vec.rs @@ -1,4 +1,3 @@ -//! //! Secret `Vec` types //! //! There is not alias type by design. diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 2ffd4f4cdc7..4c9d069a458 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -549,8 +549,6 @@ pub fn payments_incremental_authorization() {} pub fn payments_external_authentication() {} /// Payments - Complete Authorize -/// -/// #[utoipa::path( post, path = "/{payment_id}/complete_authorize", @@ -569,8 +567,6 @@ pub fn payments_external_authentication() {} pub fn payments_complete_authorize() {} /// Dynamic Tax Calculation -/// -/// #[utoipa::path( post, path = "/payments/{payment_id}/calculate_tax", @@ -587,8 +583,6 @@ pub fn payments_complete_authorize() {} pub fn payments_dynamic_tax_calculation() {} /// Payments - Post Session Tokens -/// -/// #[utoipa::path( post, path = "/payments/{payment_id}/post_session_tokens", diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index b144fd046ad..9b8f56aeb81 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -68,7 +68,6 @@ pub async fn routing_link_config() {} /// Routing - Retrieve /// /// Retrieve a routing algorithm - #[utoipa::path( get, path = "/routing/{routing_algorithm_id}", @@ -91,7 +90,6 @@ pub async fn routing_retrieve_config() {} /// Routing - Retrieve /// /// Retrieve a routing algorithm with its algorithm id - #[utoipa::path( get, path = "/v2/routing-algorithm/{id}", diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index a91aa57a1e4..a10ff0d60e5 100644 --- a/crates/pm_auth/src/connector/plaid/transformers.rs +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -20,7 +20,6 @@ pub struct PlaidLinkTokenRequest { } #[derive(Debug, Serialize, Eq, PartialEq)] - pub struct User { pub client_user_id: id_type::CustomerId, } @@ -94,7 +93,6 @@ pub struct PlaidExchangeTokenRequest { } #[derive(Debug, Deserialize, Eq, PartialEq)] - pub struct PlaidExchangeTokenResponse { pub access_token: String, } @@ -236,7 +234,6 @@ pub struct PlaidBankAccountCredentialsRequest { } #[derive(Debug, Deserialize, PartialEq)] - pub struct PlaidBankAccountCredentialsResponse { pub accounts: Vec<PlaidBankAccountCredentialsAccounts>, pub numbers: PlaidBankAccountCredentialsNumbers, @@ -251,7 +248,6 @@ pub struct BankAccountCredentialsOptions { } #[derive(Debug, Deserialize, PartialEq)] - pub struct PlaidBankAccountCredentialsAccounts { pub account_id: String, pub name: String, diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 9fd07a473d4..746b424abc8 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -3,8 +3,6 @@ //! The folder provides generic functions for providing serialization //! and deserialization while calling redis. //! It also includes instruments to provide tracing. -//! -//! use std::fmt::Debug; diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs index 0e2a4b8d63b..9e0fb4639a5 100644 --- a/crates/redis_interface/src/errors.rs +++ b/crates/redis_interface/src/errors.rs @@ -1,6 +1,4 @@ -//! //! Errors specific to this custom redis interface -//! #[derive(Debug, thiserror::Error, PartialEq)] pub enum RedisError { diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index f40b81af68e..92429f617d1 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -1,7 +1,5 @@ -//! //! Data types and type conversions //! from `fred`'s internal data-types to custom data-types -//! use common_utils::errors::CustomResult; use fred::types::RedisValue as FredRedisValue; diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 12cef3aa9f7..7daee6e73d7 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1448,7 +1448,7 @@ pub enum OpenBankingUKIssuer { pub struct AdyenTestBankNames<'a>(&'a str); -impl<'a> TryFrom<&common_enums::BankNames> for AdyenTestBankNames<'a> { +impl TryFrom<&common_enums::BankNames> for AdyenTestBankNames<'_> { type Error = Error; fn try_from(bank: &common_enums::BankNames) -> Result<Self, Self::Error> { Ok(match bank { @@ -1501,7 +1501,7 @@ impl<'a> TryFrom<&common_enums::BankNames> for AdyenTestBankNames<'a> { pub struct AdyenBankNames<'a>(&'a str); -impl<'a> TryFrom<&common_enums::BankNames> for AdyenBankNames<'a> { +impl TryFrom<&common_enums::BankNames> for AdyenBankNames<'_> { type Error = Error; fn try_from(bank: &common_enums::BankNames) -> Result<Self, Self::Error> { Ok(match bank { @@ -1550,9 +1550,7 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { } } -impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> - for AdyenPaymentRequest<'a> -{ +impl TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( item: &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, @@ -1612,7 +1610,7 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> } } -impl<'a> TryFrom<&types::PaymentsPreProcessingRouterData> for AdyenBalanceRequest<'a> { +impl TryFrom<&types::PaymentsPreProcessingRouterData> for AdyenBalanceRequest<'_> { type Error = Error; fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { let payment_method = match &item.request.payment_method_data { @@ -1863,8 +1861,8 @@ fn build_shopper_reference( }) } -impl<'a> TryFrom<(&domain::BankDebitData, &types::PaymentsAuthorizeRouterData)> - for AdyenPaymentMethod<'a> +impl TryFrom<(&domain::BankDebitData, &types::PaymentsAuthorizeRouterData)> + for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -1911,8 +1909,8 @@ impl<'a> TryFrom<(&domain::BankDebitData, &types::PaymentsAuthorizeRouterData)> } } -impl<'a> TryFrom<(&domain::VoucherData, &types::PaymentsAuthorizeRouterData)> - for AdyenPaymentMethod<'a> +impl TryFrom<(&domain::VoucherData, &types::PaymentsAuthorizeRouterData)> + for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -1958,7 +1956,7 @@ impl<'a> TryFrom<(&domain::VoucherData, &types::PaymentsAuthorizeRouterData)> } } -impl<'a> TryFrom<&domain::GiftCardData> for AdyenPaymentMethod<'a> { +impl TryFrom<&domain::GiftCardData> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from(gift_card_data: &domain::GiftCardData) -> Result<Self, Self::Error> { match gift_card_data { @@ -1992,7 +1990,7 @@ fn get_adyen_card_network(card_network: common_enums::CardNetwork) -> Option<Car } } -impl<'a> TryFrom<(&domain::Card, Option<Secret<String>>)> for AdyenPaymentMethod<'a> { +impl TryFrom<(&domain::Card, Option<Secret<String>>)> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( (card, card_holder_name): (&domain::Card, Option<Secret<String>>), @@ -2068,8 +2066,8 @@ impl TryFrom<&utils::CardIssuer> for CardBrand { } } -impl<'a> TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> - for AdyenPaymentMethod<'a> +impl TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> + for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2206,7 +2204,7 @@ pub fn check_required_field<'a, T>( }) } -impl<'a> +impl TryFrom<( &domain::PayLaterData, &Option<api_enums::CountryAlpha2>, @@ -2216,7 +2214,7 @@ impl<'a> &Option<Secret<String>>, &Option<Address>, &Option<Address>, - )> for AdyenPaymentMethod<'a> + )> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2329,12 +2327,12 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &domain::BankRedirectData, Option<bool>, &types::PaymentsAuthorizeRouterData, - )> for AdyenPaymentMethod<'a> + )> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2492,11 +2490,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &domain::BankTransferData, &types::PaymentsAuthorizeRouterData, - )> for AdyenPaymentMethod<'a> + )> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2564,7 +2562,7 @@ fn get_optional_shopper_email(item: &types::PaymentsAuthorizeRouterData) -> Opti } } -impl<'a> TryFrom<&domain::payments::CardRedirectData> for AdyenPaymentMethod<'a> { +impl TryFrom<&domain::payments::CardRedirectData> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( card_redirect_data: &domain::payments::CardRedirectData, @@ -2583,11 +2581,11 @@ impl<'a> TryFrom<&domain::payments::CardRedirectData> for AdyenPaymentMethod<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, payments::MandateReferenceId, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -2719,11 +2717,11 @@ impl<'a> }) } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::Card, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -2784,11 +2782,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::BankDebitData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -2842,11 +2840,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::VoucherData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -2903,11 +2901,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::BankTransferData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -2956,11 +2954,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::GiftCardData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -3009,11 +3007,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::BankRedirectData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -3117,11 +3115,11 @@ fn get_shopper_email( } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::WalletData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -3192,11 +3190,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::PayLaterData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -3268,11 +3266,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::payments::CardRedirectData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -5098,7 +5096,6 @@ impl TryFrom<&types::DefendDisputeRouterData> for AdyenDefendDisputeRequest { #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Evidence { defense_documents: Vec<DefenseDocuments>, merchant_account_code: Secret<String>, @@ -5107,7 +5104,6 @@ pub struct Evidence { #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] - pub struct DefenseDocuments { content: Secret<String>, content_type: Option<String>, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 24c6118e44a..00624ce0f9b 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -67,13 +67,11 @@ pub struct GenericVariableInput<T> { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct BraintreeApiErrorResponse { pub api_error_response: ApiErrorResponse, } #[derive(Debug, Deserialize, Serialize)] - pub struct ErrorsObject { pub errors: Vec<ErrorObject>, @@ -82,7 +80,6 @@ pub struct ErrorsObject { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct TransactionError { pub errors: Vec<ErrorObject>, pub credit_card: Option<CreditCardError>, @@ -122,7 +119,6 @@ pub struct BraintreeErrorResponse { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] - pub enum ErrorResponses { BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>), BraintreeErrorResponse(Box<BraintreeErrorResponse>), @@ -907,7 +903,6 @@ pub struct BraintreeRefundResponseData { } #[derive(Debug, Clone, Deserialize, Serialize)] - pub struct RefundResponse { pub data: BraintreeRefundResponseData, } diff --git a/crates/router/src/connector/datatrans.rs b/crates/router/src/connector/datatrans.rs index 9c7772c5b3e..e6f0ebd0985 100644 --- a/crates/router/src/connector/datatrans.rs +++ b/crates/router/src/connector/datatrans.rs @@ -4,8 +4,8 @@ use base64::Engine; use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use error_stack::{report, ResultExt}; use masking::PeekInterface; -use transformers::{self as datatrans}; +use self::transformers as datatrans; use super::{utils as connector_utils, utils::RefundsRequestData}; use crate::{ configs::settings, diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index 9ccfcd90be3..223be54d3fd 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -99,7 +99,6 @@ pub struct GlobalpayRefreshTokenRequest { } #[derive(Debug, Serialize, Deserialize)] - pub struct CurrencyConversion { /// A unique identifier generated by Global Payments to identify the currency conversion. It /// can be used to reference a currency conversion when processing a sale or a refund @@ -108,7 +107,6 @@ pub struct CurrencyConversion { } #[derive(Debug, Serialize, Deserialize)] - pub struct Device { pub capabilities: Option<Capabilities>, @@ -128,7 +126,6 @@ pub struct Device { } #[derive(Debug, Serialize, Deserialize)] - pub struct Capabilities { pub authorization_modes: Option<Vec<AuthorizationMode>>, /// The number of lines that can be used to display information on the device. @@ -146,7 +143,6 @@ pub struct Capabilities { } #[derive(Debug, Serialize, Deserialize)] - pub struct Lodging { /// A reference that identifies the booking reference for a lodging stay. pub booking_reference: Option<String>, @@ -163,7 +159,6 @@ pub struct Lodging { } #[derive(Debug, Serialize, Deserialize)] - pub struct LodgingChargeItem { pub payment_method_program_codes: Option<Vec<PaymentMethodProgramCode>>, /// A reference that identifies the charge item, such as a lodging folio number. @@ -195,7 +190,6 @@ pub struct Notifications { } #[derive(Debug, Serialize, Deserialize)] - pub struct Order { /// Merchant defined field common to all transactions that are part of the same order. pub reference: Option<String>, @@ -239,7 +233,6 @@ pub struct PaymentMethod { } #[derive(Debug, Serialize, Deserialize)] - pub struct Apm { /// A string used to identify the payment method provider being used to execute this /// transaction. @@ -247,9 +240,7 @@ pub struct Apm { } /// Information outlining the degree of authentication executed related to a transaction. - #[derive(Debug, Serialize, Deserialize)] - pub struct Authentication { /// Information outlining the degree of 3D Secure authentication executed. pub three_ds: Option<ThreeDs>, @@ -259,9 +250,7 @@ pub struct Authentication { } /// Information outlining the degree of 3D Secure authentication executed. - #[derive(Debug, Serialize, Deserialize)] - pub struct ThreeDs { /// The reference created by the 3DSecure Directory Server to identify the specific /// authentication attempt. @@ -284,7 +273,6 @@ pub struct ThreeDs { } #[derive(Debug, Serialize, Deserialize)] - pub struct BankTransfer { /// The number or reference for the payer's bank account. pub account_number: Option<Secret<String>>, @@ -298,7 +286,6 @@ pub struct BankTransfer { pub sec_code: Option<SecCode>, } #[derive(Debug, Serialize, Deserialize)] - pub struct Bank { pub address: Option<Address>, /// The local identifier code for the bank. @@ -401,7 +388,6 @@ pub enum AuthorizationMode { /// requested amount. /// pub example: PARTIAL /// - /// /// Describes whether the device can process partial authorizations. Partial, } @@ -428,7 +414,6 @@ pub enum CaptureMode { /// Describes whether the transaction was processed in a face to face(CP) scenario or a /// Customer Not Present (CNP) scenario. - #[derive(Debug, Default, Serialize, Deserialize)] pub enum Channel { #[default] @@ -609,7 +594,6 @@ pub enum NumberType { } /// Indicates how the transaction was authorized by the merchant. - #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SecCode { @@ -766,7 +750,6 @@ pub enum CardStorageMode { /// Indicates the transaction processing model being executed when using stored /// credentials. - #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Model { diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 7f2d0d0e608..c350f151d72 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -2970,7 +2970,6 @@ pub struct PaypalSourceVerificationRequest { } #[derive(Deserialize, Serialize, Debug)] - pub struct PaypalSourceVerificationResponse { pub verification_status: PaypalSourceVerificationStatus, } diff --git a/crates/router/src/connector/riskified/transformers/api.rs b/crates/router/src/connector/riskified/transformers/api.rs index c2da0193f99..2d519b3caa8 100644 --- a/crates/router/src/connector/riskified/transformers/api.rs +++ b/crates/router/src/connector/riskified/transformers/api.rs @@ -657,7 +657,6 @@ fn get_fulfillment_status( } #[derive(Debug, Clone, Deserialize, Serialize)] - pub struct RiskifiedWebhookBody { pub id: String, pub status: RiskifiedWebhookStatus, diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/router/src/connector/signifyd/transformers/api.rs index 348ca3d099a..028c0e82518 100644 --- a/crates/router/src/connector/signifyd/transformers/api.rs +++ b/crates/router/src/connector/signifyd/transformers/api.rs @@ -702,7 +702,6 @@ impl TryFrom<&frm_types::FrmRecordReturnRouterData> for SignifydPaymentsRecordRe #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct SignifydWebhookBody { pub order_id: String, pub review_disposition: ReviewDisposition, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index ed4b97e2a99..b5901f56d3b 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -54,7 +54,7 @@ use crate::{ pub fn missing_field_err( message: &'static str, -) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + '_> { +) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, diff --git a/crates/router/src/connector/wellsfargopayout.rs b/crates/router/src/connector/wellsfargopayout.rs index 51b303494bb..fe8f5dda25f 100644 --- a/crates/router/src/connector/wellsfargopayout.rs +++ b/crates/router/src/connector/wellsfargopayout.rs @@ -3,9 +3,9 @@ pub mod transformers; use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; -use transformers as wellsfargopayout; -use super::utils::{self as connector_utils}; +use self::transformers as wellsfargopayout; +use super::utils as connector_utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 6d4dde53082..055c428b1fb 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1199,7 +1199,7 @@ struct ConnectorAuthTypeAndMetadataValidation<'a> { connector_meta_data: &'a Option<pii::SecretSerdeValue>, } -impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> { +impl ConnectorAuthTypeAndMetadataValidation<'_> { pub fn validate_auth_and_metadata_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { @@ -1576,7 +1576,7 @@ struct ConnectorAuthTypeValidation<'a> { auth_type: &'a types::ConnectorAuthType, } -impl<'a> ConnectorAuthTypeValidation<'a> { +impl ConnectorAuthTypeValidation<'_> { fn validate_connector_auth_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { @@ -1666,7 +1666,7 @@ struct ConnectorStatusAndDisabledValidation<'a> { current_status: &'a api_enums::ConnectorStatus, } -impl<'a> ConnectorStatusAndDisabledValidation<'a> { +impl ConnectorStatusAndDisabledValidation<'_> { fn validate_status_and_disabled( &self, ) -> RouterResult<(api_enums::ConnectorStatus, Option<bool>)> { @@ -1709,7 +1709,7 @@ struct PaymentMethodsEnabled<'a> { payment_methods_enabled: &'a Option<Vec<api_models::admin::PaymentMethodsEnabled>>, } -impl<'a> PaymentMethodsEnabled<'a> { +impl PaymentMethodsEnabled<'_> { fn get_payment_methods_enabled(&self) -> RouterResult<Option<Vec<pii::SecretSerdeValue>>> { let mut vec = Vec::new(); let payment_methods_enabled = match self.payment_methods_enabled.clone() { @@ -1735,7 +1735,7 @@ struct ConnectorMetadata<'a> { connector_metadata: &'a Option<pii::SecretSerdeValue>, } -impl<'a> ConnectorMetadata<'a> { +impl ConnectorMetadata<'_> { fn validate_apple_pay_certificates_in_mca_metadata(&self) -> RouterResult<()> { self.connector_metadata .clone() @@ -1826,7 +1826,7 @@ struct ConnectorTypeAndConnectorName<'a> { connector_name: &'a api_enums::Connector, } -impl<'a> ConnectorTypeAndConnectorName<'a> { +impl ConnectorTypeAndConnectorName<'_> { fn get_routable_connector(&self) -> RouterResult<Option<api_enums::RoutableConnectors>> { let mut routable_connector = api_enums::RoutableConnectors::from_str(&self.connector_name.to_string()).ok(); diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 9cfe6e6ec73..ad612ed6f3b 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3149,7 +3149,7 @@ pub fn get_banks( .iter() .skip(1) .fold(first_element.to_owned(), |acc, hs| { - acc.intersection(hs).cloned().collect() + acc.intersection(hs).copied().collect() }); } @@ -3617,7 +3617,7 @@ pub async fn list_payment_methods( .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid PaymentRoutingInfo format found in payment attempt")? - .unwrap_or_else(|| storage::PaymentRoutingInfo { + .unwrap_or(storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }); diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs index 1afdaaab062..604e8c70626 100644 --- a/crates/router/src/core/payment_methods/utils.rs +++ b/crates/router/src/core/payment_methods/utils.rs @@ -737,7 +737,7 @@ fn compile_accepted_currency_for_mca( let config_currency: Vec<common_enums::Currency> = Vec::from_iter(config_currencies) .into_iter() - .cloned() + .copied() .collect(); let dir_currencies: Vec<dir::DirValue> = config_currency @@ -767,7 +767,7 @@ fn compile_accepted_currency_for_mca( let config_currency: Vec<common_enums::Currency> = Vec::from_iter(config_currencies) .into_iter() - .cloned() + .copied() .collect(); let dir_currencies: Vec<dir::DirValue> = config_currency diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index fd61fcacf5a..684293151ed 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4312,7 +4312,7 @@ pub fn if_not_create_change_operation<'a, Op, F>( status: storage_enums::IntentStatus, confirm: Option<bool>, current: &'a Op, -) -> BoxedOperation<'_, F, api::PaymentsRequest, PaymentData<F>> +) -> BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>> where F: Send + Clone, Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>> + Send + Sync, @@ -4336,7 +4336,7 @@ where pub fn is_confirm<'a, F: Clone + Send, R, Op>( operation: &'a Op, confirm: Option<bool>, -) -> BoxedOperation<'_, F, R, PaymentData<F>> +) -> BoxedOperation<'a, F, R, PaymentData<F>> where PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, &'a PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, @@ -5044,7 +5044,7 @@ where .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through algorithm format found in payment attempt")? - .unwrap_or_else(|| storage::PaymentRoutingInfo { + .unwrap_or(storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 219a4d90519..e7de03804d1 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -19,7 +19,7 @@ use common_utils::{ MinorUnit, }, }; -use diesel_models::enums::{self}; +use diesel_models::enums; // TODO : Evaluate all the helper functions () use error_stack::{report, ResultExt}; use futures::future::Either; diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs index d516cab62fe..b8a855f5332 100644 --- a/crates/router/src/core/pm_auth/transformers.rs +++ b/crates/router/src/core/pm_auth/transformers.rs @@ -1,4 +1,4 @@ -use pm_auth::types::{self as pm_auth_types}; +use pm_auth::types as pm_auth_types; use crate::{core::errors, types, types::transformers::ForeignTryFrom}; diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index c706d8854af..ebc4c926599 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -914,7 +914,6 @@ pub async fn validate_and_create_refund( /// If payment-id is provided, lists all the refunds associated with that particular payment-id /// If payment-id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default - #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 264328796c8..c22a5021a26 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -356,7 +356,7 @@ impl MerchantConnectorAccounts { } #[cfg(feature = "v2")] -impl<'h> RoutingAlgorithmHelpers<'h> { +impl RoutingAlgorithmHelpers<'_> { fn connector_choice( &self, choice: &routing_types::RoutableConnectorChoice, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 1168ea87bf5..039e891e422 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -216,12 +216,12 @@ pub async fn connect_account( .await; logger::info!(?send_email_result); - return Ok(ApplicationResponse::Json( + Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, - )); + )) } else if find_user .as_ref() .map_err(|e| e.current_context().is_db_not_found()) diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 0250415d4fd..c01d585feb7 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use api_models::user_role::role::{self as role_api}; +use api_models::user_role::role as role_api; use common_enums::{EntityType, ParentGroup, PermissionGroup, RoleScope}; use common_utils::generate_id_with_default_len; use diesel_models::role::{RoleNew, RoleUpdate}; diff --git a/crates/router/src/db/user_authentication_method.rs b/crates/router/src/db/user_authentication_method.rs index bcc2313d5db..a02e7bdb11f 100644 --- a/crates/router/src/db/user_authentication_method.rs +++ b/crates/router/src/db/user_authentication_method.rs @@ -1,4 +1,4 @@ -use diesel_models::user_authentication_method::{self as storage}; +use diesel_models::user_authentication_method as storage; use error_stack::report; use router_env::{instrument, tracing}; diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs index 783566335bc..71f10fe73e9 100644 --- a/crates/router/src/routes/payment_link.rs +++ b/crates/router/src/routes/payment_link.rs @@ -26,7 +26,6 @@ use crate::{ security(("api_key" = []), ("publishable_key" = [])) )] #[instrument(skip(state, req), fields(flow = ?Flow::PaymentLinkRetrieve))] - pub async fn payment_link_retrieve( state: web::Data<AppState>, req: actix_web::HttpRequest, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 93f50f3ed9a..27a5462c05e 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1977,7 +1977,7 @@ impl GetLockingInput for payment_types::PaymentsCaptureRequest { struct FPaymentsApproveRequest<'a>(&'a payment_types::PaymentsApproveRequest); #[cfg(feature = "oltp")] -impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> { +impl GetLockingInput for FPaymentsApproveRequest<'_> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, @@ -1997,7 +1997,7 @@ impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> { struct FPaymentsRejectRequest<'a>(&'a payment_types::PaymentsRejectRequest); #[cfg(feature = "oltp")] -impl<'a> GetLockingInput for FPaymentsRejectRequest<'a> { +impl GetLockingInput for FPaymentsRejectRequest<'_> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index e1f113633a8..9a496c18d9a 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -403,9 +403,7 @@ impl ApiClient for ProxyClient { fn add_flow_name(&mut self, _flow_name: String) {} } -/// /// Api client for testing sending request -/// #[derive(Clone)] pub struct MockApiClient; diff --git a/crates/router/src/services/authentication/decision.rs b/crates/router/src/services/authentication/decision.rs index c31a4696bc9..4ff9f8401ba 100644 --- a/crates/router/src/services/authentication/decision.rs +++ b/crates/router/src/services/authentication/decision.rs @@ -179,10 +179,7 @@ pub async fn revoke_api_key( call_decision_service(state, decision_config, rule, RULE_DELETE_METHOD).await } -/// -/// /// Safety: i64::MAX < u64::MAX -/// #[allow(clippy::as_conversions)] pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 { let now = common_utils::date_time::now(); diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 51ae9456ecc..91968510a6b 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -94,7 +94,7 @@ impl<'a, T: KafkaMessage> KafkaEvent<'a, T> { } } -impl<'a, T: KafkaMessage> KafkaMessage for KafkaEvent<'a, T> { +impl<T: KafkaMessage> KafkaMessage for KafkaEvent<'_, T> { fn key(&self) -> String { self.event.key() } @@ -130,7 +130,7 @@ impl<'a, T: KafkaMessage> KafkaConsolidatedEvent<'a, T> { } } -impl<'a, T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'a, T> { +impl<T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'_, T> { fn key(&self) -> String { self.log.event.key() } diff --git a/crates/router/src/services/kafka/authentication.rs b/crates/router/src/services/kafka/authentication.rs index 67e488d6c8f..5cf2d066ee2 100644 --- a/crates/router/src/services/kafka/authentication.rs +++ b/crates/router/src/services/kafka/authentication.rs @@ -86,7 +86,7 @@ impl<'a> KafkaAuthentication<'a> { } } -impl<'a> super::KafkaMessage for KafkaAuthentication<'a> { +impl super::KafkaMessage for KafkaAuthentication<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/authentication_event.rs b/crates/router/src/services/kafka/authentication_event.rs index 7c8b77a3848..4169ff7b42a 100644 --- a/crates/router/src/services/kafka/authentication_event.rs +++ b/crates/router/src/services/kafka/authentication_event.rs @@ -87,7 +87,7 @@ impl<'a> KafkaAuthenticationEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaAuthenticationEvent<'a> { +impl super::KafkaMessage for KafkaAuthenticationEvent<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs index cc3a538851e..4414af494f2 100644 --- a/crates/router/src/services/kafka/dispute.rs +++ b/crates/router/src/services/kafka/dispute.rs @@ -71,7 +71,7 @@ impl<'a> KafkaDispute<'a> { } } -impl<'a> super::KafkaMessage for KafkaDispute<'a> { +impl super::KafkaMessage for KafkaDispute<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs index 64d91e8acaa..92327c044d7 100644 --- a/crates/router/src/services/kafka/dispute_event.rs +++ b/crates/router/src/services/kafka/dispute_event.rs @@ -72,7 +72,7 @@ impl<'a> KafkaDisputeEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaDisputeEvent<'a> { +impl super::KafkaMessage for KafkaDisputeEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/fraud_check.rs b/crates/router/src/services/kafka/fraud_check.rs index 26fa9e6b4e2..3010f85753b 100644 --- a/crates/router/src/services/kafka/fraud_check.rs +++ b/crates/router/src/services/kafka/fraud_check.rs @@ -53,7 +53,7 @@ impl<'a> KafkaFraudCheck<'a> { } } -impl<'a> super::KafkaMessage for KafkaFraudCheck<'a> { +impl super::KafkaMessage for KafkaFraudCheck<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/kafka/fraud_check_event.rs b/crates/router/src/services/kafka/fraud_check_event.rs index f35748cb1c8..4fd71174418 100644 --- a/crates/router/src/services/kafka/fraud_check_event.rs +++ b/crates/router/src/services/kafka/fraud_check_event.rs @@ -52,7 +52,7 @@ impl<'a> KafkaFraudCheckEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaFraudCheckEvent<'a> { +impl super::KafkaMessage for KafkaFraudCheckEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index e585b21d4b2..adfff7450bc 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -180,7 +180,7 @@ impl<'a> KafkaPaymentAttempt<'a> { } } -impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> { +impl super::KafkaMessage for KafkaPaymentAttempt<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index cbce46ad9c7..177b211ae89 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -181,7 +181,7 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaPaymentAttemptEvent<'a> { +impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index 82e33de8c60..378bddf193b 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -180,7 +180,7 @@ impl KafkaPaymentIntent<'_> { } } -impl<'a> super::KafkaMessage for KafkaPaymentIntent<'a> { +impl super::KafkaMessage for KafkaPaymentIntent<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index 5657846ca4c..7509f711620 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -182,7 +182,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaPaymentIntentEvent<'a> { +impl super::KafkaMessage for KafkaPaymentIntentEvent<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs index 7a6254bd527..babf7c1c568 100644 --- a/crates/router/src/services/kafka/payout.rs +++ b/crates/router/src/services/kafka/payout.rs @@ -77,7 +77,7 @@ impl<'a> KafkaPayout<'a> { } } -impl<'a> super::KafkaMessage for KafkaPayout<'a> { +impl super::KafkaMessage for KafkaPayout<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index 7eff6f881ba..a7e37930cf2 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -66,7 +66,7 @@ impl<'a> KafkaRefund<'a> { } } -impl<'a> super::KafkaMessage for KafkaRefund<'a> { +impl super::KafkaMessage for KafkaRefund<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index 8f9f77878a1..74278944b04 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -67,7 +67,7 @@ impl<'a> KafkaRefundEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaRefundEvent<'a> { +impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/logger.rs b/crates/router/src/services/logger.rs index 7dfd7abb844..e88d4072f90 100644 --- a/crates/router/src/services/logger.rs +++ b/crates/router/src/services/logger.rs @@ -1,5 +1,3 @@ -//! //! Logger of the system. -//! pub use crate::logger::*; diff --git a/crates/router/src/types/storage/payment_link.rs b/crates/router/src/types/storage/payment_link.rs index 9a251d760bd..ae9aa417326 100644 --- a/crates/router/src/types/storage/payment_link.rs +++ b/crates/router/src/types/storage/payment_link.rs @@ -11,8 +11,8 @@ use crate::{ core::errors::{self, CustomResult}, logger, }; -#[async_trait::async_trait] +#[async_trait::async_trait] pub trait PaymentLinkDbExt: Sized { async fn filter_by_constraints( conn: &PgPooledConn, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 4ae02668957..210ae715202 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -701,7 +701,7 @@ impl ForeignFrom<storage::Config> for api_types::Config { } } -impl<'a> ForeignFrom<&'a api_types::ConfigUpdate> for storage::ConfigUpdate { +impl ForeignFrom<&api_types::ConfigUpdate> for storage::ConfigUpdate { fn foreign_from(config: &api_types::ConfigUpdate) -> Self { Self::Update { config: Some(config.value.clone()), @@ -709,7 +709,7 @@ impl<'a> ForeignFrom<&'a api_types::ConfigUpdate> for storage::ConfigUpdate { } } -impl<'a> From<&'a domain::Address> for api_types::Address { +impl From<&domain::Address> for api_types::Address { fn from(address: &domain::Address) -> Self { // If all the fields of address are none, then pass the address as None let address_details = if address.city.is_none() diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 0bd0e81149f..8acab436491 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -25,7 +25,7 @@ pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { .attach_printable("Role groups cannot be empty"); } - let unique_groups: HashSet<_> = groups.iter().cloned().collect(); + let unique_groups: HashSet<_> = groups.iter().copied().collect(); if unique_groups.contains(&PermissionGroup::OrganizationManage) { return Err(report!(UserErrors::InvalidRoleOperation)) diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index b4fcf69241b..04fa1648492 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -243,7 +243,6 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { /// `start_after`: The first psync should happen after 60 seconds /// /// `frequency` and `count`: The next 5 retries should have an interval of 300 seconds between them -/// pub async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 92cba2eec3f..751359c7763 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -205,7 +205,6 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { } #[actix_web::test] - async fn payments_create_success() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; @@ -314,7 +313,6 @@ async fn payments_create_failure() { } #[actix_web::test] - async fn refund_for_successful_payments() { let conf = Settings::new().unwrap(); use router::connector::Aci; diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 33edd5e215e..d1fb543318f 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -166,7 +166,6 @@ pub fn diesel_enum( /// } /// ``` /// - /// # Panics /// /// Panics if a struct without named fields is provided as input to the macro @@ -505,7 +504,6 @@ pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStre /// payment_method: String, /// } /// ``` - #[proc_macro_derive( PolymorphicSchema, attributes(mandatory_in, generate_schemas, remove_in) @@ -620,6 +618,7 @@ pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::Token /// /// Example /// +/// ``` /// #[derive(Default, Serialize, FlatStruct)] /// pub struct User { /// name: String, @@ -644,7 +643,7 @@ pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::Token /// ("address.zip", "941222"), /// ("email", "[email protected]"), /// ] -/// +/// ``` #[proc_macro_derive(FlatStruct)] pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index 407e910b29d..a096c236b2f 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -5,7 +5,7 @@ use quote::{quote, ToTokens}; use strum::IntoEnumIterator; use syn::{self, parse::Parse, DeriveInput}; -use crate::macros::helpers::{self}; +use crate::macros::helpers; #[derive(Debug, Clone, Copy, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 0d46f8ac332..9b3aec4c949 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -1,8 +1,6 @@ #![warn(missing_debug_implementations)] -//! //! Environment of payment router: logger, basic config, its environment awareness. -//! #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] diff --git a/crates/router_env/src/logger/mod.rs b/crates/router_env/src/logger.rs similarity index 98% rename from crates/router_env/src/logger/mod.rs rename to crates/router_env/src/logger.rs index a7aa0610e9b..2b0ae49b1f6 100644 --- a/crates/router_env/src/logger/mod.rs +++ b/crates/router_env/src/logger.rs @@ -1,6 +1,4 @@ -//! //! Logger of the system. -//! pub use tracing::{debug, error, event as log, info, warn}; pub use tracing_attributes::instrument; diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 03cc9ac17bc..746c8ee9580 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -1,6 +1,4 @@ -//! //! Logger-specific config. -//! use std::path::PathBuf; diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index 6bcf669e73a..5c3341026c2 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -1,6 +1,4 @@ -//! //! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. -//! use std::{ collections::{HashMap, HashSet}, @@ -117,10 +115,8 @@ impl fmt::Display for RecordType { } } -/// /// Format log records. /// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries. -/// #[derive(Debug)] pub struct FormattingLayer<W, F> where @@ -145,7 +141,6 @@ where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { - /// /// Constructor of `FormattingLayer`. /// /// A `name` will be attached to all records during formatting. @@ -155,7 +150,6 @@ where /// ```rust /// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter); /// ``` - /// pub fn new( service: &str, dst_writer: W, @@ -296,11 +290,9 @@ where Ok(()) } - /// /// Flush memory buffer into an output stream trailing it with next line. /// /// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading. - /// fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> { buffer.write_all(b"\n")?; self.dst_writer.make_writer().write_all(&buffer) @@ -361,12 +353,9 @@ where Ok(buffer) } - /// /// Format message of a span. /// /// Example: "[FN_WITHOUT_COLON - START]" - /// - fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String where S: Subscriber + for<'a> LookupSpan<'a>, @@ -374,12 +363,9 @@ where format!("[{} - {}]", span.metadata().name().to_uppercase(), ty) } - /// /// Format message of an event. /// /// Examples: "[FN_WITHOUT_COLON - EVENT] Message" - /// - fn event_message<S>( span: &Option<&SpanRef<'_, S>>, event: &Event<'_>, diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index 428112fb37c..6433172edf4 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -181,9 +181,7 @@ struct TraceAssertion { } impl TraceAssertion { - /// /// Should the provided url be traced - /// fn should_trace_url(&self, url: &str) -> bool { match &self.clauses { Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)), @@ -192,9 +190,7 @@ impl TraceAssertion { } } -/// /// Conditional Sampler for providing control on url based tracing -/// #[derive(Clone, Debug)] struct ConditionalSampler<T: trace::ShouldSample + Clone + 'static>(TraceAssertion, T); diff --git a/crates/router_env/src/logger/storage.rs b/crates/router_env/src/logger/storage.rs index ce220680bb1..cdaf06ecf93 100644 --- a/crates/router_env/src/logger/storage.rs +++ b/crates/router_env/src/logger/storage.rs @@ -1,6 +1,4 @@ -//! //! Storing [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. -//! use std::{collections::HashMap, fmt, time::Instant}; diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 5d59e7ddbac..b1488b904be 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -1,6 +1,4 @@ -//! //! Types. -//! use serde::Deserialize; use strum::{Display, EnumString}; @@ -9,12 +7,9 @@ pub use tracing::{ Level, Value, }; -/// /// Category and tag of log event. /// /// Don't hesitate to add your variant if it is missing here. -/// - #[derive(Debug, Default, Deserialize, Clone, Display, EnumString)] pub enum Tag { /// General. @@ -516,9 +511,7 @@ pub enum Flow { PaymentStartRedirection, } -/// /// Trait for providing generic behaviour to flow metric -/// pub trait FlowMetric: ToString + std::fmt::Debug + Clone {} impl FlowMetric for Flow {} diff --git a/crates/router_env/tests/logger.rs b/crates/router_env/tests/logger.rs index 46b5b9538cf..1070938a8a1 100644 --- a/crates/router_env/tests/logger.rs +++ b/crates/router_env/tests/logger.rs @@ -1,10 +1,11 @@ #![allow(clippy::unwrap_used)] mod test_module; + use ::config::ConfigError; use router_env::TelemetryGuard; -use self::test_module::some_module::*; +use self::test_module::fn_with_colon; fn logger() -> error_stack::Result<&'static TelemetryGuard, ConfigError> { use once_cell::sync::OnceCell; diff --git a/crates/router_env/tests/test_module/some_module.rs b/crates/router_env/tests/test_module.rs similarity index 90% rename from crates/router_env/tests/test_module/some_module.rs rename to crates/router_env/tests/test_module.rs index 8c9dda2c08e..f3c382706b4 100644 --- a/crates/router_env/tests/test_module/some_module.rs +++ b/crates/router_env/tests/test_module.rs @@ -1,7 +1,6 @@ -use logger::instrument; use router_env as logger; -#[instrument(skip_all)] +#[tracing::instrument(skip_all)] pub async fn fn_with_colon(val: i32) { let a = 13; let b = 31; @@ -23,7 +22,7 @@ pub async fn fn_with_colon(val: i32) { fn_without_colon(131).await; } -#[instrument(fields(val3 = "abc"), skip_all)] +#[tracing::instrument(fields(val3 = "abc"), skip_all)] pub async fn fn_without_colon(val: i32) { let a = 13; let b = 31; diff --git a/crates/router_env/tests/test_module/mod.rs b/crates/router_env/tests/test_module/mod.rs deleted file mode 100644 index 7699174549d..00000000000 --- a/crates/router_env/tests/test_module/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod some_module; diff --git a/crates/scheduler/src/db/mod.rs b/crates/scheduler/src/db.rs similarity index 100% rename from crates/scheduler/src/db/mod.rs rename to crates/scheduler/src/db.rs diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index efcce567727..b81676a6cc4 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use diesel_models::{self as store}; +use diesel_models as store; use error_stack::ResultExt; use futures::lock::Mutex; use hyperswitch_domain_models::{ diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 69931057959..b32c3d22044 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -117,7 +117,7 @@ impl<'a> TryFrom<CacheRedact<'a>> for RedisValue { } } -impl<'a> TryFrom<RedisValue> for CacheRedact<'a> { +impl TryFrom<RedisValue> for CacheRedact<'_> { type Error = Report<errors::ValidationError>; fn try_from(v: RedisValue) -> Result<Self, Self::Error> { diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 2fde935b670..83d8de9c30a 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -57,7 +57,7 @@ pub enum PartitionKey<'a> { }, } // PartitionKey::MerchantIdPaymentId {merchant_id, payment_id} -impl<'a> std::fmt::Display for PartitionKey<'a> { +impl std::fmt::Display for PartitionKey<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { PartitionKey::MerchantIdPaymentId { @@ -279,7 +279,7 @@ pub enum Op<'a> { Find, } -impl<'a> std::fmt::Display for Op<'a> { +impl std::fmt::Display for Op<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Op::Insert => f.write_str("insert"),
chore
address Rust 1.83.0 clippy lints and enable more clippy lints (#6705)
cb12e3da1cc836a5ba8a98b998ba4ba7e47818af
2024-12-27 11:49:55
Shankar Singh C
fix(router): rename `management_url` to `management_u_r_l` in the apple pay session response (#6945)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 636723d808a..f1caede89cc 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3438,7 +3438,7 @@ "required": [ "payment_description", "regular_billing", - "management_url" + "management_u_r_l" ], "properties": { "payment_description": { @@ -3453,7 +3453,7 @@ "description": "A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment", "nullable": true }, - "management_url": { + "management_u_r_l": { "type": "string", "description": "A URL to a web page where the user can update or delete the payment method for the recurring payment", "example": "https://hyperswitch.io" diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 186aa6dc9c3..df7e96431db 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -6052,7 +6052,7 @@ "required": [ "payment_description", "regular_billing", - "management_url" + "management_u_r_l" ], "properties": { "payment_description": { @@ -6067,7 +6067,7 @@ "description": "A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment", "nullable": true }, - "management_url": { + "management_u_r_l": { "type": "string", "description": "A URL to a web page where the user can update or delete the payment method for the recurring payment", "example": "https://hyperswitch.io" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a1718944095..816c085b8fa 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6295,7 +6295,7 @@ pub struct ApplePayRecurringPaymentRequest { pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] - pub management_url: common_utils::types::Url, + pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index e532abaa7ea..79bcfb6a497 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -3480,7 +3480,7 @@ impl .recurring_payment_interval_count, }, billing_agreement: apple_pay_recurring_details.billing_agreement, - management_url: apple_pay_recurring_details.management_url, + management_u_r_l: apple_pay_recurring_details.management_url, } } }
fix
rename `management_url` to `management_u_r_l` in the apple pay session response (#6945)
606daa9367cac8c2ea926313019deab2f938b591
2023-11-17 21:19:41
Shankar Singh C
fix(router): add choice to use the appropriate key for jws verification (#2917)
false
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 4ab7d334f88..80daf66a692 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -440,10 +440,11 @@ pub async fn get_payment_method_from_hs_locker<'a>( let jwe_body: services::JweBody = response .get_response_inner("JweBody") .change_context(errors::VaultError::FetchPaymentMethodFailed)?; - let decrypted_payload = payment_methods::get_decrypted_response_payload(jwekey, jwe_body) - .await - .change_context(errors::VaultError::FetchPaymentMethodFailed) - .attach_printable("Error getting decrypted response payload for get card")?; + let decrypted_payload = + payment_methods::get_decrypted_response_payload(jwekey, jwe_body, locker_choice) + .await + .change_context(errors::VaultError::FetchPaymentMethodFailed) + .attach_printable("Error getting decrypted response payload for get card")?; let get_card_resp: payment_methods::RetrieveCardResp = decrypted_payload .parse_struct("RetrieveCardResp") .change_context(errors::VaultError::FetchPaymentMethodFailed)?; @@ -490,10 +491,11 @@ pub async fn call_to_locker_hs<'a>( .get_response_inner("JweBody") .change_context(errors::VaultError::FetchCardFailed)?; - let decrypted_payload = payment_methods::get_decrypted_response_payload(jwekey, jwe_body) - .await - .change_context(errors::VaultError::SaveCardFailed) - .attach_printable("Error getting decrypted response payload")?; + let decrypted_payload = + payment_methods::get_decrypted_response_payload(jwekey, jwe_body, Some(locker_choice)) + .await + .change_context(errors::VaultError::SaveCardFailed) + .attach_printable("Error getting decrypted response payload")?; let stored_card_resp: payment_methods::StoreCardResp = decrypted_payload .parse_struct("StoreCardResp") .change_context(errors::VaultError::ResponseDeserializationFailed)?; @@ -557,10 +559,11 @@ pub async fn get_card_from_hs_locker<'a>( let jwe_body: services::JweBody = response .get_response_inner("JweBody") .change_context(errors::VaultError::FetchCardFailed)?; - let decrypted_payload = payment_methods::get_decrypted_response_payload(jwekey, jwe_body) - .await - .change_context(errors::VaultError::FetchCardFailed) - .attach_printable("Error getting decrypted response payload for get card")?; + let decrypted_payload = + payment_methods::get_decrypted_response_payload(jwekey, jwe_body, Some(locker_choice)) + .await + .change_context(errors::VaultError::FetchCardFailed) + .attach_printable("Error getting decrypted response payload for get card")?; let get_card_resp: payment_methods::RetrieveCardResp = decrypted_payload .parse_struct("RetrieveCardResp") .change_context(errors::VaultError::FetchCardFailed)?; @@ -609,10 +612,14 @@ pub async fn delete_card_from_hs_locker<'a>( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while executing call_connector_api for delete card"); let jwe_body: services::JweBody = response.get_response_inner("JweBody")?; - let decrypted_payload = payment_methods::get_decrypted_response_payload(jwekey, jwe_body) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error getting decrypted response payload for delete card")?; + let decrypted_payload = payment_methods::get_decrypted_response_payload( + jwekey, + jwe_body, + Some(api_enums::LockerChoice::Basilisk), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error getting decrypted response payload for delete card")?; let delete_card_resp: payment_methods::DeleteCardResp = decrypted_payload .parse_struct("DeleteCardResp") .change_context(errors::ApiErrorResponse::InternalServerError)?; diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 45182411c28..3b4d057e602 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -189,14 +189,27 @@ pub async fn get_decrypted_response_payload( #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, jwe_body: encryption::JweBody, + locker_choice: Option<api_enums::LockerChoice>, ) -> CustomResult<String, errors::VaultError> { + let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::Basilisk); + #[cfg(feature = "kms")] - let public_key = jwekey.jwekey.peek().vault_encryption_key.as_bytes(); + let public_key = match target_locker { + api_enums::LockerChoice::Basilisk => jwekey.jwekey.peek().vault_encryption_key.as_bytes(), + api_enums::LockerChoice::Tartarus => { + jwekey.jwekey.peek().rust_locker_encryption_key.as_bytes() + } + }; + #[cfg(feature = "kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); #[cfg(not(feature = "kms"))] - let public_key = jwekey.vault_encryption_key.as_bytes(); + let public_key = match target_locker { + api_enums::LockerChoice::Basilisk => jwekey.vault_encryption_key.as_bytes(), + api_enums::LockerChoice::Tartarus => jwekey.rust_locker_encryption_key.as_bytes(), + }; + #[cfg(not(feature = "kms"))] let private_key = jwekey.vault_private_key.as_bytes();
fix
add choice to use the appropriate key for jws verification (#2917)
b80f19e24849485c9407823af3e0227129c27e7e
2023-02-27 17:06:43
Abhishek
fix(core): send metadata in payments response (#670)
false
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index bb63e5d7e1c..2c53bec09ef 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -346,6 +346,7 @@ where .payment_method_type .map(ForeignInto::foreign_into), ) + .set_metadata(payment_intent.metadata) .to_owned(), ) }
fix
send metadata in payments response (#670)
089a95069b4f9bf67378f124c737e3585c6f42d3
2024-08-28 18:57:36
Narayan Bhat
feat(api_keys): add api keys route to api v2 (#5709)
false
diff --git a/api-reference-v2/README.md b/api-reference-v2/README.md new file mode 100644 index 00000000000..61bc1f08938 --- /dev/null +++ b/api-reference-v2/README.md @@ -0,0 +1,45 @@ +# Api Reference + +We use the [openapi specification](https://swagger.io/specification) for the api reference. The openapi file is generated from the code base [openapi_spec.json](openapi_spec.json). + +## How to generate the file + +This file is automatically generated from our CI pipeline when the PR is raised. However if you want to generate it manually, the following command can be used + +```bash +cargo r -p openapi --features v2 +``` + +## Render the generated openapi spec file + +In order to render the openapi spec file, we use a tool called [mintlify](https://mintlify.com/). Local setup instructions can be found [here](https://mintlify.com/docs/development#development). Once the cli is installed, Run the following command to render the openapi spec + +- Navigate to the directory where `mint.json` exists + +```bash +cd api-reference-v2 +``` + +- Run the cli + +```bash +mintlify dev +``` + +## Add new routes to openapi + +If you have added new routes to the openapi. Then in order for them to be displayed on the mintlify, run the following commands + +- Switch to the directory where api reference ( mint.json ) exists + +```bash +cd api-reference-v2 +``` + +- Run the following command to generate the route files + +```bash +npx @mintlify/scraping@latest openapi-file openapi_spec.json -o api-reference +``` + +This will generate files in [api-reference](api-reference) folder. These routes should be added to the [mint.json](mint.json) file under navigation, under respective group. diff --git a/api-reference-v2/api-reference/api-key/api-key--create.mdx b/api-reference-v2/api-reference/api-key/api-key--create.mdx new file mode 100644 index 00000000000..a92a8ea77fd --- /dev/null +++ b/api-reference-v2/api-reference/api-key/api-key--create.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/api_keys +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx new file mode 100644 index 00000000000..13b87953f1b --- /dev/null +++ b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/api_keys/{key_id} +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx new file mode 100644 index 00000000000..37a9c9fcc09 --- /dev/null +++ b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/api_keys/{key_id} +--- \ No newline at end of file diff --git a/api-reference-v2/api-reference/api-key/api-key--update.mdx b/api-reference-v2/api-reference/api-key/api-key--update.mdx new file mode 100644 index 00000000000..8d1b6e2ee11 --- /dev/null +++ b/api-reference-v2/api-reference/api-key/api-key--update.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/api_keys/{key_id} +--- diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index 27bc39d0762..975eb291507 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -50,14 +50,6 @@ "api-reference/merchant-account/merchant-account--update" ] }, - { - "group": "Merchant Connector Account", - "pages": [ - "api-reference/merchant-connector-account/merchant-connector--create", - "api-reference/merchant-connector-account/merchant-connector--retrieve", - "api-reference/merchant-connector-account/merchant-connector--update" - ] - }, { "group": "Business Profile", "pages": [ @@ -71,6 +63,23 @@ "api-reference/business-profile/business-profile--retrieve-default-fallback-routing-algorithm" ] }, + { + "group": "Merchant Connector Account", + "pages": [ + "api-reference/merchant-connector-account/merchant-connector--create", + "api-reference/merchant-connector-account/merchant-connector--retrieve", + "api-reference/merchant-connector-account/merchant-connector--update" + ] + }, + { + "group": "API Key", + "pages": [ + "api-reference/api-key/api-key--create", + "api-reference/api-key/api-key--retrieve", + "api-reference/api-key/api-key--update", + "api-reference/api-key/api-key--revoke" + ] + }, { "group": "Routing", "pages": [ diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 7b9cf0e48c8..6882e823905 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -1128,6 +1128,175 @@ } ] } + }, + "/v2/api_keys": { + "post": { + "tags": [ + "API Key" + ], + "summary": "API Key - Create", + "description": "API Key - Create\n\nCreate a new API Key for accessing our APIs from your servers. The plaintext API Key will be\ndisplayed only once on creation, so ensure you store it securely.", + "operationId": "Create an API Key", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateApiKeyRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "API Key created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateApiKeyResponse" + } + } + } + }, + "400": { + "description": "Invalid data" + } + }, + "security": [ + { + "admin_api_key": [] + } + ] + } + }, + "/v2/api_keys/{key_id}": { + "get": { + "tags": [ + "API Key" + ], + "summary": "API Key - Retrieve", + "description": "API Key - Retrieve\n\nRetrieve information about the specified API Key.", + "operationId": "Retrieve an API Key", + "parameters": [ + { + "name": "key_id", + "in": "path", + "description": "The unique identifier for the API Key", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "API Key retrieved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetrieveApiKeyResponse" + } + } + } + }, + "404": { + "description": "API Key not found" + } + }, + "security": [ + { + "admin_api_key": [] + } + ] + }, + "put": { + "tags": [ + "API Key" + ], + "summary": "API Key - Update", + "description": "API Key - Update\n\nUpdate information for the specified API Key.", + "operationId": "Update an API Key", + "parameters": [ + { + "name": "key_id", + "in": "path", + "description": "The unique identifier for the API Key", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateApiKeyRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "API Key updated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetrieveApiKeyResponse" + } + } + } + }, + "404": { + "description": "API Key not found" + } + }, + "security": [ + { + "admin_api_key": [] + } + ] + }, + "delete": { + "tags": [ + "API Key" + ], + "summary": "API Key - Revoke", + "description": "API Key - Revoke\n\nRevoke the specified API Key. Once revoked, the API Key can no longer be used for\nauthenticating with our APIs.", + "operationId": "Revoke an API Key", + "parameters": [ + { + "name": "key_id", + "in": "path", + "description": "The unique identifier for the API Key", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "API Key revoked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RevokeApiKeyResponse" + } + } + } + }, + "404": { + "description": "API Key not found" + } + }, + "security": [ + { + "admin_api_key": [] + } + ] + } } }, "components": { @@ -8436,8 +8605,7 @@ "required": [ "connector_type", "connector_name", - "profile_id", - "merchant_id" + "profile_id" ], "properties": { "connector_type": { @@ -8551,13 +8719,6 @@ ], "nullable": true }, - "merchant_id": { - "type": "string", - "description": "The identifier for the Merchant Account", - "example": "y3oqhf46pyzuxjbcn2giaqnb44", - "maxLength": 64, - "minLength": 1 - }, "additional_merchant_data": { "allOf": [ { diff --git a/api-reference/README.md b/api-reference/README.md new file mode 100644 index 00000000000..a883fc663db --- /dev/null +++ b/api-reference/README.md @@ -0,0 +1,45 @@ +# Api Reference + +We use the [openapi specification](https://swagger.io/specification) for the api reference. The openapi file is generated from the code base [openapi_spec.json](openapi_spec.json). + +## How to generate the file + +This file is automatically generated from our CI pipeline when the PR is raised. However if you want to generate it manually, the following command can be used + +```bash +cargo r -p openapi --features v1 +``` + +## Render the generated openapi spec file + +In order to render the openapi spec file, we use a tool called [mintlify](https://mintlify.com/). Local setup instructions can be found [here](https://mintlify.com/docs/development#development). Once the cli is installed, Run the following command to render the openapi spec + +- Navigate to the directory where `mint.json` exists + +```bash +cd api-reference +``` + +- Run the cli + +```bash +mintlify dev +``` + +## Add new routes to openapi + +If you have added new routes to the openapi. Then in order for them to be displayed on the mintlify, run the following commands + +- Switch to the directory where api reference ( mint.json ) exists + +```bash +cd api-reference +``` + +- Run the following command to generate the route files + +```bash +npx @mintlify/scraping@latest openapi-file openapi_spec.json -o api-reference +``` + +This will generate files in [api-reference](api-reference) folder. These routes should be added to the [mint.json](mint.json) file under navigation, under respective group. diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 9f035846252..4a07d1179e4 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -4488,7 +4488,7 @@ ] } }, - "/api_keys/{merchant_id)": { + "/api_keys/{merchant_id}": { "post": { "tags": [ "API Key" @@ -4645,9 +4645,7 @@ "admin_api_key": [] } ] - } - }, - "/api_keys/{merchant_id)/{key_id}": { + }, "delete": { "tags": [ "API Key" diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 5b2432cda9f..56924c541d3 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -767,10 +767,6 @@ pub struct MerchantConnectorCreate { // By default the ConnectorStatus is Active pub status: Option<api_enums::ConnectorStatus>, - /// The identifier for the Merchant Account - #[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")] - pub merchant_id: id_type::MerchantId, - /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 48b2e9d98c0..7a0bbb5cbe3 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -115,7 +115,7 @@ impl_api_event_type!( String, id_type::MerchantId, (id_type::MerchantId, String), - (&id_type::MerchantId, String), + (id_type::MerchantId, &String), (&id_type::MerchantId, &String), (&String, &String), (Option<i64>, Option<i64>, String), diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 2b02ec7f715..691481858ff 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -100,6 +100,12 @@ Never share your secret api keys. Keep them guarded and secure. // Routes for routing routes::routing::routing_create_config, routes::routing::routing_retrieve_config, + + // Routes for api keys + routes::api_keys::api_key_create, + routes::api_keys::api_key_retrieve, + routes::api_keys::api_key_update, + routes::api_keys::api_key_revoke, ), components(schemas( common_utils::types::MinorUnit, diff --git a/crates/openapi/src/routes/api_keys.rs b/crates/openapi/src/routes/api_keys.rs index 2956569bfb0..7ed2afe91a1 100644 --- a/crates/openapi/src/routes/api_keys.rs +++ b/crates/openapi/src/routes/api_keys.rs @@ -1,10 +1,11 @@ +#[cfg(feature = "v1")] /// API Key - Create /// /// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be /// displayed only once on creation, so ensure you store it securely. #[utoipa::path( post, - path = "/api_keys/{merchant_id)", + path = "/api_keys/{merchant_id}", params(("merchant_id" = String, Path, description = "The unique identifier for the merchant account")), request_body= CreateApiKeyRequest, responses( @@ -17,6 +18,26 @@ )] pub async fn api_key_create() {} +#[cfg(feature = "v2")] +/// API Key - Create +/// +/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be +/// displayed only once on creation, so ensure you store it securely. +#[utoipa::path( + post, + path = "/v2/api_keys", + request_body= CreateApiKeyRequest, + responses( + (status = 200, description = "API Key created", body = CreateApiKeyResponse), + (status = 400, description = "Invalid data") + ), + tag = "API Key", + operation_id = "Create an API Key", + security(("admin_api_key" = [])) +)] +pub async fn api_key_create() {} + +#[cfg(feature = "v1")] /// API Key - Retrieve /// /// Retrieve information about the specified API Key. @@ -37,6 +58,27 @@ pub async fn api_key_create() {} )] pub async fn api_key_retrieve() {} +#[cfg(feature = "v2")] +/// API Key - Retrieve +/// +/// Retrieve information about the specified API Key. +#[utoipa::path( + get, + path = "/v2/api_keys/{key_id}", + params ( + ("key_id" = String, Path, description = "The unique identifier for the API Key") + ), + responses( + (status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse), + (status = 404, description = "API Key not found") + ), + tag = "API Key", + operation_id = "Retrieve an API Key", + security(("admin_api_key" = [])) +)] +pub async fn api_key_retrieve() {} + +#[cfg(feature = "v1")] /// API Key - Update /// /// Update information for the specified API Key. @@ -58,13 +100,35 @@ pub async fn api_key_retrieve() {} )] pub async fn api_key_update() {} +#[cfg(feature = "v2")] +/// API Key - Update +/// +/// Update information for the specified API Key. +#[utoipa::path( + put, + path = "/v2/api_keys/{key_id}", + request_body = UpdateApiKeyRequest, + params ( + ("key_id" = String, Path, description = "The unique identifier for the API Key") + ), + responses( + (status = 200, description = "API Key updated", body = RetrieveApiKeyResponse), + (status = 404, description = "API Key not found") + ), + tag = "API Key", + operation_id = "Update an API Key", + security(("admin_api_key" = [])) +)] +pub async fn api_key_update() {} + +#[cfg(feature = "v1")] /// API Key - Revoke /// /// Revoke the specified API Key. Once revoked, the API Key can no longer be used for /// authenticating with our APIs. #[utoipa::path( delete, - path = "/api_keys/{merchant_id)/{key_id}", + path = "/api_keys/{merchant_id}/{key_id}", params ( ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"), ("key_id" = String, Path, description = "The unique identifier for the API Key") @@ -78,3 +142,24 @@ pub async fn api_key_update() {} security(("admin_api_key" = [])) )] pub async fn api_key_revoke() {} + +#[cfg(feature = "v2")] +/// API Key - Revoke +/// +/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for +/// authenticating with our APIs. +#[utoipa::path( + delete, + path = "/v2/api_keys/{key_id}", + params ( + ("key_id" = String, Path, description = "The unique identifier for the API Key") + ), + responses( + (status = 200, description = "API Key revoked", body = RevokeApiKeyResponse), + (status = 404, description = "API Key not found") + ), + tag = "API Key", + operation_id = "Revoke an API Key", + security(("admin_api_key" = [])) +)] +pub async fn api_key_revoke() {} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 59ed7ae605c..4057c1a108c 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2705,7 +2705,8 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { pub async fn create_connector( state: SessionState, req: api::MerchantConnectorCreate, - merchant_id: &id_type::MerchantId, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -2716,27 +2717,13 @@ pub async fn create_connector( .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid connector name".to_string(), })?; - - let key_store = store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - merchant_id, - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let connector_metadata = ConnectorMetadata { connector_metadata: &req.metadata, }; - connector_metadata.validate_apple_pay_certificates_in_mca_metadata()?; + let merchant_id = merchant_account.get_id(); - let merchant_account = state - .store - .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + connector_metadata.validate_apple_pay_certificates_in_mca_metadata()?; #[cfg(all( any(feature = "v1", feature = "v2"), @@ -2956,19 +2943,14 @@ pub async fn retrieve_connector( #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] pub async fn retrieve_connector( state: SessionState, - merchant_id: id_type::MerchantId, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); - let key_store = store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &merchant_id, - &store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_id = merchant_account.get_id(); let mca = store .find_merchant_connector_account_by_id(key_manager_state, &id, &key_store) @@ -2978,7 +2960,7 @@ pub async fn retrieve_connector( })?; // Validate if the merchant_id sent in the request is valid - if mca.merchant_id != merchant_id { + if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", @@ -3174,19 +3156,14 @@ pub async fn delete_connector( #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] pub async fn delete_connector( state: SessionState, - merchant_id: id_type::MerchantId, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); - let key_store = db - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &merchant_id, - &db.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_id = merchant_account.get_id(); let mca = db .find_merchant_connector_account_by_id(key_manager_state, &id, &key_store) @@ -3196,7 +3173,7 @@ pub async fn delete_connector( })?; // Validate if the merchant_id sent in the request is valid - if mca.merchant_id != merchant_id { + if mca.merchant_id != *merchant_id { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Invalid merchant_id {} provided for merchant_connector_account {:?}", @@ -3215,7 +3192,7 @@ pub async fn delete_connector( })?; let response = api::MerchantConnectorDeleteResponse { - merchant_id, + merchant_id: merchant_id.clone(), id, deleted: is_deleted, }; @@ -3678,25 +3655,11 @@ impl BusinessProfileCreateBridge for api::BusinessProfileCreate { pub async fn create_business_profile( state: SessionState, request: api::BusinessProfileCreate, - merchant_id: &id_type::MerchantId, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::BusinessProfileResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); - let key_store = db - .get_merchant_key_store_by_merchant_id( - key_manager_state, - merchant_id, - &db.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - - // Get the merchant account, if few fields are not passed, then they will be inherited from - // merchant account - let merchant_account = db - .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(all( any(feature = "v1", feature = "v2"), @@ -3780,17 +3743,10 @@ pub async fn list_business_profile( pub async fn retrieve_business_profile( state: SessionState, profile_id: id_type::ProfileId, - merchant_id: id_type::MerchantId, + key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::BusinessProfileResponse> { let db = state.store.as_ref(); - let key_store = db - .get_merchant_key_store_by_merchant_id( - &(&state).into(), - &merchant_id, - &db.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + let business_profile = db .find_business_profile_by_profile_id(&(&state).into(), &key_store, &profile_id) .await @@ -4042,19 +3998,10 @@ impl BusinessProfileUpdateBridge for api::BusinessProfileUpdate { pub async fn update_business_profile( state: SessionState, profile_id: &id_type::ProfileId, - merchant_id: &id_type::MerchantId, + key_store: domain::MerchantKeyStore, request: api::BusinessProfileUpdate, ) -> RouterResponse<api::BusinessProfileResponse> { let db = state.store.as_ref(); - let key_store = db - .get_merchant_key_store_by_merchant_id( - &(&state).into(), - merchant_id, - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) - .attach_printable("Error while fetching the key store by merchant_id")?; let key_manager_state = &(&state).into(); let business_profile = db @@ -4064,12 +4011,6 @@ pub async fn update_business_profile( id: profile_id.get_string_repr().to_owned(), })?; - if business_profile.merchant_id != *merchant_id { - Err(errors::ApiErrorResponse::AccessForbidden { - resource: profile_id.get_string_repr().to_owned(), - })? - } - let business_profile_update = request .get_update_business_profile_object(&state, &key_store) .await?; diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index f06050c5303..6e907dbd91b 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -9,6 +9,7 @@ use crate::{ configs::settings, consts, core::errors::{self, RouterResponse, StorageErrorExt}, + db::domain, routes::{metrics, SessionState}, services::{authentication, ApplicationResponse}, types::{api, storage, transformers::ForeignInto}, @@ -112,22 +113,12 @@ impl PlaintextApiKey { pub async fn create_api_key( state: SessionState, api_key: api::CreateApiKeyRequest, - merchant_id: common_utils::id_type::MerchantId, + key_store: domain::MerchantKeyStore, ) -> RouterResponse<api::CreateApiKeyResponse> { let api_key_config = state.conf.api_keys.get_inner(); let store = state.store.as_ref(); - // We are not fetching merchant account as the merchant key store is needed to search for a - // merchant account. - // Instead, we're only fetching merchant key store, as it is sufficient to identify - // non-existence of a merchant account. - store - .get_merchant_key_store_by_merchant_id( - &(&state).into(), - &merchant_id, - &store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_id = key_store.merchant_id.clone(); let hash_key = api_key_config.get_hash_key()?; let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); @@ -266,12 +257,12 @@ pub async fn add_api_key_expiry_task( #[instrument(skip_all)] pub async fn retrieve_api_key( state: SessionState, - merchant_id: &common_utils::id_type::MerchantId, + merchant_id: common_utils::id_type::MerchantId, key_id: &str, ) -> RouterResponse<api::RetrieveApiKeyResponse> { let store = state.store.as_ref(); let api_key = store - .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) + .find_api_key_by_merchant_id_key_id_optional(&merchant_id, key_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed .attach_printable("Failed to retrieve API key")? diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 7616e83beef..8e679040c91 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -1,13 +1,7 @@ use actix_web::{web, HttpRequest, HttpResponse}; -#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -use error_stack::ResultExt; -#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; use router_env::{instrument, tracing, Flow}; use super::app::AppState; -#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -use crate::headers; use crate::{ core::{admin::*, api_locking}, services::{api, authentication as auth, authorization::permissions::Permission}, @@ -102,18 +96,6 @@ pub async fn merchant_account_create( /// Merchant Account - Retrieve /// /// Retrieve a merchant account details. -#[utoipa::path( - get, - path = "/accounts/{account_id}", - params (("account_id" = String, Path, description = "The unique identifier for the merchant account")), - responses( - (status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse), - (status = 404, description = "Merchant account not found") - ), - tag = "Merchant Account", - operation_id = "Retrieve a Merchant Account", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountRetrieve))] pub async fn retrieve_merchant_account( state: web::Data<AppState>, @@ -168,19 +150,6 @@ pub async fn merchant_account_list( /// Merchant Account - Update /// /// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc -#[utoipa::path( - post, - path = "/accounts/{account_id}", - request_body = MerchantAccountUpdate, - params (("account_id" = String, Path, description = "The unique identifier for the merchant account")), - responses( - (status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse), - (status = 404, description = "Merchant account not found") - ), - tag = "Merchant Account", - operation_id = "Update a Merchant Account", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountUpdate))] pub async fn update_merchant_account( state: web::Data<AppState>, @@ -212,20 +181,7 @@ pub async fn update_merchant_account( /// Merchant Account - Delete /// /// To delete a merchant account -#[utoipa::path( - delete, - path = "/accounts/{account_id}", - params (("account_id" = String, Path, description = "The unique identifier for the merchant account")), - responses( - (status = 200, description = "Merchant Account Deleted", body = MerchantAccountDeleteResponse), - (status = 404, description = "Merchant account not found") - ), - tag = "Merchant Account", - operation_id = "Delete a Merchant Account", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountDelete))] -// #[delete("/{id}")] pub async fn delete_merchant_account( state: web::Data<AppState>, req: HttpRequest, @@ -247,52 +203,6 @@ pub async fn delete_merchant_account( .await } -#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -struct HeaderMapStruct<'a> { - headers: &'a actix_http::header::HeaderMap, -} - -#[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -impl<'a> HeaderMapStruct<'a> { - pub fn from(request: &'a HttpRequest) -> Self { - HeaderMapStruct { - headers: request.headers(), - } - } - - fn get_mandatory_header_value_by_key( - &self, - key: String, - ) -> Result<&str, error_stack::Report<ApiErrorResponse>> { - self.headers - .get(&key) - .ok_or(ApiErrorResponse::InvalidRequestData { - message: format!("Missing header key: {}", key), - }) - .attach_printable(format!("Failed to find header key: {}", key))? - .to_str() - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable(format!( - "Failed to convert header value to string for header key: {}", - key - )) - } - - pub fn get_merchant_id_from_header( - &self, - ) -> crate::errors::RouterResult<common_utils::id_type::MerchantId> { - self.get_mandatory_header_value_by_key(headers::X_MERCHANT_ID.into()) - .map(|val| val.to_owned()) - .and_then(|merchant_id| { - common_utils::id_type::MerchantId::wrap(merchant_id) - .change_context(ApiErrorResponse::InternalServerError) - .attach_printable( - "Error while converting MerchantId from `x-merchant-id` string header", - ) - }) - } -} - /// Merchant Connector - Create /// /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." @@ -300,18 +210,6 @@ impl<'a> HeaderMapStruct<'a> { any(feature = "v1", feature = "v2"), not(feature = "merchant_connector_account_v2") ))] -#[utoipa::path( - post, - path = "/accounts/{account_id}/connectors", - request_body = MerchantConnectorCreate, - responses( - (status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse), - (status = 400, description = "Missing Mandatory fields"), - ), - tag = "Merchant Connector Account", - operation_id = "Create a Merchant Connector", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsCreate))] pub async fn connector_create( state: web::Data<AppState>, @@ -327,9 +225,11 @@ pub async fn connector_create( state, &req, payload, - |state, _, req, _| create_connector(state, req, &merchant_id), + |state, auth_data, req, _| { + create_connector(state, req, auth_data.merchant_account, auth_data.key_store) + }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorAccountWrite, @@ -344,18 +244,6 @@ pub async fn connector_create( /// /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -#[utoipa::path( - post, - path = "/connector_accounts", - request_body = MerchantConnectorCreate, - responses( - (status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse), - (status = 400, description = "Missing Mandatory fields"), - ), - tag = "Merchant Connector Account", - operation_id = "Create a Merchant Connector", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsCreate))] pub async fn connector_create( state: web::Data<AppState>, @@ -364,17 +252,17 @@ pub async fn connector_create( ) -> HttpResponse { let flow = Flow::MerchantConnectorsCreate; let payload = json_payload.into_inner(); - let merchant_id = payload.merchant_id.clone(); Box::pin(api::server_wrap( flow, state, &req, payload, - |state, _, req, _| create_connector(state, req, &merchant_id), + |state, auth_data, req, _| { + create_connector(state, req, auth_data.merchant_account, auth_data.key_store) + }, auth::auth_type( - &auth::AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorAccountWrite, }, req.headers(), @@ -437,7 +325,7 @@ pub async fn connector_retrieve( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantId::default(), + &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorAccountRead, @@ -452,21 +340,6 @@ pub async fn connector_retrieve( /// /// Retrieve Merchant Connector Details #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -#[utoipa::path( - get, - path = "/connector_accounts/{id}", - params( - ("id" = i32, Path, description = "The unique identifier for the Merchant Connector") - ), - responses( - (status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse), - (status = 404, description = "Merchant Connector does not exist in records"), - (status = 401, description = "Unauthorized request") - ), - tag = "Merchant Connector Account", - operation_id = "Retrieve a Merchant Connector", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsRetrieve))] pub async fn connector_retrieve( state: web::Data<AppState>, @@ -477,23 +350,22 @@ pub async fn connector_retrieve( let id = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner(); - let merchant_id = match HeaderMapStruct::from(&req).get_merchant_id_from_header() { - Ok(val) => val, - Err(err) => { - return api::log_and_return_error_response(err); - } - }; - api::server_wrap( flow, state, &req, payload, - |state, _, req, _| retrieve_connector(state, merchant_id.clone(), req.id.clone()), + |state, auth_data, req, _| { + retrieve_connector( + state, + auth_data.merchant_account, + auth_data.key_store, + req.id.clone(), + ) + }, auth::auth_type( - &auth::AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorAccountRead, }, req.headers(), @@ -536,7 +408,7 @@ pub async fn payment_connector_list( merchant_id.to_owned(), |state, _auth, merchant_id, _| list_payment_connectors(state, merchant_id, None), auth::auth_type( - &auth::AdminApiAuthWithMerchantId::default(), + &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorAccountRead, @@ -587,7 +459,7 @@ pub async fn payment_connector_list_profile( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantId::default(), + &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorAccountRead, @@ -650,7 +522,7 @@ pub async fn connector_update( ) }, auth::auth_type( - &auth::AdminApiAuthWithMerchantId::default(), + &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorAccountWrite, @@ -774,21 +646,6 @@ pub async fn connector_delete( /// /// Delete or Detach a Merchant Connector from Merchant Account #[cfg(all(feature = "v2", feature = "merchant_connector_account_v2"))] -#[utoipa::path( - delete, - path = "/connector_accounts/{id}", - params( - ("id" = i32, Path, description = "The unique identifier for the Merchant Connector") - ), - responses( - (status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse), - (status = 404, description = "Merchant Connector does not exist in records"), - (status = 401, description = "Unauthorized request") - ), - tag = "Merchant Connector Account", - operation_id = "Delete a Merchant Connector", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::MerchantConnectorsDelete))] pub async fn connector_delete( state: web::Data<AppState>, @@ -799,25 +656,22 @@ pub async fn connector_delete( let id = path.into_inner(); let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner(); - let header_map = HeaderMapStruct { - headers: req.headers(), - }; - let merchant_id = match header_map.get_merchant_id_from_header() { - Ok(val) => val, - Err(err) => { - return api::log_and_return_error_response(err); - } - }; Box::pin(api::server_wrap( flow, state, &req, payload, - |state, _, req, _| delete_connector(state, merchant_id.clone(), req.id), + |state, auth_data, req, _| { + delete_connector( + state, + auth_data.merchant_account, + auth_data.key_store, + req.id, + ) + }, auth::auth_type( - &auth::AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorAccountWrite, }, req.headers(), @@ -897,11 +751,13 @@ pub async fn business_profile_create( state, &req, payload, - |state, _, req, _| create_business_profile(state, req, &merchant_id), + |state, auth_data, req, _| { + create_business_profile(state, req, auth_data.merchant_account, auth_data.key_store) + }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + merchant_id, required_permission: Permission::MerchantAccountWrite, }, req.headers(), @@ -921,23 +777,17 @@ pub async fn business_profile_create( let flow = Flow::BusinessProfileCreate; let payload = json_payload.into_inner(); - let merchant_id = match HeaderMapStruct::from(&req).get_merchant_id_from_header() { - Ok(val) => val, - Err(err) => { - return api::log_and_return_error_response(err); - } - }; - Box::pin(api::server_wrap( flow, state, &req, payload, - |state, _, req, _| create_business_profile(state, req, &merchant_id), + |state, auth_data, req, _| { + create_business_profile(state, req, auth_data.merchant_account, auth_data.key_store) + }, auth::auth_type( - &auth::AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountWrite, }, req.headers(), @@ -968,9 +818,11 @@ pub async fn business_profile_retrieve( state, &req, profile_id, - |state, _, profile_id, _| retrieve_business_profile(state, profile_id, merchant_id.clone()), + |state, auth_data, profile_id, _| { + retrieve_business_profile(state, profile_id, auth_data.key_store) + }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountRead, @@ -992,23 +844,17 @@ pub async fn business_profile_retrieve( let flow = Flow::BusinessProfileRetrieve; let profile_id = path.into_inner(); - let merchant_id = match HeaderMapStruct::from(&req).get_merchant_id_from_header() { - Ok(val) => val, - Err(err) => { - return api::log_and_return_error_response(err); - } - }; - Box::pin(api::server_wrap( flow, state, &req, profile_id, - |state, _, profile_id, _| retrieve_business_profile(state, profile_id, merchant_id.clone()), + |state, auth_data, profile_id, _| { + retrieve_business_profile(state, profile_id, auth_data.key_store) + }, auth::auth_type( - &auth::AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, }, req.headers(), @@ -1041,9 +887,11 @@ pub async fn business_profile_update( state, &req, json_payload.into_inner(), - |state, _, req, _| update_business_profile(state, &profile_id, &merchant_id, req), + |state, auth_data, req, _| { + update_business_profile(state, &profile_id, auth_data.key_store, req) + }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, @@ -1066,23 +914,17 @@ pub async fn business_profile_update( let flow = Flow::BusinessProfileUpdate; let profile_id = path.into_inner(); - let merchant_id = match HeaderMapStruct::from(&req).get_merchant_id_from_header() { - Ok(val) => val, - Err(err) => { - return api::log_and_return_error_response(err); - } - }; - Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), - |state, _, req, _| update_business_profile(state, &profile_id, &merchant_id, req), + |state, auth_data, req, _| { + update_business_profile(state, &profile_id, auth_data.key_store, req) + }, auth::auth_type( - &auth::AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id: merchant_id.clone(), + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountWrite, }, req.headers(), diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 3513984979b..78bccad4a0d 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -12,19 +12,10 @@ use crate::{ /// /// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be /// displayed only once on creation, so ensure you store it securely. -#[utoipa::path( - post, - path = "/api_keys/{merchant_id)", - params(("merchant_id" = String, Path, description = "The unique identifier for the merchant account")), - request_body= CreateApiKeyRequest, - responses( - (status = 200, description = "API Key created", body = CreateApiKeyResponse), - (status = 400, description = "Invalid data") - ), - tag = "API Key", - operation_id = "Create an API Key", - security(("admin_api_key" = [])) -)] +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))] pub async fn api_key_create( state: web::Data<AppState>, @@ -41,11 +32,11 @@ pub async fn api_key_create( state, &req, payload, - |state, _, payload, _| async { - api_keys::create_api_key(state, payload, merchant_id.clone()).await + |state, auth_data, payload, _| async { + api_keys::create_api_key(state, payload, auth_data.key_store).await }, auth::auth_type( - &auth::AdminApiAuth, + &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ApiKeyWrite, @@ -56,24 +47,81 @@ pub async fn api_key_create( )) .await } + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))] +pub async fn api_key_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_types::CreateApiKeyRequest>, +) -> impl Responder { + let flow = Flow::ApiKeyCreate; + let payload = json_payload.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth_data, payload, _| async { + api_keys::create_api_key(state, payload, auth_data.key_store).await + }, + auth::auth_type( + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { + required_permission: Permission::ApiKeyWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +/// API Key - Retrieve +/// +/// Retrieve information about the specified API Key. +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))] +pub async fn api_key_retrieve( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> impl Responder { + let flow = Flow::ApiKeyRetrieve; + let key_id = path.into_inner(); + + api::server_wrap( + flow, + state, + &req, + &key_id, + |state, auth_data, key_id, _| { + api_keys::retrieve_api_key( + state, + auth_data.merchant_account.get_id().to_owned(), + key_id, + ) + }, + auth::auth_type( + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { + required_permission: Permission::ApiKeyRead, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] /// API Key - Retrieve /// /// Retrieve information about the specified API Key. -#[utoipa::path( - get, - path = "/api_keys/{merchant_id}/{key_id}", - params ( - ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"), - ("key_id" = String, Path, description = "The unique identifier for the API Key") - ), - responses( - (status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse), - (status = 404, description = "API Key not found") - ), - tag = "API Key", - operation_id = "Retrieve an API Key", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))] pub async fn api_key_retrieve( state: web::Data<AppState>, @@ -87,7 +135,7 @@ pub async fn api_key_retrieve( flow, state, &req, - (&merchant_id, &key_id), + (merchant_id.clone(), &key_id), |state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id), auth::auth_type( &auth::AdminApiAuth, @@ -101,25 +149,14 @@ pub async fn api_key_retrieve( ) .await } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] /// API Key - Update /// /// Update information for the specified API Key. -#[utoipa::path( - post, - path = "/api_keys/{merchant_id}/{key_id}", - request_body = UpdateApiKeyRequest, - params ( - ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"), - ("key_id" = String, Path, description = "The unique identifier for the API Key") - ), - responses( - (status = 200, description = "API Key updated", body = RetrieveApiKeyResponse), - (status = 404, description = "API Key not found") - ), - tag = "API Key", - operation_id = "Update an API Key", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyUpdate))] pub async fn api_key_update( state: web::Data<AppState>, @@ -151,25 +188,47 @@ pub async fn api_key_update( ) .await } + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +pub async fn api_key_update( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<(common_utils::id_type::MerchantId, String)>, + json_payload: web::Json<api_types::UpdateApiKeyRequest>, +) -> impl Responder { + let flow = Flow::ApiKeyUpdate; + let (merchant_id, key_id) = path.into_inner(); + let mut payload = json_payload.into_inner(); + payload.key_id = key_id; + payload.merchant_id.clone_from(&merchant_id); + + api::server_wrap( + flow, + state, + &req, + payload, + |state, _, payload, _| api_keys::update_api_key(state, payload), + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id, + required_permission: Permission::ApiKeyWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] /// API Key - Revoke /// /// Revoke the specified API Key. Once revoked, the API Key can no longer be used for /// authenticating with our APIs. -#[utoipa::path( - delete, - path = "/api_keys/{merchant_id)/{key_id}", - params ( - ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"), - ("key_id" = String, Path, description = "The unique identifier for the API Key") - ), - responses( - (status = 200, description = "API Key revoked", body = RevokeApiKeyResponse), - (status = 404, description = "API Key not found") - ), - tag = "API Key", - operation_id = "Revoke an API Key", - security(("admin_api_key" = [])) -)] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))] pub async fn api_key_revoke( state: web::Data<AppState>, @@ -197,6 +256,36 @@ pub async fn api_key_revoke( ) .await } + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))] +pub async fn api_key_revoke( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<(common_utils::id_type::MerchantId, String)>, +) -> impl Responder { + let flow = Flow::ApiKeyRevoke; + let (merchant_id, key_id) = path.into_inner(); + + api::server_wrap( + flow, + state, + &req, + (&merchant_id, &key_id), + |state, _, (merchant_id, key_id), _| api_keys::revoke_api_key(state, merchant_id, key_id), + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthMerchantFromRoute { + merchant_id: merchant_id.clone(), + required_permission: Permission::ApiKeyWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +} + /// API Key - List /// /// List all API Keys associated with your merchant account. diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 32bcc34d6bb..8201380cc29 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1405,7 +1405,27 @@ impl Poll { pub struct ApiKeys; -#[cfg(feature = "olap")] +#[cfg(all(feature = "v2", feature = "olap", feature = "merchant_account_v2"))] +impl ApiKeys { + pub fn server(state: AppState) -> Scope { + web::scope("/v2/api_keys") + .app_data(web::Data::new(state)) + .service(web::resource("").route(web::post().to(api_key_create))) + .service(web::resource("/list").route(web::get().to(api_key_list))) + .service( + web::resource("/{key_id}") + .route(web::get().to(api_key_retrieve)) + .route(web::put().to(api_key_update)) + .route(web::delete().to(api_key_revoke)), + ) + } +} + +#[cfg(all( + feature = "olap", + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] impl ApiKeys { pub fn server(state: AppState) -> Scope { web::scope("/api_keys/{merchant_id}") diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 63c40580e53..60ecbe0a2bc 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1598,7 +1598,7 @@ pub async fn payments_manual_update( &req, payload, |state, _auth, req, _req_state| payments::payments_manual_update(state, req), - &auth::AdminApiAuthWithMerchantId::default(), + &auth::AdminApiAuthWithMerchantIdFromHeader, locking_action, )) .await diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index f1de5528224..b1f12b10670 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -692,11 +692,11 @@ where } } -#[derive(Debug, Default)] -pub struct AdminApiAuthWithMerchantId(AdminApiAuth); +#[derive(Debug)] +pub struct AdminApiAuthWithMerchantIdFromRoute(pub id_type::MerchantId); #[async_trait] -impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantId +impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromRoute where A: SessionStateInfo + Sync, { @@ -705,25 +705,12 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { - self.0 + AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; - let merchant_id = - get_header_value_by_key(headers::X_MERCHANT_ID.to_string(), request_headers)? - .get_required_value(headers::X_MERCHANT_ID) - .change_context(errors::ApiErrorResponse::InvalidRequestData { - message: format!("`{}` header is missing", headers::X_MERCHANT_ID), - }) - .and_then(|merchant_id_str| { - id_type::MerchantId::try_from(std::borrow::Cow::from( - merchant_id_str.to_string(), - )) - .change_context( - errors::ApiErrorResponse::InvalidRequestData { - message: format!("`{}` header is invalid", headers::X_MERCHANT_ID), - }, - ) - })?; + + let merchant_id = self.0.clone(); + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -755,6 +742,113 @@ where } })?; + let auth = AuthenticationData { + merchant_account: merchant, + key_store, + profile_id: None, + }; + + Ok(( + auth, + AuthenticationType::AdminApiAuthWithMerchantId { merchant_id }, + )) + } +} + +/// A helper struct to extract headers from the request +struct HeaderMapStruct<'a> { + headers: &'a HeaderMap, +} + +impl<'a> HeaderMapStruct<'a> { + pub fn new(headers: &'a HeaderMap) -> Self { + HeaderMapStruct { headers } + } + + fn get_mandatory_header_value_by_key( + &self, + key: String, + ) -> Result<&str, error_stack::Report<errors::ApiErrorResponse>> { + self.headers + .get(&key) + .ok_or(errors::ApiErrorResponse::InvalidRequestData { + message: format!("Missing header key: `{}`", key), + }) + .attach_printable(format!("Failed to find header key: {}", key))? + .to_str() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "`X-Merchant-Id` in headers", + }) + .attach_printable(format!( + "Failed to convert header value to string for header key: {}", + key + )) + } + + pub fn get_merchant_id_from_header(&self) -> RouterResult<id_type::MerchantId> { + self.get_mandatory_header_value_by_key(headers::X_MERCHANT_ID.into()) + .map(|val| val.to_owned()) + .and_then(|merchant_id| { + id_type::MerchantId::wrap(merchant_id).change_context( + errors::ApiErrorResponse::InvalidRequestData { + message: format!("`{}` header is invalid", headers::X_MERCHANT_ID), + }, + ) + }) + } +} + +/// Get the merchant-id from `x-merchant-id` header +#[derive(Debug)] +pub struct AdminApiAuthWithMerchantIdFromHeader; + +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for AdminApiAuthWithMerchantIdFromHeader +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + AdminApiAuth + .authenticate_and_fetch(request_headers, state) + .await?; + + let merchant_id = HeaderMapStruct::new(request_headers).get_merchant_id_from_header()?; + + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(errors::ApiErrorResponse::MerchantAccountNotFound) + } else { + e.change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant key store for the merchant id") + } + })?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(errors::ApiErrorResponse::Unauthorized) + } else { + e.change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant account for the merchant id") + } + })?; + let auth = AuthenticationData { merchant_account: merchant, key_store, @@ -1026,6 +1120,111 @@ pub struct JWTAuthMerchantFromRoute { pub required_permission: Permission, } +pub struct JWTAuthMerchantFromHeader { + pub required_permission: Permission, +} + +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantFromHeader +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if payload.check_in_blacklist(state).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.required_permission, &permissions)?; + + let merchant_id_from_header = + HeaderMapStruct::new(request_headers).get_merchant_id_from_header()?; + + // Check if token has access to MerchantId that has been requested through headers + if payload.merchant_id != merchant_id_from_header { + return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); + } + Ok(( + (), + AuthenticationType::MerchantJwt { + merchant_id: payload.merchant_id, + user_id: Some(payload.user_id), + }, + )) + } +} + +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeader +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?; + if payload.check_in_blacklist(state).await? { + return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); + } + + let permissions = authorization::get_permissions(state, &payload).await?; + authorization::check_authorization(&self.required_permission, &permissions)?; + + let merchant_id_from_header = + HeaderMapStruct::new(request_headers).get_merchant_id_from_header()?; + + // Check if token has access to MerchantId that has been requested through headers + if payload.merchant_id != merchant_id_from_header { + return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); + } + + let key_manager_state = &(&state.session_state()).into(); + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let merchant = state + .store() + .find_merchant_account_by_merchant_id( + key_manager_state, + &payload.merchant_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken) + .attach_printable("Failed to fetch merchant account for the merchant id")?; + + let auth = AuthenticationData { + merchant_account: merchant, + key_store, + profile_id: payload.profile_id, + }; + + Ok(( + auth, + AuthenticationType::MerchantJwt { + merchant_id: payload.merchant_id, + user_id: Some(payload.user_id), + }, + )) + } +} + #[async_trait] impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantFromRoute where
feat
add api keys route to api v2 (#5709)
2dec2ca50bbac0eed6f9fc562662b86436b4b656
2023-08-03 15:36:07
Chethan Rao
refactor(payment_methods): add `requires_cvv` field to customer payment method list api object (#1852)
false
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 248525fcc40..f795513c6ef 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -577,6 +577,10 @@ pub struct CustomerPaymentMethod { #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, + + /// Whether this payment method requires CVV to be collected + #[schema(example = true)] + pub requires_cvv: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8b7db2d6c88..9dab92f67fe 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1727,6 +1727,25 @@ pub async fn list_customer_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + let is_requires_cvv = db + .find_config_by_key(format!("{}_requires_cvv", merchant_account.merchant_id).as_str()) + .await; + + let requires_cvv = match is_requires_cvv { + // If an entry is found with the config value as `false`, we set requires_cvv to false + Ok(value) => value.config != "false", + Err(err) => { + if err.current_context().is_db_not_found() { + // By default, cvv is made required field for all merchants + true + } else { + Err(err + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant_id config for requires_cvv"))? + } + } + }; + let resp = db .find_payment_method_by_customer_id_merchant_id_list( customer_id, @@ -1771,6 +1790,7 @@ pub async fn list_customer_payment_method( bank_transfer: pmd, #[cfg(not(feature = "payouts"))] bank_transfer: None, + requires_cvv, }; customer_pms.push(pma.to_owned()); diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 5334bf3d636..e25db0bde8b 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4273,7 +4273,8 @@ "customer_id", "payment_method", "recurring_enabled", - "installment_payment_enabled" + "installment_payment_enabled", + "requires_cvv" ], "properties": { "payment_token": { @@ -4359,6 +4360,11 @@ } ], "nullable": true + }, + "requires_cvv": { + "type": "boolean", + "description": "Whether this payment method requires CVV to be collected", + "example": true } } },
refactor
add `requires_cvv` field to customer payment method list api object (#1852)
8d2e573a29671bbbf74b7646b87c409b25d1b171
2023-02-15 14:28:07
Nishant Joshi
feat: add `track_caller` to functions that perform `change_context` (#592)
false
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index 8389beeeebb..b05dd25b15f 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -1,11 +1,13 @@ use crate::{core::errors, logger}; pub trait StorageErrorExt { + #[track_caller] fn to_not_found_response( self, not_found_response: errors::ApiErrorResponse, ) -> error_stack::Report<errors::ApiErrorResponse>; + #[track_caller] fn to_duplicate_response( self, duplicate_response: errors::ApiErrorResponse, @@ -41,8 +43,11 @@ impl StorageErrorExt for error_stack::Report<errors::StorageError> { } pub trait ConnectorErrorExt { + #[track_caller] fn to_refund_failed_response(self) -> error_stack::Report<errors::ApiErrorResponse>; + #[track_caller] fn to_payment_failed_response(self) -> error_stack::Report<errors::ApiErrorResponse>; + #[track_caller] fn to_verify_failed_response(self) -> error_stack::Report<errors::ApiErrorResponse>; } @@ -121,6 +126,7 @@ impl ConnectorErrorExt for error_stack::Report<errors::ConnectorError> { } pub trait RedisErrorExt { + #[track_caller] fn to_redis_failed_response(self, key: &str) -> error_stack::Report<errors::StorageError>; }
feat
add `track_caller` to functions that perform `change_context` (#592)
dfa4b50dbd5cfc927fbbd6a68725d2c51625e6d1
2024-05-01 16:07:39
Chethan Rao
feat: add an api for retrieving the extended card info from redis (#4484)
false
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index b8f4a9d6d90..59e65c0605f 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -8,9 +8,10 @@ use crate::{ PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ - PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters, - PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, - PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest, + ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints, + PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2, + PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest, + PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest, PaymentsStartRequest, RedirectionResponse, @@ -201,3 +202,5 @@ impl ApiEventMetric for PaymentsExternalAuthenticationRequest { }) } } + +impl ApiEventMetric for ExtendedCardInfoResponse {} diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 5d35ba3e490..bd19443d002 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4622,6 +4622,12 @@ pub enum PaymentLinkStatusWrap { IntentStatus(api_enums::IntentStatus), } +#[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +pub struct ExtendedCardInfoResponse { + // Encrypted customer payment method data + pub payload: String, +} + #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index bb9ef731992..810143d115b 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -470,6 +470,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentLinkResponse, api_models::payments::RetrievePaymentLinkResponse, api_models::payments::PaymentLinkInitiateRequest, + api_models::payments::ExtendedCardInfoResponse, api_models::routing::RoutingConfigRequest, api_models::routing::RoutingDictionaryRecord, api_models::routing::RoutingKind, diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 580eb4a80bc..bca1cbb64b8 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -262,6 +262,8 @@ pub enum StripeErrorCode { CurrencyConversionFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, + #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")] + ExtendedCardInfoNotFound, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes @@ -643,6 +645,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => { Self::InvalidWalletToken { wallet_name } } + errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound, } } } @@ -714,7 +717,8 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::PaymentMethodUnactivated | Self::InvalidConnectorConfiguration { .. } | Self::CurrencyConversionFailed - | Self::PaymentMethodDeleteFailed => StatusCode::BAD_REQUEST, + | Self::PaymentMethodDeleteFailed + | Self::ExtendedCardInfoNotFound => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 5d1e527d6d4..0c492f0f089 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -269,6 +269,8 @@ pub enum ApiErrorResponse { message = "Invalid Cookie" )] InvalidCookie, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")] + ExtendedCardInfoNotFound, } impl PTError for ApiErrorResponse { diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index 1197e01cdf4..880c0d7b20b 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -301,6 +301,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::InvalidCookie => { AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None)) } + Self::ExtendedCardInfoNotFound => { + AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None)) + } } } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index aa049cb6c66..e2a5f148440 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4034,3 +4034,26 @@ pub async fn payment_external_authentication( }, )) } + +#[instrument(skip_all)] +pub async fn get_extended_card_info( + state: AppState, + merchant_id: String, + payment_id: String, +) -> RouterResponse<payments_api::ExtendedCardInfoResponse> { + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let key = helpers::get_redis_key_for_extended_card_info(&merchant_id, &payment_id); + let payload = redis_conn + .get_key::<String>(&key) + .await + .change_context(errors::ApiErrorResponse::ExtendedCardInfoNotFound)?; + + Ok(services::ApplicationResponse::Json( + payments_api::ExtendedCardInfoResponse { payload }, + )) +} diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index bcc911e497a..ff69749405a 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4319,3 +4319,7 @@ pub fn validate_mandate_data_and_future_usage( Ok(()) } } + +pub fn get_redis_key_for_extended_card_info(merchant_id: &str, payment_id: &str) -> String { + format!("{merchant_id}_{payment_id}_extended_card_info") +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 595fd26f92c..d42d3fe0039 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -382,6 +382,9 @@ impl Payments { ) .service( web::resource("/{payment_id}/3ds/authentication").route(web::post().to(payments_external_authentication)), + ) + .service( + web::resource("/{payment_id}/extended_card_info").route(web::get().to(retrieve_extended_card_info)), ); } route diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index de87f7fce53..f8a0a6a5ff0 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -120,7 +120,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentsRedirect | Flow::PaymentsIncrementalAuthorization | Flow::PaymentsExternalAuthentication - | Flow::PaymentsAuthorize => Self::Payments, + | Flow::PaymentsAuthorize + | Flow::GetExtendedCardInfo => Self::Payments, Flow::PayoutsCreate | Flow::PayoutsRetrieve diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index c1d67c4ce00..c9e1cf14ce3 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1357,6 +1357,30 @@ pub async fn post_3ds_payments_authorize( .await } +/// Retrieve endpoint for merchant to fetch the encrypted customer payment method data +#[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))] +pub async fn retrieve_extended_card_info( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + path: web::Path<String>, +) -> impl Responder { + let flow = Flow::GetExtendedCardInfo; + let payment_id = path.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payment_id, + |state, auth, payment_id, _| { + payments::get_extended_card_info(state, auth.merchant_account.merchant_id, payment_id) + }, + &auth::ApiKeyAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub fn get_or_generate_payment_id( payload: &mut payment_types::PaymentsRequest, ) -> errors::RouterResult<()> { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 9dfdb6a57a8..a7aac03db51 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -402,6 +402,8 @@ pub enum Flow { RetrievePollStatus, /// Toggles the extended card info feature in profile level ToggleExtendedCardInfo, + /// Get the extended card info associated to a payment_id + GetExtendedCardInfo, } /// diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index bd4d02cf4b3..9d9d96ccac1 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -8707,6 +8707,17 @@ "mandate_revoked" ] }, + "ExtendedCardInfoResponse": { + "type": "object", + "required": [ + "payload" + ], + "properties": { + "payload": { + "type": "string" + } + } + }, "ExternalAuthenticationDetailsResponse": { "type": "object", "required": [
feat
add an api for retrieving the extended card info from redis (#4484)
fad4895f756811bb0af9ccbc69b9f6dfff3ab32f
2023-07-06 11:57:21
Abhishek Marrivagu
refactor(payments): error message of manual retry (#1617)
false
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index dcba9f60920..d6a4f429734 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2202,7 +2202,7 @@ pub fn get_attempt_type( } else { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: - format!("You cannot {action} this payment because it has status {}, you can pass manual_retry as true in request to try this payment again", payment_intent.status) + format!("You cannot {action} this payment because it has status {}, you can pass `retry_action` as `manual_retry` in request to try this payment again", payment_intent.status) } )) }
refactor
error message of manual retry (#1617)
88b4b9679d6de62bad7d52442be4565894a1d43b
2023-07-24 17:10:19
Prasunna Soppa
fix(connector): [Paypal] Fix payment status for PayPal cards (#1749)
false
diff --git a/config/config.example.toml b/config/config.example.toml index 7f32d237838..13b6a677a00 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -182,7 +182,7 @@ opayo.base_url = "https://pi-test.sagepay.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" -paypal.base_url = "https://www.sandbox.paypal.com/" +paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" powertranz.base_url = "https://staging.ptranz.com/api/" rapyd.base_url = "https://sandboxapi.rapyd.net" diff --git a/config/development.toml b/config/development.toml index 1c6864b5cad..b0e0bcc20c2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -145,7 +145,7 @@ opayo.base_url = "https://pi-test.sagepay.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" -paypal.base_url = "https://www.sandbox.paypal.com/" +paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" powertranz.base_url = "https://staging.ptranz.com/api/" rapyd.base_url = "https://sandboxapi.rapyd.net" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index fde85bf21cb..18ec15ca73c 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -104,7 +104,7 @@ opayo.base_url = "https://pi-test.sagepay.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" -paypal.base_url = "https://www.sandbox.paypal.com/" +paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" powertranz.base_url = "https://staging.ptranz.com/api/" rapyd.base_url = "https://sandboxapi.rapyd.net" diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 2639b04e497..855199cb3c8 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -262,7 +262,7 @@ pub struct PaymentsCollectionItem { expiration_time: Option<String>, id: String, final_capture: Option<bool>, - status: PaypalOrderStatus, + status: PaypalPaymentStatus, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] @@ -376,11 +376,25 @@ impl<F, T> types::ResponseId::NoResponseId, ), }; - let status = storage_enums::AttemptStatus::foreign_from(( - item.response.status, - item.response.intent, - )); - + //payment collection will always have only one element as we only make one transaction per order. + let payment_collection = &item + .response + .purchase_units + .first() + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)? + .payments; + //payment collection item will either have "authorizations" field or "capture" field, not both at a time. + let payment_collection_item = match ( + &payment_collection.authorizations, + &payment_collection.captures, + ) { + (Some(authorizations), None) => authorizations.first(), + (None, Some(captures)) => captures.first(), + _ => None, + } + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + let status = payment_collection_item.status.clone(); + let status = storage_enums::AttemptStatus::from(status); Ok(Self { status, response: Ok(types::PaymentsResponseData::TransactionResponse { diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs index 1fbd0313149..b177ed4efbb 100644 --- a/crates/router/tests/connectors/paypal.rs +++ b/crates/router/tests/connectors/paypal.rs @@ -93,7 +93,7 @@ async fn should_capture_authorized_payment() { ) .await .expect("Capture payment response"); - assert_eq!(response.status, enums::AttemptStatus::Charged); + assert_eq!(response.status, enums::AttemptStatus::Pending); } // Partially captures a payment using the manual capture flow (Non 3DS). @@ -117,7 +117,7 @@ async fn should_partially_capture_authorized_payment() { ) .await .expect("Capture payment response"); - assert_eq!(response.status, enums::AttemptStatus::Charged); + assert_eq!(response.status, enums::AttemptStatus::Pending); } // Synchronizes a payment using the manual capture flow (Non 3DS). @@ -302,7 +302,7 @@ async fn should_make_payment() { .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); - assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); + assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); } // Synchronizes a payment using the automatic capture flow (Non 3DS). @@ -314,7 +314,7 @@ async fn should_sync_auto_captured_payment() { .unwrap(); assert_eq!( authorize_response.status.clone(), - enums::AttemptStatus::Charged + enums::AttemptStatus::Pending ); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()); assert_ne!(txn_id, None, "Empty connector transaction id"); @@ -335,7 +335,7 @@ async fn should_sync_auto_captured_payment() { ) .await .unwrap(); - assert_eq!(response.status, enums::AttemptStatus::Charged,); + assert_eq!(response.status, enums::AttemptStatus::Pending); } // Refunds a payment using the automatic capture flow (Non 3DS). diff --git a/crates/router/tests/connectors/paypal_ui.rs b/crates/router/tests/connectors/paypal_ui.rs index ccae55d56d3..ef999f7aff7 100644 --- a/crates/router/tests/connectors/paypal_ui.rs +++ b/crates/router/tests/connectors/paypal_ui.rs @@ -22,7 +22,7 @@ async fn should_make_paypal_paypal_wallet_payment( Event::Assert(Assert::IsPresent("How Search works")), Event::Assert(Assert::ContainsAny( Selector::QueryParamStr, - vec!["status=succeeded"], + vec!["status=processing"], )), ], ) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 7a7354d09a4..8b479565c50 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -91,7 +91,7 @@ opayo.base_url = "https://pi-test.sagepay.com/" opennode.base_url = "https://dev-api.opennode.com" payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" -paypal.base_url = "https://www.sandbox.paypal.com/" +paypal.base_url = "https://api-m.sandbox.paypal.com/" payu.base_url = "https://secure.snd.payu.com/" powertranz.base_url = "https://staging.ptranz.com/api/" rapyd.base_url = "https://sandboxapi.rapyd.net"
fix
[Paypal] Fix payment status for PayPal cards (#1749)
a1d63d4b8be273c525aac76f22cf3bda25719f28
2024-03-04 13:11:12
Pa1NarK
refactor(test_utils): use json to run collection and add run time edit (#3807)
false
diff --git a/Cargo.lock b/Cargo.lock index b466a161097..60bc557972c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4977,14 +4977,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.9.6" +version = "1.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebee201405406dbf528b8b672104ae6d6d63e6d118cb10e4d51abbc7b58044ff" +checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.3.9", - "regex-syntax 0.7.5", + "regex-automata 0.4.5", + "regex-syntax 0.8.2", ] [[package]] @@ -4998,13 +4998,13 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.3.9" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9" +checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.7.5", + "regex-syntax 0.8.2", ] [[package]] @@ -5031,6 +5031,12 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" +[[package]] +name = "regex-syntax" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" + [[package]] name = "rend" version = "0.4.1" @@ -6356,6 +6362,7 @@ dependencies = [ "clap", "masking", "rand 0.8.5", + "regex", "reqwest", "serde", "serde_json", diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml index ceb188b74db..59ff36e6cc5 100644 --- a/crates/test_utils/Cargo.toml +++ b/crates/test_utils/Cargo.toml @@ -17,6 +17,7 @@ async-trait = "0.1.68" base64 = "0.21.2" clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage"] } rand = "0.8.5" +regex = "1.10.3" reqwest = { version = "0.11.18", features = ["native-tls"] } serde = { version = "1.0.193", features = ["derive"] } serde_json = "1.0.108" diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs index 22c91e063d8..006075895b5 100644 --- a/crates/test_utils/src/main.rs +++ b/crates/test_utils/src/main.rs @@ -16,28 +16,20 @@ fn main() { }; let status = child.wait(); - if runner.file_modified_flag { - let git_status = Command::new("git") - .args([ - "restore", - format!("{}/event.prerequest.js", runner.collection_path).as_str(), - ]) - .output(); + // Filter out None values leaving behind Some(Path) + let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect(); + let git_status = Command::new("git").arg("restore").args(&paths).output(); - match git_status { - Ok(output) => { - if output.status.success() { - let stdout_str = String::from_utf8_lossy(&output.stdout); - println!("Git command executed successfully: {stdout_str}"); - } else { - let stderr_str = String::from_utf8_lossy(&output.stderr); - eprintln!("Git command failed with error: {stderr_str}"); - } - } - Err(e) => { - eprintln!("Error running Git: {e}"); + match git_status { + Ok(output) => { + if !output.status.success() { + let stderr_str = String::from_utf8_lossy(&output.stderr); + eprintln!("Git command failed with error: {stderr_str}"); } } + Err(e) => { + eprintln!("Error running Git: {e}"); + } } let exit_code = match status { diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs index 961853548a2..e70c630cffe 100644 --- a/crates/test_utils/src/newman_runner.rs +++ b/crates/test_utils/src/newman_runner.rs @@ -1,7 +1,14 @@ -use std::{env, io::Write, path::Path, process::Command}; +use std::{ + env, + fs::{self, OpenOptions}, + io::{self, Write}, + path::Path, + process::{exit, Command}, +}; use clap::{arg, command, Parser}; use masking::PeekInterface; +use regex::Regex; use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap}; #[derive(Parser)] @@ -33,14 +40,24 @@ struct Args { pub struct ReturnArgs { pub newman_command: Command, - pub file_modified_flag: bool, + pub modified_file_paths: Vec<Option<String>>, pub collection_path: String, } -// Just by the name of the connector, this function generates the name of the collection dir +// Generates the name of the collection JSON file for the specified connector. +// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json +#[inline] +fn get_collection_path(name: impl AsRef<str>) -> String { + format!( + "postman/collection-json/{}.postman_collection.json", + name.as_ref() + ) +} + +// Generates the name of the collection directory for the specified connector. // Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe #[inline] -fn get_path(name: impl AsRef<str>) -> String { +fn get_dir_path(name: impl AsRef<str>) -> String { format!("postman/collection-dir/{}", name.as_ref()) } @@ -72,22 +89,34 @@ pub fn generate_newman_command() -> ReturnArgs { let base_url = args.base_url; let admin_api_key = args.admin_api_key; - let collection_path = get_path(&connector_name); + let collection_path = get_collection_path(&connector_name); + let collection_dir_path = get_dir_path(&connector_name); let auth_map = ConnectorAuthenticationMap::new(); let inner_map = auth_map.inner(); - // Newman runner - // Depending on the conditions satisfied, variables are added. Since certificates of stripe have already - // been added to the postman collection, those conditions are set to true and collections that have - // variables set up for certificate, will consider those variables and will fail. + /* + Newman runner + Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments. + It can be overridden by explicitly passing certificates as arguments. + + If the collection requires certificates (Stripe collection for example) during the merchant connector account create step, + then Stripe's certificates will be passed implicitly (for now). + If any other connector requires certificates to be passed, that has to be passed explicitly for now. + */ let mut newman_command = Command::new("newman"); - newman_command.args(["dir-run", &collection_path]); + newman_command.args(["run", &collection_path]); newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]); newman_command.args(["--env-var", &format!("baseUrl={base_url}")]); - if let Some(auth_type) = inner_map.get(&connector_name) { + let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path); + + // validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses + let (connector_name, modified_collection_file_paths) = + check_connector_for_dynamic_amount(&connector_name); + + if let Some(auth_type) = inner_map.get(connector_name) { match auth_type { ConnectorAuthType::HeaderKey { api_key } => { newman_command.args([ @@ -187,24 +216,126 @@ pub fn generate_newman_command() -> ReturnArgs { newman_command.arg("--verbose"); } - let mut modified = false; - if let Some(headers) = &args.custom_headers { + ReturnArgs { + newman_command, + modified_file_paths: vec![modified_collection_file_paths, custom_header_exist], + collection_path, + } +} + +pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> { + if let Some(headers) = &headers { for header in headers { if let Some((key, value)) = header.split_once(':') { let content_to_insert = format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#); - if insert_content(&collection_path, &content_to_insert).is_ok() { - modified = true; + + if let Err(err) = insert_content(path, &content_to_insert) { + eprintln!("An error occurred while inserting the custom header: {err}"); } } else { eprintln!("Invalid header format: {}", header); } } + + return Some(format!("{}/event.prerequest.js", path)); } + None +} - ReturnArgs { - newman_command, - file_modified_flag: modified, - collection_path, +// If the connector name exists in dynamic_amount_connectors, +// the corresponding collection is modified at runtime to remove double quotes +pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) { + let collection_dir_path = get_dir_path(connector_name); + + let dynamic_amount_connectors = ["nmi", "powertranz"]; + + if dynamic_amount_connectors.contains(&connector_name) { + return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None)); + } + /* + If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers, + since we're running from collections directly, we'll have to export the collection again and it is much simpler. + We could directly inject the custom-headers using regex, but it is not encouraged as it is hard + to determine the place of edit. + */ + export_collection(connector_name, collection_dir_path); + + (connector_name, None) +} + +/* +Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within +double quotes without which it fails to execute. +For integer values like `amount`, this is a bummer as it flags the value stating it is of type +string and not integer. +Refactoring is done in 2 steps: +- Export the collection to json (although the json will be up-to-date, we export it again for safety) +- Use regex to replace the values which removes double quotes from integer values + Ex: \"{{amount}}\" -> {{amount}} +*/ + +pub fn remove_quotes_for_integer_values( + connector_name: &str, +) -> Result<(&str, Option<String>), io::Error> { + let collection_path = get_collection_path(connector_name); + let collection_dir_path = get_dir_path(connector_name); + + let values_to_replace = [ + "amount", + "another_random_number", + "capture_amount", + "random_number", + "refund_amount", + ]; + + export_collection(connector_name, collection_dir_path); + + let mut contents = fs::read_to_string(&collection_path)?; + for value_to_replace in values_to_replace { + if let Ok(re) = Regex::new(&format!( + r#"\\"(?P<field>\{{\{{{}\}}\}})\\""#, + value_to_replace + )) { + contents = re.replace_all(&contents, "$field").to_string(); + } else { + eprintln!("Regex validation failed."); + } + + let mut file = OpenOptions::new() + .write(true) + .truncate(true) + .open(&collection_path)?; + + file.write_all(contents.as_bytes())?; + } + + Ok((connector_name, Some(collection_path))) +} + +pub fn export_collection(connector_name: &str, collection_dir_path: String) { + let collection_path = get_collection_path(connector_name); + + let mut newman_command = Command::new("newman"); + newman_command.args([ + "dir-import".to_owned(), + collection_dir_path, + "-o".to_owned(), + collection_path.clone(), + ]); + + match newman_command.spawn().and_then(|mut child| child.wait()) { + Ok(exit_status) => { + if exit_status.success() { + println!("Conversion of collection from directory structure to json successful!"); + } else { + eprintln!("Conversion of collection from directory structure to json failed!"); + exit(exit_status.code().unwrap_or(1)); + } + } + Err(err) => { + eprintln!("Failed to execute dir-import: {:?}", err); + exit(1); + } } } diff --git a/postman/collection-dir/aci/Health check/New Request/request.json b/postman/collection-dir/aci/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/aci/Health check/New Request/request.json +++ b/postman/collection-dir/aci/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/adyen_uk/Health check/New Request/request.json b/postman/collection-dir/adyen_uk/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/adyen_uk/Health check/New Request/request.json +++ b/postman/collection-dir/adyen_uk/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/airwallex/Health check/New Request/request.json b/postman/collection-dir/airwallex/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/airwallex/Health check/New Request/request.json +++ b/postman/collection-dir/airwallex/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/authorizedotnet/Health check/New Request/request.json b/postman/collection-dir/authorizedotnet/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/authorizedotnet/Health check/New Request/request.json +++ b/postman/collection-dir/authorizedotnet/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/bambora/Health check/New Request/request.json b/postman/collection-dir/bambora/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/bambora/Health check/New Request/request.json +++ b/postman/collection-dir/bambora/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/bambora_3ds/Health check/New Request/request.json b/postman/collection-dir/bambora_3ds/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/bambora_3ds/Health check/New Request/request.json +++ b/postman/collection-dir/bambora_3ds/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/bankofamerica/Health check/New Request/request.json b/postman/collection-dir/bankofamerica/Health check/New Request/request.json index 4cc8d4b1a96..ce92926c776 100644 --- a/postman/collection-dir/bankofamerica/Health check/New Request/request.json +++ b/postman/collection-dir/bankofamerica/Health check/New Request/request.json @@ -1,20 +1,9 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "health" - ] + "host": ["{{baseUrl}}"], + "path": ["health"] } } diff --git a/postman/collection-dir/bluesnap/Health check/New Request/request.json b/postman/collection-dir/bluesnap/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/bluesnap/Health check/New Request/request.json +++ b/postman/collection-dir/bluesnap/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/braintree/Health check/New Request/request.json b/postman/collection-dir/braintree/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/braintree/Health check/New Request/request.json +++ b/postman/collection-dir/braintree/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/checkout/Health check/New Request/request.json b/postman/collection-dir/checkout/Health check/New Request/request.json index 4cc8d4b1a96..ce92926c776 100644 --- a/postman/collection-dir/checkout/Health check/New Request/request.json +++ b/postman/collection-dir/checkout/Health check/New Request/request.json @@ -1,20 +1,9 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "health" - ] + "host": ["{{baseUrl}}"], + "path": ["health"] } } diff --git a/postman/collection-dir/forte/Health check/New Request/request.json b/postman/collection-dir/forte/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/forte/Health check/New Request/request.json +++ b/postman/collection-dir/forte/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/globalpay/Health check/New Request/request.json b/postman/collection-dir/globalpay/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/globalpay/Health check/New Request/request.json +++ b/postman/collection-dir/globalpay/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/hyperswitch/Health check/New Request/request.json b/postman/collection-dir/hyperswitch/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/hyperswitch/Health check/New Request/request.json +++ b/postman/collection-dir/hyperswitch/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/mollie/Health check/New Request/request.json b/postman/collection-dir/mollie/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/mollie/Health check/New Request/request.json +++ b/postman/collection-dir/mollie/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/multisafepay/Health check/New Request/request.json b/postman/collection-dir/multisafepay/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/multisafepay/Health check/New Request/request.json +++ b/postman/collection-dir/multisafepay/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/nexinets/Health check/New Request/request.json b/postman/collection-dir/nexinets/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/nexinets/Health check/New Request/request.json +++ b/postman/collection-dir/nexinets/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json index 6c99817eb04..7b72495e5c4 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json @@ -29,12 +29,7 @@ "key": "Accept", "value": "application/json" }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - }, + , { "key": "publishable_key", "value": "", @@ -79,14 +74,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json index 2d931088d18..bad52859824 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json @@ -18,18 +18,14 @@ } }, "raw_json_formatted": { - "amount": "{{another_random_number}}" + "amount": "{{another_random_number}}", + "amount_to_capture": "{{another_random_number}}" } }, "url": { "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json index 6c99817eb04..7b72495e5c4 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json @@ -29,12 +29,7 @@ "key": "Accept", "value": "application/json" }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - }, + , { "key": "publishable_key", "value": "", @@ -79,14 +74,8 @@ }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id", - "confirm" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id", "confirm"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json index 2d931088d18..bad52859824 100644 --- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json +++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json @@ -18,18 +18,14 @@ } }, "raw_json_formatted": { - "amount": "{{another_random_number}}" + "amount": "{{another_random_number}}", + "amount_to_capture": "{{another_random_number}}" } }, "url": { "raw": "{{baseUrl}}/payments/:id", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "payments", - ":id" - ], + "host": ["{{baseUrl}}"], + "path": ["payments", ":id"], "variable": [ { "key": "id", diff --git a/postman/collection-dir/nmi/Health check/New Request/request.json b/postman/collection-dir/nmi/Health check/New Request/request.json index 4cc8d4b1a96..ce92926c776 100644 --- a/postman/collection-dir/nmi/Health check/New Request/request.json +++ b/postman/collection-dir/nmi/Health check/New Request/request.json @@ -1,20 +1,9 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "health" - ] + "host": ["{{baseUrl}}"], + "path": ["health"] } } diff --git a/postman/collection-dir/payme/Health check/New Request/request.json b/postman/collection-dir/payme/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/payme/Health check/New Request/request.json +++ b/postman/collection-dir/payme/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/paypal/Health check/New Request/request.json b/postman/collection-dir/paypal/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/paypal/Health check/New Request/request.json +++ b/postman/collection-dir/paypal/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/powertranz/Health check/New Request/request.json b/postman/collection-dir/powertranz/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/powertranz/Health check/New Request/request.json +++ b/postman/collection-dir/powertranz/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/rapyd/Health check/New Request/request.json b/postman/collection-dir/rapyd/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/rapyd/Health check/New Request/request.json +++ b/postman/collection-dir/rapyd/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/shift4/Health check/New Request/request.json b/postman/collection-dir/shift4/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/shift4/Health check/New Request/request.json +++ b/postman/collection-dir/shift4/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json index fed600e09cd..dfe421f512f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json @@ -24,23 +24,12 @@ { "key": "Accept", "value": "application/json" - }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true } ], "url": { "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - "payment_methods" - ], + "host": ["{{baseUrl}}"], + "path": ["account", "payment_methods"], "query": [ { "key": "client_secret", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json index fed600e09cd..dfe421f512f 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json @@ -24,23 +24,12 @@ { "key": "Accept", "value": "application/json" - }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true } ], "url": { "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "account", - "payment_methods" - ], + "host": ["{{baseUrl}}"], + "path": ["account", "payment_methods"], "query": [ { "key": "client_secret", diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json index 5b0c090f2be..5a51941cf64 100644 --- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json +++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json @@ -29,12 +29,7 @@ "key": "Accept", "value": "application/json" }, - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - }, + , { "key": "publishable_key", "value": "", diff --git a/postman/collection-dir/stripe/Health check/New Request/request.json b/postman/collection-dir/stripe/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/stripe/Health check/New Request/request.json +++ b/postman/collection-dir/stripe/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/trustpay/Health check/New Request/request.json b/postman/collection-dir/trustpay/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/trustpay/Health check/New Request/request.json +++ b/postman/collection-dir/trustpay/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/volt/Health check/New Request/request.json b/postman/collection-dir/volt/Health check/New Request/request.json index 4cc8d4b1a96..ce92926c776 100644 --- a/postman/collection-dir/volt/Health check/New Request/request.json +++ b/postman/collection-dir/volt/Health check/New Request/request.json @@ -1,20 +1,9 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", - "host": [ - "{{baseUrl}}" - ], - "path": [ - "health" - ] + "host": ["{{baseUrl}}"], + "path": ["health"] } } diff --git a/postman/collection-dir/wise/Health check/Health/request.json b/postman/collection-dir/wise/Health check/Health/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/wise/Health check/Health/request.json +++ b/postman/collection-dir/wise/Health check/Health/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/worldline/Health check/New Request/request.json b/postman/collection-dir/worldline/Health check/New Request/request.json index e40e9396178..ce92926c776 100644 --- a/postman/collection-dir/worldline/Health check/New Request/request.json +++ b/postman/collection-dir/worldline/Health check/New Request/request.json @@ -1,13 +1,6 @@ { "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], diff --git a/postman/collection-dir/zen/Health check/New Request/request.json b/postman/collection-dir/zen/Health check/New Request/request.json index 9b836ff05cb..24ea5a4157a 100644 --- a/postman/collection-dir/zen/Health check/New Request/request.json +++ b/postman/collection-dir/zen/Health check/New Request/request.json @@ -3,14 +3,7 @@ "type": "noauth" }, "method": "GET", - "header": [ - { - "key": "x-feature", - "value": "router-custom", - "type": "text", - "disabled": true - } - ], + "header": [], "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"],
refactor
use json to run collection and add run time edit (#3807)
c7bb9ccda3ce307ffba29072b28bdea0a0eaa7f5
2024-09-27 18:52:40
Narayan Bhat
refactor(payment_attempt_v2): add payment attempt v2 domain and diesel models (#6027)
false
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index c16b1d9a418..e8668aab502 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -19,7 +19,6 @@ recon = [] v1 = ["common_utils/v1"] v2 = ["common_utils/v2", "customer_v2"] customer_v2 = ["common_utils/customer_v2"] -payment_v2 = [] payment_methods_v2 = ["common_utils/payment_methods_v2"] [dependencies] diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index 6b288899778..02d917f3b17 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -13,7 +13,6 @@ kv_store = [] v1 = [] v2 = [] customer_v2 = [] -payment_v2 = [] payment_methods_v2 = [] [dependencies] diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index 1cf7fc9d81c..d91e57a2b5d 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -1,7 +1,7 @@ use error_stack::ResultExt; use serde::{Deserialize, Serialize}; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::payment_attempt::PaymentAttemptUpdateInternal; use crate::{ address::{Address, AddressNew, AddressUpdateInternal}, @@ -111,11 +111,11 @@ impl DBOperation { Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig .update_with_attempt_id( diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 63ce905f65f..75a9aeda2b8 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -4,35 +4,24 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::enums::{self as storage_enums}; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] use crate::schema::payment_attempt; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::schema_v2::payment_attempt; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable, )] -#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = payment_attempt, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentAttempt { - pub payment_id: id_type::PaymentId, + pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, - pub attempt_id: String, pub status: storage_enums::AttemptStatus, - pub amount: MinorUnit, - pub currency: Option<storage_enums::Currency>, - pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, - pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, - pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, - pub payment_method: Option<storage_enums::PaymentMethod>, - pub connector_transaction_id: Option<String>, - pub capture_method: Option<storage_enums::CaptureMethod>, - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] @@ -43,22 +32,15 @@ pub struct PaymentAttempt { pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, - pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub error_code: Option<String>, pub payment_token: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<storage_enums::PaymentExperience>, - pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, - pub business_sub_label: Option<String>, - pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - // providing a location to store mandate details intermediately for transaction - pub mandate_details: Option<storage_enums::MandateDataType>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, - // reference to the payment at connector side pub connector_response_reference_id: Option<String>, pub amount_capturable: MinorUnit, pub updated_by: String, @@ -71,7 +53,6 @@ pub struct PaymentAttempt { pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<String>, - pub mandate_data: Option<storage_enums::MandateDetails>, pub fingerprint_id: Option<String>, pub payment_method_billing_address_id: Option<String>, pub charge_id: Option<String>, @@ -81,11 +62,19 @@ pub struct PaymentAttempt { pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, + pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, + pub connector_payment_id: Option<String>, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub routing_result: Option<serde_json::Value>, + pub authentication_applied: Option<common_enums::AuthenticationType>, + pub external_reference_id: Option<String>, + pub tax_on_surcharge: Option<MinorUnit>, + pub id: String, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable, )] @@ -161,6 +150,7 @@ pub struct PaymentAttempt { pub order_tax_amount: Option<MinorUnit>, } +#[cfg(feature = "v1")] impl PaymentAttempt { pub fn get_or_calculate_net_amount(&self) -> MinorUnit { self.net_amount.unwrap_or( @@ -181,6 +171,62 @@ pub struct PaymentListFilters { pub payment_method: Vec<storage_enums::PaymentMethod>, } +#[cfg(feature = "v2")] +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] +#[diesel(table_name = payment_attempt)] +pub struct PaymentAttemptNew { + pub payment_id: id_type::GlobalPaymentId, + pub merchant_id: id_type::MerchantId, + pub status: storage_enums::AttemptStatus, + pub error_message: Option<String>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_on_surcharge: Option<MinorUnit>, + pub payment_method_id: Option<String>, + pub confirm: bool, + pub authentication_type: Option<storage_enums::AuthenticationType>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub last_synced: Option<PrimitiveDateTime>, + pub cancellation_reason: Option<String>, + pub amount_to_capture: Option<MinorUnit>, + pub browser_info: Option<serde_json::Value>, + pub payment_token: Option<String>, + pub error_code: Option<String>, + pub connector_metadata: Option<serde_json::Value>, + pub payment_experience: Option<storage_enums::PaymentExperience>, + pub payment_method_data: Option<serde_json::Value>, + pub preprocessing_step_id: Option<String>, + pub error_reason: Option<String>, + pub connector_response_reference_id: Option<String>, + pub multiple_capture_count: Option<i16>, + pub amount_capturable: MinorUnit, + pub updated_by: String, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + pub authentication_data: Option<serde_json::Value>, + pub encoded_data: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub net_amount: Option<MinorUnit>, + pub external_three_ds_authentication_attempted: Option<bool>, + pub authentication_connector: Option<String>, + pub authentication_id: Option<String>, + pub fingerprint_id: Option<String>, + pub payment_method_billing_address_id: Option<String>, + pub charge_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, + pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub profile_id: id_type::ProfileId, + pub organization_id: id_type::OrganizationId, + pub card_network: Option<String>, + pub shipping_cost: Option<MinorUnit>, + pub order_tax_amount: Option<MinorUnit>, +} + +#[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptNew { @@ -252,6 +298,7 @@ pub struct PaymentAttemptNew { pub order_tax_amount: Option<MinorUnit>, } +#[cfg(feature = "v1")] impl PaymentAttemptNew { /// returns amount + surcharge_amount + tax_amount (surcharge) + shipping_cost + order_tax_amount pub fn calculate_net_amount(&self) -> MinorUnit { @@ -273,6 +320,26 @@ impl PaymentAttemptNew { } } +#[cfg(feature = "v2")] +impl PaymentAttemptNew { + /// returns amount + surcharge_amount + tax_amount + pub fn calculate_net_amount(&self) -> MinorUnit { + todo!(); + } + + pub fn get_or_calculate_net_amount(&self) -> MinorUnit { + self.net_amount + .unwrap_or_else(|| self.calculate_net_amount()) + } + + pub fn populate_derived_fields(self) -> Self { + let mut payment_attempt_new = self; + payment_attempt_new.net_amount = Some(payment_attempt_new.calculate_net_amount()); + payment_attempt_new + } +} + +#[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentAttemptUpdate { Update { @@ -464,6 +531,239 @@ pub enum PaymentAttemptUpdate { }, } +#[cfg(feature = "v2")] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum PaymentAttemptUpdate { + // Update { + // amount: MinorUnit, + // currency: storage_enums::Currency, + // status: storage_enums::AttemptStatus, + // authentication_type: Option<storage_enums::AuthenticationType>, + // payment_method: Option<storage_enums::PaymentMethod>, + // payment_token: Option<String>, + // payment_method_data: Option<serde_json::Value>, + // payment_method_type: Option<storage_enums::PaymentMethodType>, + // payment_experience: Option<storage_enums::PaymentExperience>, + // business_sub_label: Option<String>, + // amount_to_capture: Option<MinorUnit>, + // capture_method: Option<storage_enums::CaptureMethod>, + // surcharge_amount: Option<MinorUnit>, + // tax_amount: Option<MinorUnit>, + // fingerprint_id: Option<String>, + // payment_method_billing_address_id: Option<String>, + // updated_by: String, + // }, + // UpdateTrackers { + // payment_token: Option<String>, + // connector: Option<String>, + // straight_through_algorithm: Option<serde_json::Value>, + // amount_capturable: Option<MinorUnit>, + // surcharge_amount: Option<MinorUnit>, + // tax_amount: Option<MinorUnit>, + // updated_by: String, + // merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + // }, + // AuthenticationTypeUpdate { + // authentication_type: storage_enums::AuthenticationType, + // updated_by: String, + // }, + // ConfirmUpdate { + // amount: MinorUnit, + // currency: storage_enums::Currency, + // status: storage_enums::AttemptStatus, + // authentication_type: Option<storage_enums::AuthenticationType>, + // capture_method: Option<storage_enums::CaptureMethod>, + // payment_method: Option<storage_enums::PaymentMethod>, + // browser_info: Option<serde_json::Value>, + // connector: Option<String>, + // payment_token: Option<String>, + // payment_method_data: Option<serde_json::Value>, + // payment_method_type: Option<storage_enums::PaymentMethodType>, + // payment_experience: Option<storage_enums::PaymentExperience>, + // business_sub_label: Option<String>, + // straight_through_algorithm: Option<serde_json::Value>, + // error_code: Option<Option<String>>, + // error_message: Option<Option<String>>, + // amount_capturable: Option<MinorUnit>, + // surcharge_amount: Option<MinorUnit>, + // tax_amount: Option<MinorUnit>, + // fingerprint_id: Option<String>, + // updated_by: String, + // merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + // payment_method_id: Option<String>, + // external_three_ds_authentication_attempted: Option<bool>, + // authentication_connector: Option<String>, + // authentication_id: Option<String>, + // payment_method_billing_address_id: Option<String>, + // client_source: Option<String>, + // client_version: Option<String>, + // customer_acceptance: Option<pii::SecretSerdeValue>, + // }, + // VoidUpdate { + // status: storage_enums::AttemptStatus, + // cancellation_reason: Option<String>, + // updated_by: String, + // }, + // PaymentMethodDetailsUpdate { + // payment_method_id: Option<String>, + // updated_by: String, + // }, + // BlocklistUpdate { + // status: storage_enums::AttemptStatus, + // error_code: Option<Option<String>>, + // error_message: Option<Option<String>>, + // updated_by: String, + // }, + // RejectUpdate { + // status: storage_enums::AttemptStatus, + // error_code: Option<Option<String>>, + // error_message: Option<Option<String>>, + // updated_by: String, + // }, + // ResponseUpdate { + // status: storage_enums::AttemptStatus, + // connector: Option<String>, + // connector_transaction_id: Option<String>, + // authentication_type: Option<storage_enums::AuthenticationType>, + // payment_method_id: Option<String>, + // mandate_id: Option<String>, + // connector_metadata: Option<serde_json::Value>, + // payment_token: Option<String>, + // error_code: Option<Option<String>>, + // error_message: Option<Option<String>>, + // error_reason: Option<Option<String>>, + // connector_response_reference_id: Option<String>, + // amount_capturable: Option<MinorUnit>, + // updated_by: String, + // authentication_data: Option<serde_json::Value>, + // encoded_data: Option<String>, + // unified_code: Option<Option<String>>, + // unified_message: Option<Option<String>>, + // payment_method_data: Option<serde_json::Value>, + // charge_id: Option<String>, + // }, + // UnresolvedResponseUpdate { + // status: storage_enums::AttemptStatus, + // connector: Option<String>, + // connector_transaction_id: Option<String>, + // payment_method_id: Option<String>, + // error_code: Option<Option<String>>, + // error_message: Option<Option<String>>, + // error_reason: Option<Option<String>>, + // connector_response_reference_id: Option<String>, + // updated_by: String, + // }, + // StatusUpdate { + // status: storage_enums::AttemptStatus, + // updated_by: String, + // }, + // ErrorUpdate { + // connector: Option<String>, + // status: storage_enums::AttemptStatus, + // error_code: Option<Option<String>>, + // error_message: Option<Option<String>>, + // error_reason: Option<Option<String>>, + // amount_capturable: Option<MinorUnit>, + // updated_by: String, + // unified_code: Option<Option<String>>, + // unified_message: Option<Option<String>>, + // connector_transaction_id: Option<String>, + // payment_method_data: Option<serde_json::Value>, + // authentication_type: Option<storage_enums::AuthenticationType>, + // }, + // CaptureUpdate { + // amount_to_capture: Option<MinorUnit>, + // multiple_capture_count: Option<MinorUnit>, + // updated_by: String, + // }, + // AmountToCaptureUpdate { + // status: storage_enums::AttemptStatus, + // amount_capturable: MinorUnit, + // updated_by: String, + // }, + // PreprocessingUpdate { + // status: storage_enums::AttemptStatus, + // payment_method_id: Option<String>, + // connector_metadata: Option<serde_json::Value>, + // preprocessing_step_id: Option<String>, + // connector_transaction_id: Option<String>, + // connector_response_reference_id: Option<String>, + // updated_by: String, + // }, + // ConnectorResponse { + // authentication_data: Option<serde_json::Value>, + // encoded_data: Option<String>, + // connector_transaction_id: Option<String>, + // connector: Option<String>, + // charge_id: Option<String>, + // updated_by: String, + // }, + // IncrementalAuthorizationAmountUpdate { + // amount: MinorUnit, + // amount_capturable: MinorUnit, + // }, + // AuthenticationUpdate { + // status: storage_enums::AttemptStatus, + // external_three_ds_authentication_attempted: Option<bool>, + // authentication_connector: Option<String>, + // authentication_id: Option<String>, + // updated_by: String, + // }, + // ManualUpdate { + // status: Option<storage_enums::AttemptStatus>, + // error_code: Option<String>, + // error_message: Option<String>, + // error_reason: Option<String>, + // updated_by: String, + // unified_code: Option<String>, + // unified_message: Option<String>, + // connector_transaction_id: Option<String>, + // }, +} + +#[cfg(feature = "v2")] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = payment_attempt)] +pub struct PaymentAttemptUpdateInternal { + net_amount: Option<i64>, + status: Option<storage_enums::AttemptStatus>, + authentication_type: Option<storage_enums::AuthenticationType>, + error_message: Option<Option<String>>, + payment_method_id: Option<String>, + cancellation_reason: Option<String>, + modified_at: PrimitiveDateTime, + browser_info: Option<serde_json::Value>, + payment_token: Option<String>, + error_code: Option<Option<String>>, + connector_metadata: Option<serde_json::Value>, + payment_method_data: Option<serde_json::Value>, + payment_experience: Option<storage_enums::PaymentExperience>, + preprocessing_step_id: Option<String>, + error_reason: Option<Option<String>>, + connector_response_reference_id: Option<String>, + multiple_capture_count: Option<i16>, + surcharge_amount: Option<i64>, + tax_on_surcharge: Option<i64>, + amount_capturable: Option<i64>, + updated_by: String, + merchant_connector_id: Option<Option<id_type::MerchantConnectorAccountId>>, + authentication_data: Option<serde_json::Value>, + encoded_data: Option<String>, + unified_code: Option<Option<String>>, + unified_message: Option<Option<String>>, + external_three_ds_authentication_attempted: Option<bool>, + authentication_connector: Option<String>, + authentication_id: Option<String>, + fingerprint_id: Option<String>, + payment_method_billing_address_id: Option<String>, + charge_id: Option<String>, + client_source: Option<String>, + client_version: Option<String>, + customer_acceptance: Option<pii::SecretSerdeValue>, + card_network: Option<String>, +} + +#[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptUpdateInternal { @@ -518,6 +818,14 @@ pub struct PaymentAttemptUpdateInternal { pub order_tax_amount: Option<MinorUnit>, } +#[cfg(feature = "v2")] +impl PaymentAttemptUpdateInternal { + pub fn populate_derived_fields(self, source: &PaymentAttempt) -> Self { + todo!(); + } +} + +#[cfg(feature = "v1")] impl PaymentAttemptUpdateInternal { pub fn populate_derived_fields(self, source: &PaymentAttempt) -> Self { let mut update_internal = self; @@ -553,6 +861,97 @@ impl PaymentAttemptUpdateInternal { } } +#[cfg(feature = "v2")] +impl PaymentAttemptUpdate { + pub fn apply_changeset(self, source: PaymentAttempt) -> PaymentAttempt { + todo!() + // let PaymentAttemptUpdateInternal { + // net_amount, + // status, + // authentication_type, + // error_message, + // payment_method_id, + // cancellation_reason, + // modified_at: _, + // browser_info, + // payment_token, + // error_code, + // connector_metadata, + // payment_method_data, + // payment_experience, + // straight_through_algorithm, + // preprocessing_step_id, + // error_reason, + // connector_response_reference_id, + // multiple_capture_count, + // surcharge_amount, + // tax_amount, + // amount_capturable, + // updated_by, + // merchant_connector_id, + // authentication_data, + // encoded_data, + // unified_code, + // unified_message, + // external_three_ds_authentication_attempted, + // authentication_connector, + // authentication_id, + // payment_method_billing_address_id, + // fingerprint_id, + // charge_id, + // client_source, + // client_version, + // customer_acceptance, + // card_network, + // } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); + // PaymentAttempt { + // net_amount: net_amount.or(source.net_amount), + // status: status.unwrap_or(source.status), + // authentication_type: authentication_type.or(source.authentication_type), + // error_message: error_message.unwrap_or(source.error_message), + // payment_method_id: payment_method_id.or(source.payment_method_id), + // cancellation_reason: cancellation_reason.or(source.cancellation_reason), + // modified_at: common_utils::date_time::now(), + // browser_info: browser_info.or(source.browser_info), + // payment_token: payment_token.or(source.payment_token), + // error_code: error_code.unwrap_or(source.error_code), + // connector_metadata: connector_metadata.or(source.connector_metadata), + // payment_method_data: payment_method_data.or(source.payment_method_data), + // payment_experience: payment_experience.or(source.payment_experience), + // straight_through_algorithm: straight_through_algorithm + // .or(source.straight_through_algorithm), + // preprocessing_step_id: preprocessing_step_id.or(source.preprocessing_step_id), + // error_reason: error_reason.unwrap_or(source.error_reason), + // connector_response_reference_id: connector_response_reference_id + // .or(source.connector_response_reference_id), + // multiple_capture_count: multiple_capture_count.or(source.multiple_capture_count), + // surcharge_amount: surcharge_amount.or(source.surcharge_amount), + // tax_amount: tax_amount.or(source.tax_amount), + // amount_capturable: amount_capturable.unwrap_or(source.amount_capturable), + // updated_by, + // merchant_connector_id: merchant_connector_id.unwrap_or(source.merchant_connector_id), + // authentication_data: authentication_data.or(source.authentication_data), + // encoded_data: encoded_data.or(source.encoded_data), + // unified_code: unified_code.unwrap_or(source.unified_code), + // unified_message: unified_message.unwrap_or(source.unified_message), + // external_three_ds_authentication_attempted: external_three_ds_authentication_attempted + // .or(source.external_three_ds_authentication_attempted), + // authentication_connector: authentication_connector.or(source.authentication_connector), + // authentication_id: authentication_id.or(source.authentication_id), + // payment_method_billing_address_id: payment_method_billing_address_id + // .or(source.payment_method_billing_address_id), + // fingerprint_id: fingerprint_id.or(source.fingerprint_id), + // charge_id: charge_id.or(source.charge_id), + // client_source: client_source.or(source.client_source), + // client_version: client_version.or(source.client_version), + // customer_acceptance: customer_acceptance.or(source.customer_acceptance), + // card_network: card_network.or(source.card_network), + // ..source + // } + } +} + +#[cfg(feature = "v1")] impl PaymentAttemptUpdate { pub fn apply_changeset(self, source: PaymentAttempt) -> PaymentAttempt { let PaymentAttemptUpdateInternal { @@ -665,6 +1064,922 @@ impl PaymentAttemptUpdate { } } +#[cfg(feature = "v2")] +impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { + fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { + todo!() + // match payment_attempt_update { + // PaymentAttemptUpdate::Update { + // amount, + // currency, + // status, + // // connector_transaction_id, + // authentication_type, + // payment_method, + // payment_token, + // payment_method_data, + // payment_method_type, + // payment_experience, + // business_sub_label, + // amount_to_capture, + // capture_method, + // surcharge_amount, + // tax_amount, + // fingerprint_id, + // updated_by, + // payment_method_billing_address_id, + // } => Self { + // status: Some(status), + // // connector_transaction_id, + // authentication_type, + // payment_token, + // modified_at: common_utils::date_time::now(), + // payment_method_data, + // payment_experience, + // surcharge_amount, + // tax_amount, + // fingerprint_id, + // payment_method_billing_address_id, + // updated_by, + // net_amount: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // error_code: None, + // connector_metadata: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::AuthenticationTypeUpdate { + // authentication_type, + // updated_by, + // } => Self { + // authentication_type: Some(authentication_type), + // modified_at: common_utils::date_time::now(), + // updated_by, + // net_amount: None, + // status: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::ConfirmUpdate { + // amount, + // currency, + // authentication_type, + // capture_method, + // status, + // payment_method, + // browser_info, + // connector, + // payment_token, + // payment_method_data, + // payment_method_type, + // payment_experience, + // business_sub_label, + // straight_through_algorithm, + // error_code, + // error_message, + // amount_capturable, + // updated_by, + // merchant_connector_id, + // surcharge_amount, + // tax_amount, + // external_three_ds_authentication_attempted, + // authentication_connector, + // authentication_id, + // payment_method_billing_address_id, + // fingerprint_id, + // payment_method_id, + // client_source, + // client_version, + // customer_acceptance, + // } => Self { + // authentication_type, + // status: Some(status), + // modified_at: common_utils::date_time::now(), + // browser_info, + // payment_token, + // payment_method_data, + // payment_experience, + // straight_through_algorithm, + // error_code, + // error_message, + // amount_capturable, + // updated_by, + // merchant_connector_id: merchant_connector_id.map(Some), + // surcharge_amount, + // tax_amount, + // external_three_ds_authentication_attempted, + // authentication_connector, + // authentication_id, + // payment_method_billing_address_id, + // fingerprint_id, + // payment_method_id, + // client_source, + // client_version, + // customer_acceptance, + // net_amount: None, + // cancellation_reason: None, + // connector_metadata: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // charge_id: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::VoidUpdate { + // status, + // cancellation_reason, + // updated_by, + // } => Self { + // status: Some(status), + // cancellation_reason, + // modified_at: common_utils::date_time::now(), + // updated_by, + // net_amount: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::RejectUpdate { + // status, + // error_code, + // error_message, + // updated_by, + // } => Self { + // status: Some(status), + // modified_at: common_utils::date_time::now(), + // error_code, + // error_message, + // updated_by, + // net_amount: None, + // authentication_type: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::BlocklistUpdate { + // status, + // error_code, + // error_message, + // updated_by, + // } => Self { + // status: Some(status), + // modified_at: common_utils::date_time::now(), + // error_code, + // error_message, + // updated_by, + // merchant_connector_id: Some(None), + // net_amount: None, + // authentication_type: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::PaymentMethodDetailsUpdate { + // payment_method_id, + // updated_by, + // } => Self { + // payment_method_id, + // modified_at: common_utils::date_time::now(), + // updated_by, + // net_amount: None, + // status: None, + // authentication_type: None, + // error_message: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::ResponseUpdate { + // status, + // connector, + // connector_transaction_id, + // authentication_type, + // payment_method_id, + // mandate_id, + // connector_metadata, + // payment_token, + // error_code, + // error_message, + // error_reason, + // connector_response_reference_id, + // amount_capturable, + // updated_by, + // authentication_data, + // encoded_data, + // unified_code, + // unified_message, + // payment_method_data, + // charge_id, + // } => Self { + // status: Some(status), + // authentication_type, + // payment_method_id, + // modified_at: common_utils::date_time::now(), + // connector_metadata, + // error_code, + // error_message, + // payment_token, + // error_reason, + // connector_response_reference_id, + // amount_capturable, + // updated_by, + // authentication_data, + // encoded_data, + // unified_code, + // unified_message, + // payment_method_data, + // charge_id, + // net_amount: None, + // cancellation_reason: None, + // browser_info: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // merchant_connector_id: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::ErrorUpdate { + // connector, + // status, + // error_code, + // error_message, + // error_reason, + // amount_capturable, + // updated_by, + // unified_code, + // unified_message, + // connector_transaction_id, + // payment_method_data, + // authentication_type, + // } => Self { + // status: Some(status), + // error_message, + // error_code, + // modified_at: common_utils::date_time::now(), + // error_reason, + // amount_capturable, + // updated_by, + // unified_code, + // unified_message, + // payment_method_data, + // authentication_type, + // net_amount: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // connector_metadata: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { + // status: Some(status), + // modified_at: common_utils::date_time::now(), + // updated_by, + // net_amount: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::UpdateTrackers { + // payment_token, + // connector, + // straight_through_algorithm, + // amount_capturable, + // surcharge_amount, + // tax_amount, + // updated_by, + // merchant_connector_id, + // } => Self { + // payment_token, + // modified_at: common_utils::date_time::now(), + // straight_through_algorithm, + // amount_capturable, + // surcharge_amount, + // tax_amount, + // updated_by, + // merchant_connector_id: merchant_connector_id.map(Some), + // net_amount: None, + // status: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::UnresolvedResponseUpdate { + // status, + // connector, + // connector_transaction_id, + // payment_method_id, + // error_code, + // error_message, + // error_reason, + // connector_response_reference_id, + // updated_by, + // } => Self { + // status: Some(status), + // payment_method_id, + // modified_at: common_utils::date_time::now(), + // error_code, + // error_message, + // error_reason, + // connector_response_reference_id, + // updated_by, + // net_amount: None, + // authentication_type: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::PreprocessingUpdate { + // status, + // payment_method_id, + // connector_metadata, + // preprocessing_step_id, + // connector_transaction_id, + // connector_response_reference_id, + // updated_by, + // } => Self { + // status: Some(status), + // payment_method_id, + // modified_at: common_utils::date_time::now(), + // connector_metadata, + // preprocessing_step_id, + // connector_response_reference_id, + // updated_by, + // net_amount: None, + // authentication_type: None, + // error_message: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // error_reason: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::CaptureUpdate { + // multiple_capture_count, + // updated_by, + // amount_to_capture, + // } => Self { + // multiple_capture_count, + // modified_at: common_utils::date_time::now(), + // updated_by, + // net_amount: None, + // status: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::AmountToCaptureUpdate { + // status, + // amount_capturable, + // updated_by, + // } => Self { + // status: Some(status), + // modified_at: common_utils::date_time::now(), + // amount_capturable: Some(amount_capturable), + // updated_by, + // net_amount: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::ConnectorResponse { + // authentication_data, + // encoded_data, + // connector_transaction_id, + // connector, + // updated_by, + // charge_id, + // } => Self { + // authentication_data, + // encoded_data, + // modified_at: common_utils::date_time::now(), + // updated_by, + // charge_id, + // net_amount: None, + // status: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { + // amount, + // amount_capturable, + // } => Self { + // modified_at: common_utils::date_time::now(), + // amount_capturable: Some(amount_capturable), + // net_amount: None, + // status: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // updated_by: String::default(), + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::AuthenticationUpdate { + // status, + // external_three_ds_authentication_attempted, + // authentication_connector, + // authentication_id, + // updated_by, + // } => Self { + // status: Some(status), + // modified_at: common_utils::date_time::now(), + // external_three_ds_authentication_attempted, + // authentication_connector, + // authentication_id, + // updated_by, + // net_amount: None, + // authentication_type: None, + // error_message: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // error_code: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // error_reason: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // unified_code: None, + // unified_message: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // PaymentAttemptUpdate::ManualUpdate { + // status, + // error_code, + // error_message, + // error_reason, + // updated_by, + // unified_code, + // unified_message, + // connector_transaction_id, + // } => Self { + // status, + // error_code: error_code.map(Some), + // modified_at: common_utils::date_time::now(), + // error_message: error_message.map(Some), + // error_reason: error_reason.map(Some), + // updated_by, + // unified_code: unified_code.map(Some), + // unified_message: unified_message.map(Some), + // net_amount: None, + // authentication_type: None, + // payment_method_id: None, + // cancellation_reason: None, + // browser_info: None, + // payment_token: None, + // connector_metadata: None, + // payment_method_data: None, + // payment_experience: None, + // straight_through_algorithm: None, + // preprocessing_step_id: None, + // connector_response_reference_id: None, + // multiple_capture_count: None, + // surcharge_amount: None, + // tax_amount: None, + // amount_capturable: None, + // merchant_connector_id: None, + // authentication_data: None, + // encoded_data: None, + // external_three_ds_authentication_attempted: None, + // authentication_connector: None, + // authentication_id: None, + // fingerprint_id: None, + // payment_method_billing_address_id: None, + // charge_id: None, + // client_source: None, + // client_version: None, + // customer_acceptance: None, + // card_network: None, + // }, + // } + } +} + +#[cfg(feature = "v1")] impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { match payment_attempt_update { diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index c6ebbe671e9..23d1a0f1ac8 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -5,12 +5,12 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::enums as storage_enums; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] use crate::schema::payment_intent; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::schema_v2::payment_intent; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { @@ -72,7 +72,7 @@ pub struct PaymentIntent { pub id: common_utils::id_type::GlobalPaymentId, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { @@ -205,7 +205,7 @@ pub struct DefaultTax { pub order_tax_amount: MinorUnit, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] @@ -265,7 +265,7 @@ pub struct PaymentIntentNew { pub id: common_utils::id_type::GlobalPaymentId, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] @@ -330,7 +330,7 @@ pub struct PaymentIntentNew { pub skip_external_tax_calculation: Option<bool>, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { ResponseUpdate { @@ -409,7 +409,7 @@ pub enum PaymentIntentUpdate { }, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { ResponseUpdate { @@ -491,7 +491,7 @@ pub enum PaymentIntentUpdate { }, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, @@ -516,7 +516,7 @@ pub struct PaymentIntentUpdateFields { pub is_payment_processor_token_flow: Option<bool>, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, @@ -548,7 +548,7 @@ pub struct PaymentIntentUpdateFields { pub tax_details: Option<TaxDetails>, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { @@ -579,7 +579,7 @@ pub struct PaymentIntentUpdateInternal { pub frm_merchant_decision: Option<String>, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { @@ -622,7 +622,7 @@ pub struct PaymentIntentUpdateInternal { pub tax_details: Option<TaxDetails>, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { todo!() @@ -693,7 +693,7 @@ impl PaymentIntentUpdate { } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let PaymentIntentUpdateInternal { @@ -783,7 +783,7 @@ impl PaymentIntentUpdate { } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { todo!() @@ -1292,7 +1292,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index 48941330ec6..e07d716fb6c 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -8,9 +8,9 @@ use diesel::{ use error_stack::{report, ResultExt}; use super::generics; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] use crate::schema::payment_attempt::dsl; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::schema_v2::payment_attempt::dsl; use crate::{ enums::{self, IntentStatus}, @@ -29,7 +29,7 @@ impl PaymentAttemptNew { } impl PaymentAttempt { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, @@ -57,7 +57,7 @@ impl PaymentAttempt { } } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, @@ -70,9 +70,7 @@ impl PaymentAttempt { _, >( conn, - dsl::attempt_id - .eq(self.attempt_id.to_owned()) - .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), + dsl::id.eq(self.id.to_owned()), payment_attempt.populate_derived_fields(&self), ) .await @@ -85,6 +83,7 @@ impl PaymentAttempt { } } + #[cfg(feature = "v1")] pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, @@ -99,6 +98,7 @@ impl PaymentAttempt { .await } + #[cfg(feature = "v1")] pub async fn find_by_connector_transaction_id_payment_id_merchant_id( conn: &PgPooledConn, connector_transaction_id: &str, @@ -115,6 +115,7 @@ impl PaymentAttempt { .await } + #[cfg(feature = "v1")] pub async fn find_last_successful_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, @@ -137,6 +138,7 @@ impl PaymentAttempt { .ok_or(report!(DatabaseError::NotFound)) } + #[cfg(feature = "v1")] pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, @@ -163,6 +165,7 @@ impl PaymentAttempt { .ok_or(report!(DatabaseError::NotFound)) } + #[cfg(feature = "v1")] pub async fn find_by_merchant_id_connector_txn_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -177,6 +180,7 @@ impl PaymentAttempt { .await } + #[cfg(feature = "v1")] pub async fn find_by_merchant_id_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -191,6 +195,16 @@ impl PaymentAttempt { .await } + #[cfg(feature = "v2")] + pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::id.eq(id.to_owned()), + ) + .await + } + + #[cfg(feature = "v1")] pub async fn find_by_merchant_id_preprocessing_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -205,6 +219,7 @@ impl PaymentAttempt { .await } + #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, @@ -222,6 +237,7 @@ impl PaymentAttempt { .await } + #[cfg(feature = "v1")] pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -244,6 +260,7 @@ impl PaymentAttempt { .await } + #[cfg(feature = "v1")] pub async fn get_filters_for_payments( conn: &PgPooledConn, pi: &[PaymentIntent], @@ -342,6 +359,7 @@ impl PaymentAttempt { )) } + #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_total_count_of_attempts( conn: &PgPooledConn, diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rs index e148c76686e..fb23fc60107 100644 --- a/crates/diesel_models/src/query/payment_intent.rs +++ b/crates/diesel_models/src/query/payment_intent.rs @@ -1,9 +1,9 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] use crate::schema::payment_intent::dsl; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::schema_v2::payment_intent::dsl; use crate::{ errors, @@ -20,7 +20,7 @@ impl PaymentIntentNew { } impl PaymentIntent { - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] pub async fn update( self, conn: &PgPooledConn, @@ -41,7 +41,7 @@ impl PaymentIntent { } } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] pub async fn find_by_global_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalPaymentId, @@ -49,7 +49,7 @@ impl PaymentIntent { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] pub async fn update( self, conn: &PgPooledConn, @@ -74,7 +74,7 @@ impl PaymentIntent { } } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, @@ -89,7 +89,7 @@ impl PaymentIntent { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, @@ -104,7 +104,7 @@ impl PaymentIntent { .await } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] pub async fn find_optional_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &str, @@ -119,7 +119,7 @@ impl PaymentIntent { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs index 3890ee2cd05..b5400f570a3 100644 --- a/crates/diesel_models/src/query/user/sample_data.rs +++ b/crates/diesel_models/src/query/user/sample_data.rs @@ -3,11 +3,11 @@ use diesel::{associations::HasTable, debug_query, ExpressionMethods, TextExpress use error_stack::ResultExt; use router_env::logger; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] use crate::schema::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, }; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::schema_v2::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, }; @@ -61,7 +61,7 @@ pub async fn insert_refunds( .attach_printable("Error while inserting refunds") } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] pub async fn delete_payment_intents( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, @@ -88,7 +88,7 @@ pub async fn delete_payment_intents( }) } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] pub async fn delete_payment_intents( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 4c44bb18b75..1c81b402f77 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -733,30 +733,18 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - payment_attempt (attempt_id, merchant_id) { + payment_attempt (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, - #[max_length = 64] - attempt_id -> Varchar, status -> AttemptStatus, - amount -> Int8, - currency -> Nullable<Currency>, - save_to_locker -> Nullable<Bool>, #[max_length = 64] connector -> Nullable<Varchar>, error_message -> Nullable<Text>, - offer_amount -> Nullable<Int8>, surcharge_amount -> Nullable<Int8>, - tax_amount -> Nullable<Int8>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, - payment_method -> Nullable<Varchar>, - #[max_length = 128] - connector_transaction_id -> Nullable<Varchar>, - capture_method -> Nullable<CaptureMethod>, - capture_on -> Nullable<Timestamp>, confirm -> Bool, authentication_type -> Nullable<AuthenticationType>, created_at -> Timestamp, @@ -765,8 +753,6 @@ diesel::table! { #[max_length = 255] cancellation_reason -> Nullable<Varchar>, amount_to_capture -> Nullable<Int8>, - #[max_length = 64] - mandate_id -> Nullable<Varchar>, browser_info -> Nullable<Jsonb>, #[max_length = 255] error_code -> Nullable<Varchar>, @@ -775,14 +761,8 @@ diesel::table! { connector_metadata -> Nullable<Jsonb>, #[max_length = 50] payment_experience -> Nullable<Varchar>, - #[max_length = 64] - payment_method_type -> Nullable<Varchar>, payment_method_data -> Nullable<Jsonb>, - #[max_length = 64] - business_sub_label -> Nullable<Varchar>, - straight_through_algorithm -> Nullable<Jsonb>, preprocessing_step_id -> Nullable<Varchar>, - mandate_details -> Nullable<Jsonb>, error_reason -> Nullable<Text>, multiple_capture_count -> Nullable<Int2>, #[max_length = 128] @@ -804,7 +784,6 @@ diesel::table! { authentication_connector -> Nullable<Varchar>, #[max_length = 64] authentication_id -> Nullable<Varchar>, - mandate_data -> Nullable<Jsonb>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, #[max_length = 64] @@ -822,6 +801,18 @@ diesel::table! { organization_id -> Varchar, #[max_length = 32] card_network -> Nullable<Varchar>, + payment_method_type_v2 -> Nullable<Varchar>, + #[max_length = 128] + connector_payment_id -> Nullable<Varchar>, + #[max_length = 64] + payment_method_subtype -> Nullable<Varchar>, + routing_result -> Nullable<Jsonb>, + authentication_applied -> Nullable<AuthenticationType>, + #[max_length = 128] + external_reference_id -> Nullable<Varchar>, + tax_on_surcharge -> Nullable<Int8>, + #[max_length = 64] + id -> Varchar, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index ddcf6352c52..a354e4a02ab 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -6,15 +6,133 @@ use common_utils::types::MinorUnit; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] use crate::schema::payment_attempt; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::schema_v2::payment_attempt; use crate::{ enums::{MandateDataType, MandateDetails}, PaymentAttemptNew, }; +#[cfg(feature = "v2")] +#[derive( + Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, +)] +#[diesel(table_name = payment_attempt)] +pub struct PaymentAttemptBatchNew { + pub payment_id: common_utils::id_type::PaymentId, + pub merchant_id: common_utils::id_type::MerchantId, + pub status: AttemptStatus, + pub error_message: Option<String>, + pub surcharge_amount: Option<i64>, + pub tax_on_surcharge: Option<i64>, + pub payment_method_id: Option<String>, + pub confirm: bool, + pub authentication_type: Option<AuthenticationType>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub last_synced: Option<PrimitiveDateTime>, + pub cancellation_reason: Option<String>, + pub browser_info: Option<serde_json::Value>, + pub payment_token: Option<String>, + pub error_code: Option<String>, + pub connector_metadata: Option<serde_json::Value>, + pub payment_experience: Option<PaymentExperience>, + pub payment_method_data: Option<serde_json::Value>, + pub preprocessing_step_id: Option<String>, + pub error_reason: Option<String>, + pub connector_response_reference_id: Option<String>, + pub multiple_capture_count: Option<i16>, + pub amount_capturable: i64, + pub updated_by: String, + pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub authentication_data: Option<serde_json::Value>, + pub encoded_data: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub net_amount: Option<i64>, + pub external_three_ds_authentication_attempted: Option<bool>, + pub authentication_connector: Option<String>, + pub authentication_id: Option<String>, + pub payment_method_billing_address_id: Option<String>, + pub fingerprint_id: Option<String>, + pub charge_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, + pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, + pub profile_id: common_utils::id_type::ProfileId, + pub organization_id: common_utils::id_type::OrganizationId, +} + +#[cfg(feature = "v2")] +#[allow(dead_code)] +impl PaymentAttemptBatchNew { + // Used to verify compatibility with PaymentAttemptTable + fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew { + // PaymentAttemptNew { + // payment_id: self.payment_id, + // merchant_id: self.merchant_id, + // status: self.status, + // error_message: self.error_message, + // surcharge_amount: self.surcharge_amount, + // tax_amount: self.tax_amount, + // payment_method_id: self.payment_method_id, + // confirm: self.confirm, + // authentication_type: self.authentication_type, + // created_at: self.created_at, + // modified_at: self.modified_at, + // last_synced: self.last_synced, + // cancellation_reason: self.cancellation_reason, + // browser_info: self.browser_info, + // payment_token: self.payment_token, + // error_code: self.error_code, + // connector_metadata: self.connector_metadata, + // payment_experience: self.payment_experience, + // card_network: self + // .payment_method_data + // .as_ref() + // .and_then(|data| data.as_object()) + // .and_then(|card| card.get("card")) + // .and_then(|v| v.as_object()) + // .and_then(|v| v.get("card_network")) + // .and_then(|network| network.as_str()) + // .map(|network| network.to_string()), + // payment_method_data: self.payment_method_data, + // straight_through_algorithm: self.straight_through_algorithm, + // preprocessing_step_id: self.preprocessing_step_id, + // error_reason: self.error_reason, + // multiple_capture_count: self.multiple_capture_count, + // connector_response_reference_id: self.connector_response_reference_id, + // amount_capturable: self.amount_capturable, + // updated_by: self.updated_by, + // merchant_connector_id: self.merchant_connector_id, + // authentication_data: self.authentication_data, + // encoded_data: self.encoded_data, + // unified_code: self.unified_code, + // unified_message: self.unified_message, + // net_amount: self.net_amount, + // external_three_ds_authentication_attempted: self + // .external_three_ds_authentication_attempted, + // authentication_connector: self.authentication_connector, + // authentication_id: self.authentication_id, + // payment_method_billing_address_id: self.payment_method_billing_address_id, + // fingerprint_id: self.fingerprint_id, + // charge_id: self.charge_id, + // client_source: self.client_source, + // client_version: self.client_version, + // customer_acceptance: self.customer_acceptance, + // profile_id: self.profile_id, + // organization_id: self.organization_id, + // } + todo!() + } +} + +#[cfg(feature = "v1")] #[derive( Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] @@ -87,6 +205,7 @@ pub struct PaymentAttemptBatchNew { pub order_tax_amount: Option<MinorUnit>, } +#[cfg(feature = "v1")] #[allow(dead_code)] impl PaymentAttemptBatchNew { // Used to verify compatibility with PaymentAttemptTable diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index e2ae011c828..3a0d4b402b7 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -16,7 +16,6 @@ frm = ["api_models/frm"] v2 = ["api_models/v2", "diesel_models/v2"] v1 = ["api_models/v1", "diesel_models/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"] -payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2"] [dependencies] diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index f25ce7cad20..2d7d49e81c7 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -14,7 +14,7 @@ use common_enums as storage_enums; use self::payment_attempt::PaymentAttempt; use crate::RemoteStorageObject; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct PaymentIntent { pub payment_id: id_type::PaymentId, @@ -79,12 +79,12 @@ pub struct PaymentIntent { } impl PaymentIntent { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2"),))] + #[cfg(feature = "v1")] pub fn get_id(&self) -> &id_type::PaymentId { &self.payment_id } - #[cfg(all(feature = "v2", feature = "payment_v2",))] + #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalPaymentId { &self.id } @@ -168,7 +168,7 @@ impl AmountDetails { } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct PaymentIntent { /// The global identifier for the payment intent. This is generated by the system. diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 003509b2039..5f0894566ad 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1,3 +1,4 @@ +#[cfg(all(feature = "v1", feature = "olap"))] use api_models::enums::Connector; use common_enums as storage_enums; use common_utils::{ @@ -16,8 +17,9 @@ use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; +#[cfg(all(feature = "v1", feature = "olap"))] use super::PaymentIntent; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use crate::merchant_key_store::MerchantKeyStore; use crate::{ behaviour, errors, @@ -27,14 +29,14 @@ use crate::{ #[async_trait::async_trait] pub trait PaymentAttemptInterface { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn insert_payment_attempt( &self, payment_attempt: PaymentAttemptNew, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, @@ -43,7 +45,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn update_payment_attempt_with_attempt_id( &self, this: PaymentAttempt, @@ -51,7 +53,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] async fn update_payment_attempt_with_attempt_id( &self, key_manager_state: &KeyManagerState, @@ -61,7 +63,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, @@ -70,7 +72,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -78,7 +80,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -86,7 +88,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, @@ -94,7 +96,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, @@ -103,7 +105,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, @@ -111,17 +113,16 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(feature = "v2", feature = "payment_v2"))] - async fn find_payment_attempt_by_attempt_id_merchant_id( + #[cfg(feature = "v2")] + async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, attempt_id: &str, - merchant_id: &id_type::MerchantId, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, @@ -129,7 +130,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, @@ -137,7 +138,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filters_for_payments( &self, pi: &[PaymentIntent], @@ -145,7 +146,7 @@ pub trait PaymentAttemptInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentListFilters, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payment_attempts( &self, @@ -162,6 +163,111 @@ pub trait PaymentAttemptInterface { ) -> error_stack::Result<i64, errors::StorageError>; } +#[cfg(feature = "v2")] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct PaymentAttempt { + pub payment_id: id_type::GlobalPaymentId, + pub merchant_id: id_type::MerchantId, + pub status: storage_enums::AttemptStatus, + pub net_amount: MinorUnit, + pub connector: Option<String>, + pub amount_to_capture: Option<MinorUnit>, + pub error_message: Option<String>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_on_surcharge: Option<MinorUnit>, + pub confirm: bool, + pub authentication_type: Option<storage_enums::AuthenticationType>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub modified_at: PrimitiveDateTime, + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub last_synced: Option<PrimitiveDateTime>, + pub cancellation_reason: Option<String>, + pub browser_info: Option<serde_json::Value>, + pub error_code: Option<String>, + pub payment_token: Option<String>, + pub connector_metadata: Option<serde_json::Value>, + pub payment_experience: Option<storage_enums::PaymentExperience>, + pub payment_method_data: Option<serde_json::Value>, + pub routing_result: Option<serde_json::Value>, + pub preprocessing_step_id: Option<String>, + pub error_reason: Option<String>, + pub multiple_capture_count: Option<i16>, + // reference to the payment at connector side + pub connector_response_reference_id: Option<String>, + pub amount_capturable: MinorUnit, + pub updated_by: String, + pub authentication_data: Option<serde_json::Value>, + pub encoded_data: Option<String>, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub external_three_ds_authentication_attempted: Option<bool>, + pub authentication_connector: Option<String>, + pub authentication_id: Option<String>, + pub payment_method_billing_address_id: Option<String>, + pub fingerprint_id: Option<String>, + pub charge_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, + pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub profile_id: id_type::ProfileId, + pub organization_id: id_type::OrganizationId, + pub payment_method_type: Option<storage_enums::PaymentMethod>, + pub payment_method_id: Option<String>, + pub connector_payment_id: Option<String>, + pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, + pub authentication_applied: Option<common_enums::AuthenticationType>, + pub external_reference_id: Option<String>, + pub shipping_cost: Option<MinorUnit>, + pub order_tax_amount: Option<MinorUnit>, + pub id: String, +} + +impl PaymentAttempt { + #[cfg(feature = "v1")] + pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> { + self.payment_method + } + + #[cfg(feature = "v2")] + pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> { + self.payment_method_type + } + + #[cfg(feature = "v1")] + pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { + self.payment_method_type + } + + #[cfg(feature = "v2")] + pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> { + self.payment_method_subtype + } + + #[cfg(feature = "v1")] + pub fn get_id(&self) -> &str { + &self.attempt_id + } + + #[cfg(feature = "v2")] + pub fn get_id(&self) -> &str { + &self.id + } + + #[cfg(feature = "v1")] + pub fn get_connector_payment_id(&self) -> Option<&str> { + self.connector_transaction_id.as_deref() + } + + #[cfg(feature = "v2")] + pub fn get_connector_payment_id(&self) -> Option<&str> { + self.connector_payment_id.as_deref() + } +} + +#[cfg(feature = "v1")] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct PaymentAttempt { pub payment_id: id_type::PaymentId, @@ -233,6 +339,18 @@ pub struct PaymentAttempt { pub order_tax_amount: Option<MinorUnit>, } +#[cfg(feature = "v2")] +impl PaymentAttempt { + pub fn get_total_amount(&self) -> MinorUnit { + todo!(); + } + + pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> { + todo!(); + } +} + +#[cfg(feature = "v1")] impl PaymentAttempt { pub fn get_total_amount(&self) -> MinorUnit { self.amount @@ -256,6 +374,56 @@ pub struct PaymentListFilters { pub authentication_type: Vec<storage_enums::AuthenticationType>, } +#[cfg(feature = "v2")] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PaymentAttemptNew { + pub payment_id: id_type::PaymentId, + pub merchant_id: id_type::MerchantId, + pub status: storage_enums::AttemptStatus, + pub error_message: Option<String>, + pub surcharge_amount: Option<MinorUnit>, + pub tax_amount: Option<MinorUnit>, + pub payment_method_id: Option<String>, + pub confirm: bool, + pub authentication_type: Option<storage_enums::AuthenticationType>, + pub created_at: PrimitiveDateTime, + pub modified_at: PrimitiveDateTime, + pub last_synced: Option<PrimitiveDateTime>, + pub cancellation_reason: Option<String>, + pub browser_info: Option<serde_json::Value>, + pub payment_token: Option<String>, + pub error_code: Option<String>, + pub connector_metadata: Option<serde_json::Value>, + pub payment_experience: Option<storage_enums::PaymentExperience>, + pub payment_method_data: Option<serde_json::Value>, + pub straight_through_algorithm: Option<serde_json::Value>, + pub preprocessing_step_id: Option<String>, + pub error_reason: Option<String>, + pub connector_response_reference_id: Option<String>, + pub multiple_capture_count: Option<i16>, + pub amount_capturable: MinorUnit, + pub updated_by: String, + pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + pub authentication_data: Option<serde_json::Value>, + pub encoded_data: Option<String>, + pub unified_code: Option<String>, + pub unified_message: Option<String>, + pub net_amount: Option<MinorUnit>, + pub external_three_ds_authentication_attempted: Option<bool>, + pub authentication_connector: Option<String>, + pub authentication_id: Option<String>, + pub fingerprint_id: Option<String>, + pub payment_method_billing_address_id: Option<String>, + pub charge_id: Option<String>, + pub client_source: Option<String>, + pub client_version: Option<String>, + pub customer_acceptance: Option<pii::SecretSerdeValue>, + pub profile_id: id_type::ProfileId, + pub organization_id: id_type::OrganizationId, + pub card_network: Option<String>, +} + +#[cfg(feature = "v1")] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PaymentAttemptNew { pub payment_id: id_type::PaymentId, @@ -327,6 +495,19 @@ pub struct PaymentAttemptNew { pub order_tax_amount: Option<MinorUnit>, } +#[cfg(feature = "v2")] +impl PaymentAttemptNew { + /// returns amount + surcharge_amount + tax_amount + pub fn calculate_net_amount(&self) -> MinorUnit { + todo!(); + } + + pub fn populate_derived_fields(self) -> Self { + todo!() + } +} + +#[cfg(feature = "v1")] impl PaymentAttemptNew { /// returns amount + surcharge_amount + tax_amount pub fn calculate_net_amount(&self) -> MinorUnit { @@ -344,6 +525,7 @@ impl PaymentAttemptNew { } } +#[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentAttemptUpdate { Update { @@ -535,1155 +717,26 @@ pub enum PaymentAttemptUpdate { }, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] -impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal { - fn from(payment_attempt_update: PaymentAttemptUpdate) -> Self { - match payment_attempt_update { - PaymentAttemptUpdate::Update { - amount, - currency, - status, - authentication_type, - payment_method, - payment_token, - payment_method_data, - payment_method_type, - payment_experience, - business_sub_label, - amount_to_capture, - capture_method, - surcharge_amount, - tax_amount, - fingerprint_id, - updated_by, - payment_method_billing_address_id, - } => Self { - amount: Some(amount), - currency: Some(currency), - status: Some(status), - authentication_type, - payment_method, - payment_token, - modified_at: common_utils::date_time::now(), - payment_method_data, - payment_method_type, - payment_experience, - business_sub_label, - amount_to_capture, - capture_method, - surcharge_amount, - tax_amount, - fingerprint_id, - payment_method_billing_address_id, - updated_by, - net_amount: None, - connector_transaction_id: None, - connector: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - error_code: None, - connector_metadata: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - connector_response_reference_id: None, - multiple_capture_count: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::AuthenticationTypeUpdate { - authentication_type, - updated_by, - } => Self { - authentication_type: Some(authentication_type), - modified_at: common_utils::date_time::now(), - updated_by, - amount: None, - net_amount: None, - currency: None, - status: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::ConfirmUpdate { - amount, - currency, - authentication_type, - capture_method, - status, - payment_method, - browser_info, - connector, - payment_token, - payment_method_data, - payment_method_type, - payment_experience, - business_sub_label, - straight_through_algorithm, - error_code, - error_message, - amount_capturable, - updated_by, - merchant_connector_id, - surcharge_amount, - tax_amount, - external_three_ds_authentication_attempted, - authentication_connector, - authentication_id, - payment_method_billing_address_id, - fingerprint_id, - payment_method_id, - client_source, - client_version, - customer_acceptance, - shipping_cost, - order_tax_amount, - } => Self { - amount: Some(amount), - currency: Some(currency), - authentication_type, - status: Some(status), - payment_method, - modified_at: common_utils::date_time::now(), - browser_info, - connector: connector.map(Some), - payment_token, - payment_method_data, - payment_method_type, - payment_experience, - business_sub_label, - straight_through_algorithm, - error_code, - error_message, - amount_capturable, - updated_by, - merchant_connector_id: merchant_connector_id.map(Some), - surcharge_amount, - tax_amount, - external_three_ds_authentication_attempted, - authentication_connector, - authentication_id, - payment_method_billing_address_id, - fingerprint_id, - payment_method_id, - capture_method, - client_source, - client_version, - customer_acceptance, - net_amount: None, - connector_transaction_id: None, - amount_to_capture: None, - cancellation_reason: None, - mandate_id: None, - connector_metadata: None, - preprocessing_step_id: None, - error_reason: None, - connector_response_reference_id: None, - multiple_capture_count: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - charge_id: None, - card_network: None, - shipping_cost, - order_tax_amount, - }, - PaymentAttemptUpdate::VoidUpdate { - status, - cancellation_reason, - updated_by, - } => Self { - status: Some(status), - cancellation_reason, - modified_at: common_utils::date_time::now(), - updated_by, - amount: None, - net_amount: None, - currency: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::RejectUpdate { - status, - error_code, - error_message, - updated_by, - } => Self { - status: Some(status), - modified_at: common_utils::date_time::now(), - error_code, - error_message, - updated_by, - amount: None, - net_amount: None, - currency: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::BlocklistUpdate { - status, - error_code, - error_message, - updated_by, - } => Self { - status: Some(status), - modified_at: common_utils::date_time::now(), - error_code, - connector: Some(None), - error_message, - updated_by, - merchant_connector_id: Some(None), - amount: None, - net_amount: None, - currency: None, - connector_transaction_id: None, - amount_to_capture: None, - authentication_type: None, - payment_method: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::PaymentMethodDetailsUpdate { - payment_method_id, - updated_by, - } => Self { - payment_method_id, - modified_at: common_utils::date_time::now(), - updated_by, - amount: None, - net_amount: None, - currency: None, - status: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::ResponseUpdate { - status, - connector, - connector_transaction_id, - authentication_type, - payment_method_id, - mandate_id, - connector_metadata, - payment_token, - error_code, - error_message, - error_reason, - connector_response_reference_id, - amount_capturable, - updated_by, - authentication_data, - encoded_data, - unified_code, - unified_message, - payment_method_data, - charge_id, - } => Self { - status: Some(status), - connector: connector.map(Some), - connector_transaction_id, - authentication_type, - payment_method_id, - modified_at: common_utils::date_time::now(), - mandate_id, - connector_metadata, - error_code, - error_message, - payment_token, - error_reason, - connector_response_reference_id, - amount_capturable, - updated_by, - authentication_data, - encoded_data, - unified_code, - unified_message, - payment_method_data, - charge_id, - amount: None, - net_amount: None, - currency: None, - amount_to_capture: None, - payment_method: None, - cancellation_reason: None, - browser_info: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - capture_method: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - merchant_connector_id: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::ErrorUpdate { - connector, - status, - error_code, - error_message, - error_reason, - amount_capturable, - updated_by, - unified_code, - unified_message, - connector_transaction_id, - payment_method_data, - authentication_type, - } => Self { - connector: connector.map(Some), - status: Some(status), - error_message, - error_code, - modified_at: common_utils::date_time::now(), - error_reason, - amount_capturable, - updated_by, - unified_code, - unified_message, - connector_transaction_id, - payment_method_data, - authentication_type, - amount: None, - net_amount: None, - currency: None, - amount_to_capture: None, - payment_method: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - connector_metadata: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self { - status: Some(status), - modified_at: common_utils::date_time::now(), - updated_by, - amount: None, - net_amount: None, - currency: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::UpdateTrackers { - payment_token, - connector, - straight_through_algorithm, - amount_capturable, - surcharge_amount, - tax_amount, - updated_by, - merchant_connector_id, - } => Self { - payment_token, - modified_at: common_utils::date_time::now(), - connector: connector.map(Some), - straight_through_algorithm, - amount_capturable, - surcharge_amount, - tax_amount, - updated_by, - merchant_connector_id: merchant_connector_id.map(Some), - amount: None, - net_amount: None, - currency: None, - status: None, - connector_transaction_id: None, - amount_to_capture: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::UnresolvedResponseUpdate { - status, - connector, - connector_transaction_id, - payment_method_id, - error_code, - error_message, - error_reason, - connector_response_reference_id, - updated_by, - } => Self { - status: Some(status), - connector: connector.map(Some), - connector_transaction_id, - payment_method_id, - modified_at: common_utils::date_time::now(), - error_code, - error_message, - error_reason, - connector_response_reference_id, - updated_by, - amount: None, - net_amount: None, - currency: None, - amount_to_capture: None, - authentication_type: None, - payment_method: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - capture_method: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::PreprocessingUpdate { - status, - payment_method_id, - connector_metadata, - preprocessing_step_id, - connector_transaction_id, - connector_response_reference_id, - updated_by, - } => Self { - status: Some(status), - payment_method_id, - modified_at: common_utils::date_time::now(), - connector_metadata, - preprocessing_step_id, - connector_transaction_id, - connector_response_reference_id, - updated_by, - amount: None, - net_amount: None, - currency: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - error_reason: None, - capture_method: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::CaptureUpdate { - multiple_capture_count, - updated_by, - amount_to_capture, - } => Self { - multiple_capture_count, - modified_at: common_utils::date_time::now(), - updated_by, - amount_to_capture, - amount: None, - net_amount: None, - currency: None, - status: None, - connector_transaction_id: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::AmountToCaptureUpdate { - status, - amount_capturable, - updated_by, - } => Self { - status: Some(status), - modified_at: common_utils::date_time::now(), - amount_capturable: Some(amount_capturable), - updated_by, - amount: None, - net_amount: None, - currency: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::ConnectorResponse { - authentication_data, - encoded_data, - connector_transaction_id, - connector, - updated_by, - charge_id, - } => Self { - authentication_data, - encoded_data, - connector_transaction_id, - connector: connector.map(Some), - modified_at: common_utils::date_time::now(), - updated_by, - charge_id, - amount: None, - net_amount: None, - currency: None, - status: None, - amount_to_capture: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { - amount, - amount_capturable, - } => Self { - amount: Some(amount), - modified_at: common_utils::date_time::now(), - amount_capturable: Some(amount_capturable), - net_amount: None, - currency: None, - status: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - updated_by: String::default(), - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::AuthenticationUpdate { - status, - external_three_ds_authentication_attempted, - authentication_connector, - authentication_id, - updated_by, - } => Self { - status: Some(status), - modified_at: common_utils::date_time::now(), - external_three_ds_authentication_attempted, - authentication_connector, - authentication_id, - updated_by, - amount: None, - net_amount: None, - currency: None, - connector_transaction_id: None, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - error_message: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - error_code: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - error_reason: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - unified_code: None, - unified_message: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - PaymentAttemptUpdate::ManualUpdate { - status, - error_code, - error_message, - error_reason, - updated_by, - unified_code, - unified_message, - connector_transaction_id, - } => Self { - status, - error_code: error_code.map(Some), - modified_at: common_utils::date_time::now(), - error_message: error_message.map(Some), - error_reason: error_reason.map(Some), - updated_by, - unified_code: unified_code.map(Some), - unified_message: unified_message.map(Some), - amount: None, - net_amount: None, - currency: None, - connector_transaction_id, - amount_to_capture: None, - connector: None, - authentication_type: None, - payment_method: None, - payment_method_id: None, - cancellation_reason: None, - mandate_id: None, - browser_info: None, - payment_token: None, - connector_metadata: None, - payment_method_data: None, - payment_method_type: None, - payment_experience: None, - business_sub_label: None, - straight_through_algorithm: None, - preprocessing_step_id: None, - capture_method: None, - connector_response_reference_id: None, - multiple_capture_count: None, - surcharge_amount: None, - tax_amount: None, - amount_capturable: None, - merchant_connector_id: None, - authentication_data: None, - encoded_data: None, - external_three_ds_authentication_attempted: None, - authentication_connector: None, - authentication_id: None, - fingerprint_id: None, - payment_method_billing_address_id: None, - charge_id: None, - client_source: None, - client_version: None, - customer_acceptance: None, - card_network: None, - shipping_cost: None, - order_tax_amount: None, - }, - } +// TODO: Add fields as necessary +#[cfg(feature = "v2")] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum PaymentAttemptUpdate {} + +#[cfg(feature = "v2")] +impl ForeignIDRef for PaymentAttempt { + fn foreign_id(&self) -> String { + todo!() } } +#[cfg(feature = "v1")] impl ForeignIDRef for PaymentAttempt { fn foreign_id(&self) -> String { self.attempt_id.clone() } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentAttempt { type DstType = DieselPaymentAttempt; @@ -1925,7 +978,7 @@ impl behaviour::Conversion for PaymentAttempt { } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentAttempt { type DstType = DieselPaymentAttempt; @@ -1941,70 +994,118 @@ impl behaviour::Conversion for PaymentAttempt { .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); + + let Self { + payment_id, + merchant_id, + status, + net_amount, + error_message, + surcharge_amount, + tax_on_surcharge, + confirm, + authentication_type, + created_at, + modified_at, + last_synced, + cancellation_reason, + browser_info, + error_code, + payment_token, + connector_metadata, + payment_experience, + payment_method_data, + routing_result, + preprocessing_step_id, + error_reason, + multiple_capture_count, + connector_response_reference_id, + amount_capturable, + updated_by, + authentication_data, + encoded_data, + merchant_connector_id, + unified_code, + unified_message, + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + payment_method_billing_address_id, + fingerprint_id, + charge_id, + client_source, + client_version, + customer_acceptance, + profile_id, + organization_id, + payment_method_type, + connector_payment_id, + payment_method_subtype, + authentication_applied, + external_reference_id, + id, + amount_to_capture, + payment_method_id, + shipping_cost, + order_tax_amount, + connector, + } = self; + Ok(DieselPaymentAttempt { - payment_id: self.payment_id, - merchant_id: self.merchant_id, - attempt_id: self.attempt_id, - status: self.status, - amount: self.amount, - currency: self.currency, - save_to_locker: self.save_to_locker, - connector: self.connector, - error_message: self.error_message, - offer_amount: self.offer_amount, - surcharge_amount: self.surcharge_amount, - tax_amount: self.tax_amount, - payment_method_id: self.payment_method_id, - payment_method: self.payment_method, - connector_transaction_id: self.connector_transaction_id, - capture_method: self.capture_method, - capture_on: self.capture_on, - confirm: self.confirm, - authentication_type: self.authentication_type, - created_at: self.created_at, - modified_at: self.modified_at, - last_synced: self.last_synced, - cancellation_reason: self.cancellation_reason, - amount_to_capture: self.amount_to_capture, - mandate_id: self.mandate_id, - browser_info: self.browser_info, - error_code: self.error_code, - payment_token: self.payment_token, - connector_metadata: self.connector_metadata, - payment_experience: self.payment_experience, - payment_method_type: self.payment_method_type, - payment_method_data: self.payment_method_data, - business_sub_label: self.business_sub_label, - straight_through_algorithm: self.straight_through_algorithm, - preprocessing_step_id: self.preprocessing_step_id, - mandate_details: self.mandate_details.map(Into::into), - error_reason: self.error_reason, - multiple_capture_count: self.multiple_capture_count, - connector_response_reference_id: self.connector_response_reference_id, - amount_capturable: self.amount_capturable, - updated_by: self.updated_by, - merchant_connector_id: self.merchant_connector_id, - authentication_data: self.authentication_data, - encoded_data: self.encoded_data, - unified_code: self.unified_code, - unified_message: self.unified_message, - net_amount: Some(self.net_amount), - external_three_ds_authentication_attempted: self - .external_three_ds_authentication_attempted, - authentication_connector: self.authentication_connector, - authentication_id: self.authentication_id, - mandate_data: self.mandate_data.map(Into::into), - fingerprint_id: self.fingerprint_id, - payment_method_billing_address_id: self.payment_method_billing_address_id, - charge_id: self.charge_id, - client_source: self.client_source, - client_version: self.client_version, - customer_acceptance: self.customer_acceptance, - profile_id: self.profile_id, - organization_id: self.organization_id, + payment_id, + merchant_id, + id, + status, + error_message, + surcharge_amount, + tax_on_surcharge, + payment_method_id, + payment_method_type_v2: payment_method_type, + connector_payment_id, + confirm, + authentication_type, + created_at, + modified_at, + last_synced, + cancellation_reason, + amount_to_capture, + browser_info, + error_code, + payment_token, + connector_metadata, + payment_experience, + payment_method_subtype, + payment_method_data, + preprocessing_step_id, + error_reason, + multiple_capture_count, + connector_response_reference_id, + amount_capturable, + updated_by, + merchant_connector_id, + authentication_data, + encoded_data, + unified_code, + unified_message, + net_amount: Some(net_amount), + external_three_ds_authentication_attempted, + authentication_connector, + authentication_id, + fingerprint_id, + payment_method_billing_address_id, + charge_id, + client_source, + client_version, + customer_acceptance, + profile_id, + organization_id, card_network, - order_tax_amount: self.order_tax_amount, - shipping_cost: self.shipping_cost, + order_tax_amount, + shipping_cost, + routing_result, + authentication_applied, + external_reference_id, + connector, }) } @@ -2018,26 +1119,18 @@ impl behaviour::Conversion for PaymentAttempt { Self: Sized, { async { - let net_amount = storage_model.get_or_calculate_net_amount(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, - attempt_id: storage_model.attempt_id, + id: storage_model.id, status: storage_model.status, - amount: storage_model.amount, - net_amount, - currency: storage_model.currency, - save_to_locker: storage_model.save_to_locker, - connector: storage_model.connector, + net_amount: storage_model.net_amount.unwrap_or(MinorUnit::new(0)), + tax_on_surcharge: storage_model.tax_on_surcharge, error_message: storage_model.error_message, - offer_amount: storage_model.offer_amount, surcharge_amount: storage_model.surcharge_amount, - tax_amount: storage_model.tax_amount, payment_method_id: storage_model.payment_method_id, - payment_method: storage_model.payment_method, - connector_transaction_id: storage_model.connector_transaction_id, - capture_method: storage_model.capture_method, - capture_on: storage_model.capture_on, + payment_method_type: storage_model.payment_method_type_v2, + connector_payment_id: storage_model.connector_payment_id, confirm: storage_model.confirm, authentication_type: storage_model.authentication_type, created_at: storage_model.created_at, @@ -2045,18 +1138,14 @@ impl behaviour::Conversion for PaymentAttempt { last_synced: storage_model.last_synced, cancellation_reason: storage_model.cancellation_reason, amount_to_capture: storage_model.amount_to_capture, - mandate_id: storage_model.mandate_id, browser_info: storage_model.browser_info, error_code: storage_model.error_code, payment_token: storage_model.payment_token, connector_metadata: storage_model.connector_metadata, payment_experience: storage_model.payment_experience, - payment_method_type: storage_model.payment_method_type, payment_method_data: storage_model.payment_method_data, - business_sub_label: storage_model.business_sub_label, - straight_through_algorithm: storage_model.straight_through_algorithm, + routing_result: storage_model.routing_result, preprocessing_step_id: storage_model.preprocessing_step_id, - mandate_details: storage_model.mandate_details.map(Into::into), error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, @@ -2071,7 +1160,6 @@ impl behaviour::Conversion for PaymentAttempt { .external_three_ds_authentication_attempted, authentication_connector: storage_model.authentication_connector, authentication_id: storage_model.authentication_id, - mandate_data: storage_model.mandate_data.map(Into::into), payment_method_billing_address_id: storage_model.payment_method_billing_address_id, fingerprint_id: storage_model.fingerprint_id, charge_id: storage_model.charge_id, @@ -2082,6 +1170,10 @@ impl behaviour::Conversion for PaymentAttempt { organization_id: storage_model.organization_id, order_tax_amount: storage_model.order_tax_amount, shipping_cost: storage_model.shipping_cost, + payment_method_subtype: storage_model.payment_method_subtype, + authentication_applied: storage_model.authentication_applied, + external_reference_id: storage_model.external_reference_id, + connector: storage_model.connector, }) } .await @@ -2100,42 +1192,28 @@ impl behaviour::Conversion for PaymentAttempt { .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); + Ok(DieselPaymentAttemptNew { payment_id: self.payment_id, merchant_id: self.merchant_id, - attempt_id: self.attempt_id, status: self.status, - amount: self.amount, - currency: self.currency, - save_to_locker: self.save_to_locker, - connector: self.connector, error_message: self.error_message, - offer_amount: self.offer_amount, surcharge_amount: self.surcharge_amount, - tax_amount: self.tax_amount, + tax_on_surcharge: self.tax_on_surcharge, payment_method_id: self.payment_method_id, - payment_method: self.payment_method, - capture_method: self.capture_method, - capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, - amount_to_capture: self.amount_to_capture, - mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, error_code: self.error_code, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, - payment_method_type: self.payment_method_type, payment_method_data: self.payment_method_data, - business_sub_label: self.business_sub_label, - straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, - mandate_details: self.mandate_details.map(Into::into), error_reason: self.error_reason, connector_response_reference_id: self.connector_response_reference_id, multiple_capture_count: self.multiple_capture_count, @@ -2151,7 +1229,6 @@ impl behaviour::Conversion for PaymentAttempt { .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, - mandate_data: self.mandate_data.map(Into::into), fingerprint_id: self.fingerprint_id, payment_method_billing_address_id: self.payment_method_billing_address_id, charge_id: self.charge_id, @@ -2163,6 +1240,14 @@ impl behaviour::Conversion for PaymentAttempt { card_network, order_tax_amount: self.order_tax_amount, shipping_cost: self.shipping_cost, + amount_to_capture: self.amount_to_capture, }) } } + +#[cfg(feature = "v2")] +impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal { + fn from(update: PaymentAttemptUpdate) -> Self { + todo!() + } +} diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 381a84ce824..bd4707243ce 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -20,7 +20,9 @@ use masking::{Deserialize, PeekInterface, Secret}; use serde::Serialize; use time::PrimitiveDateTime; -use super::{payment_attempt::PaymentAttempt, PaymentIntent}; +#[cfg(all(feature = "v1", feature = "olap"))] +use super::payment_attempt::PaymentAttempt; +use super::PaymentIntent; use crate::{ behaviour, errors, merchant_key_store::MerchantKeyStore, @@ -46,7 +48,7 @@ pub trait PaymentIntentInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, errors::StorageError>; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, @@ -56,7 +58,7 @@ pub trait PaymentIntentInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, errors::StorageError>; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, @@ -65,17 +67,7 @@ pub trait PaymentIntentInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<PaymentIntent, errors::StorageError>; - async fn get_active_payment_attempt( - &self, - payment: &mut PaymentIntent, - storage_scheme: storage_enums::MerchantStorageScheme, - ) -> error_stack::Result<PaymentAttempt, errors::StorageError>; - - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, @@ -85,11 +77,7 @@ pub trait PaymentIntentInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>; - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, @@ -99,11 +87,7 @@ pub trait PaymentIntentInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>; - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, @@ -111,11 +95,7 @@ pub trait PaymentIntentInterface { constraints: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError>; - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, @@ -125,11 +105,7 @@ pub trait PaymentIntentInterface { storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, errors::StorageError>; - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, @@ -146,7 +122,7 @@ pub struct CustomerData { pub phone_country_code: Option<String>, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: Option<MinorUnit>, @@ -171,7 +147,7 @@ pub struct PaymentIntentUpdateFields { pub is_payment_processor_token_flow: Option<bool>, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, @@ -203,7 +179,7 @@ pub struct PaymentIntentUpdateFields { pub tax_details: Option<diesel_models::TaxDetails>, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { ResponseUpdate { @@ -286,7 +262,7 @@ pub enum PaymentIntentUpdate { } // TODO: remove all enum variants and create new variants that should be used for v2 -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize)] pub enum PaymentIntentUpdate { ResponseUpdate { @@ -359,7 +335,7 @@ pub enum PaymentIntentUpdate { }, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[derive(Clone, Debug, Default)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, @@ -392,7 +368,7 @@ pub struct PaymentIntentUpdateInternal { pub is_payment_processor_token_flow: Option<bool>, } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[derive(Clone, Debug, Default)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, @@ -436,7 +412,7 @@ pub struct PaymentIntentUpdateInternal { pub tax_details: Option<diesel_models::TaxDetails>, } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { todo!() @@ -614,7 +590,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { @@ -815,7 +791,7 @@ use diesel_models::{ PaymentIntentUpdate as DieselPaymentIntentUpdate, PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields, }; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { fn from(value: PaymentIntentUpdate) -> Self { todo!() @@ -959,7 +935,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { fn from(value: PaymentIntentUpdate) -> Self { match value { @@ -1131,7 +1107,7 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate { } // TODO: evaluate if we will be using the same update struct for v2 as well, uncomment this and make necessary changes if necessary -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal { fn from(value: PaymentIntentUpdateInternal) -> Self { todo!() @@ -1199,7 +1175,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInt } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal { fn from(value: PaymentIntentUpdateInternal) -> Self { let modified_at = common_utils::date_time::now(); @@ -1474,7 +1450,7 @@ where } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentIntent { type DstType = DieselPaymentIntent; @@ -1747,7 +1723,7 @@ impl behaviour::Conversion for PaymentIntent { } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for PaymentIntent { type DstType = DieselPaymentIntent; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 2146b97d6eb..5a0d599dcbc 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -527,6 +527,7 @@ impl SurchargeDetails { } } +#[cfg(feature = "v1")] impl From<( &RequestSurchargeDetails, @@ -554,6 +555,23 @@ impl } } +#[cfg(feature = "v2")] +impl + From<( + &RequestSurchargeDetails, + &payments::payment_attempt::PaymentAttempt, + )> for SurchargeDetails +{ + fn from( + (request_surcharge_details, payment_attempt): ( + &RequestSurchargeDetails, + &payments::payment_attempt::PaymentAttempt, + ), + ) -> Self { + todo!() + } +} + #[derive(Debug, Clone)] pub struct AuthenticationData { pub eci: Option<String>, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 7159f34e4bc..69c23730b94 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,10 +33,9 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] -v2 = ["customer_v2", "payment_methods_v2", "payment_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2"] +v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2"] v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"] -payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2", "storage_impl/payment_v2"] payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"] dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing"] @@ -83,7 +82,7 @@ nanoid = "0.4.0" num_cpus = "1.16.0" num-traits = "0.2.19" once_cell = "1.19.0" -openidconnect = "3.5.0" # TODO: remove reqwest +openidconnect = "3.5.0" # TODO: remove reqwest openssl = "0.10.64" quick-xml = { version = "0.31.0", features = ["serialize"] } rand = "0.8.5" @@ -124,7 +123,7 @@ x509-parser = "0.16.0" # First party crates analytics = { version = "0.1.0", path = "../analytics", optional = true, default-features = false } -api_models = { version = "0.1.0", path = "../api_models", features = ["errors"]} +api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] } diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 2217de20907..70c35b460e8 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -763,6 +763,7 @@ pub fn is_operation_allowed<Op: Debug>(operation: &Op) -> bool { .contains(&format!("{operation:?}").as_str()) } +#[cfg(feature = "v1")] impl From<PaymentToFrmData> for PaymentDetails { fn from(payment_data: PaymentToFrmData) -> Self { Self { @@ -837,7 +838,7 @@ pub async fn frm_fulfillment_core( } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn make_fulfillment_api_call( db: &dyn StorageInterface, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs index 65079f633df..8a9a91fb1e7 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs @@ -588,7 +588,7 @@ where updated_by: frm_data.merchant_account.storage_scheme.to_string(), }; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] let payment_attempt = db .update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), @@ -598,7 +598,7 @@ where .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] let payment_attempt = db .update_payment_attempt_with_attempt_id( key_manager_state, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 578655a927d..3c09db61a39 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -4735,11 +4735,7 @@ async fn get_pm_list_context( Ok(payment_method_retrieval_context) } -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - not(feature = "payment_methods_v2") -))] +#[cfg(feature = "v1")] async fn perform_surcharge_ops( payment_intent: Option<storage::PaymentIntent>, state: &routes::SessionState, @@ -4784,7 +4780,7 @@ async fn perform_surcharge_ops( Ok(()) } -#[cfg(all(feature = "v2", feature = "payment_v2", feature = "payment_methods_v2"))] +#[cfg(feature = "v2")] pub async fn perform_surcharge_ops( _payment_intent: Option<storage::PaymentIntent>, _state: &routes::SessionState, diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs index eaf100a0cb6..982d13b54bc 100644 --- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs +++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs @@ -101,6 +101,22 @@ impl SurchargeSource { } } +#[cfg(feature = "v2")] +pub async fn perform_surcharge_decision_management_for_payment_method_list( + _state: &SessionState, + _algorithm_ref: routing::RoutingAlgorithmRef, + _payment_attempt: &storage::PaymentAttempt, + _payment_intent: &storage::PaymentIntent, + _billing_address: Option<payments::Address>, + _response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled], +) -> ConditionalConfigResult<( + types::SurchargeMetadata, + surcharge_decision_configs::MerchantSurchargeConfigs, +)> { + todo!() +} + +#[cfg(feature = "v1")] pub async fn perform_surcharge_decision_management_for_payment_method_list( state: &SessionState, algorithm_ref: routing::RoutingAlgorithmRef, @@ -220,6 +236,7 @@ pub async fn perform_surcharge_decision_management_for_payment_method_list( Ok((surcharge_metadata, merchant_surcharge_configs)) } +#[cfg(feature = "v1")] pub async fn perform_surcharge_decision_management_for_session_flow( state: &SessionState, algorithm_ref: routing::RoutingAlgorithmRef, @@ -358,7 +375,7 @@ pub async fn perform_surcharge_decision_management_for_saved_cards( payment_intent: &storage::PaymentIntent, customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod], ) -> ConditionalConfigResult<types::SurchargeMetadata> { - let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone()); + let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.id.clone()); let surcharge_source = match ( payment_attempt.get_surcharge_details(), algorithm_ref.surcharge_config_algo_id, @@ -424,6 +441,15 @@ pub async fn perform_surcharge_decision_management_for_saved_cards( Ok(surcharge_metadata) } +#[cfg(feature = "v2")] +fn get_surcharge_details_from_surcharge_output( + _surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput, + _payment_attempt: &storage::PaymentAttempt, +) -> ConditionalConfigResult<types::SurchargeDetails> { + todo!() +} + +#[cfg(feature = "v1")] fn get_surcharge_details_from_surcharge_output( surcharge_details: surcharge_decision_configs::SurchargeDetailsOutput, payment_attempt: &storage::PaymentAttempt, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 4bfca852fb0..d00d4b7b259 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -103,6 +103,7 @@ use crate::{ types::{api::authentication, BrowserInformation}, }; +#[cfg(feature = "v1")] #[allow(clippy::too_many_arguments, clippy::type_complexity)] #[instrument(skip_all, fields(payment_id, merchant_id))] pub async fn payments_operation_core<F, Req, Op, FData, D>( @@ -825,6 +826,21 @@ pub fn get_connector_data( .attach_printable("Connector not found in connectors iterator") } +#[cfg(feature = "v2")] +#[instrument(skip_all)] +pub async fn call_surcharge_decision_management_for_session_flow( + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _business_profile: &domain::Profile, + _payment_attempt: &storage::PaymentAttempt, + _payment_intent: &storage::PaymentIntent, + _billing_address: Option<api_models::payments::Address>, + _session_connector_data: &[api::SessionConnectorData], +) -> RouterResult<Option<api::SessionSurchargeDetails>> { + todo!() +} + +#[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn call_surcharge_decision_management_for_session_flow( state: &SessionState, @@ -888,6 +904,8 @@ pub async fn call_surcharge_decision_management_for_session_flow( }) } } + +#[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn payments_core<F, Res, Req, Op, FData, D>( state: SessionState, @@ -2059,6 +2077,32 @@ where Ok(payment_data) } +#[cfg(feature = "v2")] +pub async fn call_create_connector_customer_if_required<F, Req, D>( + _state: &SessionState, + _customer: &Option<domain::Customer>, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _payment_data: &mut D, +) -> RouterResult<Option<storage::CustomerUpdate>> +where + F: Send + Clone + Sync, + Req: Send + Sync, + + // To create connector flow specific interface data + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, + D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>, + RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send, + + // To construct connector flow specific api + dyn api::Connector: + services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>, +{ + todo!() +} + +#[cfg(feature = "v1")] pub async fn call_create_connector_customer_if_required<F, Req, D>( state: &SessionState, customer: &Option<domain::Customer>, @@ -2305,7 +2349,7 @@ where _ => { // 3DS validation for paypal cards after verification (authorize call) if connector.connector_name == router_types::Connector::Paypal - && payment_data.get_payment_attempt().payment_method + && payment_data.get_payment_attempt().get_payment_method() == Some(storage_enums::PaymentMethod::Card) && matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") { @@ -2656,6 +2700,26 @@ pub enum TokenizationAction { TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails), } +#[cfg(feature = "v2")] +#[allow(clippy::too_many_arguments)] +pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( + _state: &SessionState, + _operation: &BoxedOperation<'_, F, Req, D>, + _payment_data: &mut D, + _validate_result: &operations::ValidateResult, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, +) -> RouterResult<(D, TokenizationAction)> +where + F: Send + Clone, + D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, +{ + todo!() +} + +#[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( state: &SessionState, @@ -3037,7 +3101,7 @@ where payment_data.get_payment_intent().status, storage_enums::IntentStatus::Processing ) && matches!( - payment_data.get_payment_attempt().capture_method, + payment_data.get_capture_method(), Some(storage_enums::CaptureMethod::ManualMultiple) )) } @@ -3350,7 +3414,7 @@ pub async fn add_process_sync_task( let tracking_data = api::PaymentsRetrieveRequest { force_sync: true, merchant_id: Some(payment_attempt.merchant_id.clone()), - resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.attempt_id.clone()), + resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.get_id().to_owned()), ..Default::default() }; let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow; @@ -3359,7 +3423,7 @@ pub async fn add_process_sync_task( let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, - &payment_attempt.attempt_id, + payment_attempt.get_id(), &payment_attempt.merchant_id, ); let process_tracker_entry = storage::ProcessTrackerNew::new( @@ -3386,7 +3450,7 @@ pub async fn reset_process_sync_task( let process_tracker_id = pt_utils::get_process_tracker_id( runner, task, - &payment_attempt.attempt_id, + payment_attempt.get_id(), &payment_attempt.merchant_id, ); let psync_process = db @@ -3399,6 +3463,7 @@ pub async fn reset_process_sync_task( Ok(()) } +#[cfg(feature = "v1")] pub fn update_straight_through_routing<F, D>( payment_data: &mut D, request_straight_through: serde_json::Value, @@ -3417,6 +3482,7 @@ where Ok(()) } +#[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_connector_choice<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, @@ -3498,6 +3564,7 @@ where Ok(connector) } +#[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn connector_selection<F, D>( state: &SessionState, @@ -4336,7 +4403,10 @@ pub fn should_add_task_to_process_tracker<F: Clone, D: OperationSessionGetters<F let connector = payment_data.get_payment_attempt().connector.as_deref(); !matches!( - (payment_data.get_payment_attempt().payment_method, connector), + ( + payment_data.get_payment_attempt().get_payment_method(), + connector + ), ( Some(storage_enums::PaymentMethod::BankTransfer), Some("stripe") @@ -5035,6 +5105,7 @@ pub trait OperationSessionGetters<F> { fn get_token_data(&self) -> Option<&storage::PaymentTokenData>; fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>; fn get_force_sync(&self) -> Option<bool>; + fn get_capture_method(&self) -> Option<enums::CaptureMethod>; } pub trait OperationSessionSetters<F> { @@ -5052,6 +5123,7 @@ pub trait OperationSessionSetters<F> { &mut self, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ); + #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod); fn set_frm_message(&mut self, frm_message: FraudCheck); fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus); @@ -5069,6 +5141,8 @@ pub trait OperationSessionSetters<F> { &mut self, setup_future_usage: storage_enums::FutureUsage, ); + + #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, straight_through_algorithm: serde_json::Value, @@ -5199,6 +5273,16 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { fn get_force_sync(&self) -> Option<bool> { self.force_sync } + + #[cfg(feature = "v1")] + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + self.payment_attempt.capture_method + } + + #[cfg(feature = "v2")] + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + self.payment_intent.capture_method + } } impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { @@ -5246,6 +5330,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { self.payment_attempt.merchant_connector_id = merchant_connector_id; } + #[cfg(feature = "v1")] fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod) { self.payment_attempt.capture_method = Some(capture_method); } @@ -5284,6 +5369,7 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { self.payment_intent.setup_future_usage = Some(setup_future_usage); } + #[cfg(feature = "v1")] fn set_straight_through_algorithm_in_payment_attempt( &mut self, straight_through_algorithm: serde_json::Value, @@ -5414,6 +5500,10 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> { fn get_force_sync(&self) -> Option<bool> { todo!() } + + fn get_capture_method(&self) -> Option<enums::CaptureMethod> { + todo!() + } } #[cfg(feature = "v2")] @@ -5462,10 +5552,6 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { todo!() } - fn set_capture_method_in_attempt(&mut self, _capture_method: enums::CaptureMethod) { - todo!() - } - fn set_frm_message(&mut self, _frm_message: FraudCheck) { todo!() } @@ -5500,13 +5586,6 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> { self.payment_intent.setup_future_usage = Some(setup_future_usage); } - fn set_straight_through_algorithm_in_payment_attempt( - &mut self, - _straight_through_algorithm: serde_json::Value, - ) { - todo!() - } - fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) { todo!() } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 6fbe98b3a47..03b2a3153ea 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -72,7 +72,7 @@ impl ) -> RouterResult<Option<types::MerchantRecipientData>> { let payment_method = &self .payment_attempt - .payment_method + .get_payment_method() .get_required_value("PaymentMethod")?; let data = if *payment_method == enums::PaymentMethod::OpenBanking { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index a2fbb3bae44..3782026835b 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -887,6 +887,7 @@ pub fn validate_request_amount_and_amount_to_capture( } } +#[cfg(feature = "v1")] /// if capture method = automatic, amount_to_capture(if provided) must be equal to amount #[instrument(skip_all)] pub fn validate_amount_to_capture_and_capture_method( @@ -2266,7 +2267,7 @@ pub async fn store_in_vault_and_generate_ppmt( ) .await?; let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); - let key_for_hyperswitch_token = payment_attempt.payment_method.map(|payment_method| { + let key_for_hyperswitch_token = payment_attempt.get_payment_method().map(|payment_method| { payment_methods_handler::ParentPaymentMethodToken::create_key_for_token(( &parent_payment_method_token, payment_method, @@ -3870,7 +3871,7 @@ pub enum AttemptType { } impl AttemptType { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc. // Logic to override the fields with data provided in the request should be done after this if required. // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function. @@ -3965,7 +3966,7 @@ impl AttemptType { } } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc. // Logic to override the fields with data provided in the request should be done after this if required. // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function. @@ -4007,7 +4008,7 @@ impl AttemptType { storage_scheme, ); - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] let new_payment_attempt = db .insert_payment_attempt(new_payment_attempt_to_insert, storage_scheme) .await @@ -4015,7 +4016,7 @@ impl AttemptType { payment_id: fetched_payment_intent.get_id().to_owned(), })?; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] let new_payment_attempt = db .insert_payment_attempt( key_manager_state, @@ -4040,7 +4041,7 @@ impl AttemptType { ), Some(true), ), - active_attempt_id: new_payment_attempt.attempt_id.clone(), + active_attempt_id: new_payment_attempt.get_id().to_owned(), attempt_count: new_attempt_count, updated_by: storage_scheme.to_string(), }, @@ -4053,7 +4054,7 @@ impl AttemptType { logger::info!( "manual_retry payment for {:?} with attempt_id {}", updated_payment_intent.get_id(), - new_payment_attempt.attempt_id + new_payment_attempt.get_id() ); Ok((updated_payment_intent, new_payment_attempt)) @@ -5655,7 +5656,7 @@ where if let Some(skip_saving_wallet_at_connector) = skip_saving_wallet_at_connector_optional { if let Some(payment_method_type) = - payment_data.get_payment_attempt().payment_method_type + payment_data.get_payment_attempt().get_payment_method_type() { if skip_saving_wallet_at_connector.contains(&payment_method_type) { logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate."); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 5b171aa4403..51f2de51f26 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -339,7 +339,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa )?; } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] let payment_attempt = db .insert_payment_attempt(payment_attempt_new, storage_scheme) .await @@ -347,7 +347,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_id: payment_id.clone(), })?; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] let payment_attempt = db .insert_payment_attempt( key_manager_state, diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index deaa20e3f3d..6a5299db8c4 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -302,10 +302,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor updated_by: storage_scheme.clone().to_string(), }; - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2") - ))] + #[cfg(feature = "v1")] let respond = state .store .update_payment_attempt_with_attempt_id( @@ -315,7 +312,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor ) .await; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] let respond = state .store .update_payment_attempt_with_attempt_id( @@ -404,7 +401,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu }; //payment_attempt update if let Some(payment_attempt_update) = option_payment_attempt_update { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] { payment_data.payment_attempt = state .store @@ -417,7 +414,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAu .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] { payment_data.payment_attempt = state .store diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index ad643164f11..b69c1ebf911 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -336,6 +336,26 @@ where Ok(router_data) } +#[cfg(feature = "v2")] +#[instrument(skip_all)] +pub async fn modify_trackers<F, FData, D>( + state: &routes::SessionState, + connector: String, + payment_data: &mut D, + key_store: &domain::MerchantKeyStore, + storage_scheme: storage_enums::MerchantStorageScheme, + router_data: types::RouterData<F, FData, types::PaymentsResponseData>, + is_step_up: bool, +) -> RouterResult<()> +where + F: Clone + Send, + FData: Send, + D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync, +{ + todo!() +} + +#[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn modify_trackers<F, FData, D>( state: &routes::SessionState, @@ -426,7 +446,7 @@ where charge_id, }; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), payment_attempt_update, @@ -435,7 +455,7 @@ where .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] db.update_payment_attempt_with_attempt_id( key_manager_state, key_store, @@ -475,7 +495,7 @@ where authentication_type: auth_update, }; - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] db.update_payment_attempt_with_attempt_id( payment_data.get_payment_attempt().clone(), payment_attempt_update, @@ -484,7 +504,7 @@ where .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] db.update_payment_attempt_with_attempt_id( key_manager_state, key_store, @@ -497,14 +517,14 @@ where } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] let payment_attempt = db .insert_payment_attempt(new_payment_attempt, storage_scheme) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error inserting payment attempt")?; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] let payment_attempt = db .insert_payment_attempt( key_manager_state, @@ -524,7 +544,7 @@ where key_manager_state, payment_data.get_payment_intent().clone(), storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { - active_attempt_id: payment_data.get_payment_attempt().attempt_id.clone(), + active_attempt_id: payment_data.get_payment_attempt().get_id().to_owned(), attempt_count: new_attempt_count, updated_by: storage_scheme.to_string(), }, @@ -539,7 +559,7 @@ where Ok(()) } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] #[instrument(skip_all)] pub fn make_new_payment_attempt( connector: String, @@ -618,7 +638,7 @@ pub fn make_new_payment_attempt( } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] #[instrument(skip_all)] pub fn make_new_payment_attempt( _connector: String, diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 1909fa25fb5..04080a42730 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -938,7 +938,7 @@ pub async fn perform_session_flow_routing( let session_pm_input = SessionRoutingPmTypeInput { state: session_input.state, key_store: session_input.key_store, - attempt_id: &session_input.payment_attempt.attempt_id, + attempt_id: session_input.payment_attempt.get_id(), routing_algorithm: &routing_algorithm, backend_input: backend_input.clone(), allowed_connectors, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index e5cce9ad3a9..2c5a88e69b0 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -68,26 +68,6 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; - let resource_id = match payment_data - .payment_attempt - .connector_transaction_id - .clone() - { - Some(id) => types::ResponseId::ConnectorTransactionId(id), - None => types::ResponseId::NoResponseId, - }; - - // [#44]: why should response be filled during request - let response = Ok(types::PaymentsResponseData::TransactionResponse { - resource_id, - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charge_id: None, - }); let additional_data = PaymentAdditionalData { router_base_url: state.base_url.clone(), connector_name: connector_id.to_string(), @@ -106,7 +86,7 @@ where .payment_id .get_string_repr() .to_owned(), - attempt_id: payment_data.payment_attempt.attempt_id.clone(), + attempt_id: payment_data.payment_attempt.get_id().to_owned(), status: payment_data.payment_attempt.status, payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type: auth_type, @@ -120,7 +100,7 @@ where connector_meta_data: None, connector_wallets_details: None, request: T::try_from(additional_data)?, - response, + response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()), amount_captured: None, minor_amount_captured: None, access_token: None, @@ -1258,6 +1238,7 @@ where Ok(output) } +#[cfg(feature = "v1")] pub fn third_party_sdk_session_next_action<Op>( payment_attempt: &storage::PaymentAttempt, operation: &Op, @@ -1508,6 +1489,7 @@ impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralK } } +#[cfg(feature = "v1")] pub fn bank_transfer_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::BankTransferNextStepsData>> { @@ -1538,6 +1520,7 @@ pub fn bank_transfer_next_steps_check( Ok(bank_transfer_next_step) } +#[cfg(feature = "v1")] pub fn voucher_next_steps_check( payment_attempt: storage::PaymentAttempt, ) -> RouterResult<Option<api_models::payments::VoucherNextStepData>> { @@ -1792,29 +1775,45 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v2")] +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { + todo!() + } +} + +#[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; + let capture_method = payment_data.get_capture_method(); let amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.final_amount) .unwrap_or(payment_data.amount.into()); + + let payment_method_type = payment_data + .payment_attempt + .get_payment_method_type() + .to_owned(); Ok(Self { amount, integrity_object: None, mandate_id: payment_data.mandate_id.clone(), - connector_transaction_id: match payment_data.payment_attempt.connector_transaction_id { + connector_transaction_id: match payment_data.payment_attempt.get_connector_payment_id() + { Some(connector_txn_id) => { - types::ResponseId::ConnectorTransactionId(connector_txn_id) + types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned()) } None => types::ResponseId::NoResponseId, }, encoded_data: payment_data.payment_attempt.encoded_data, - capture_method: payment_data.payment_attempt.capture_method, + capture_method, connector_meta: payment_data.payment_attempt.connector_metadata, sync_type: match payment_data.multiple_capture_data { Some(multiple_capture_data) => types::SyncRequestType::MultipleCaptureSync( @@ -1822,7 +1821,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData ), None => types::SyncRequestType::SinglePaymentSync, }, - payment_method_type: payment_data.payment_attempt.payment_method_type, + payment_method_type, currency: payment_data.currency, charges: payment_data .payment_intent @@ -1842,44 +1841,6 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] -impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData { - type Error = error_stack::Report<errors::ApiErrorResponse>; - - fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { - let payment_data = additional_data.payment_data; - let amount = payment_data - .surcharge_details - .as_ref() - .map(|surcharge_details| surcharge_details.final_amount) - .unwrap_or(payment_data.amount.into()); - Ok(Self { - amount, - integrity_object: None, - mandate_id: payment_data.mandate_id.clone(), - connector_transaction_id: match payment_data.payment_attempt.connector_transaction_id { - Some(connector_txn_id) => { - types::ResponseId::ConnectorTransactionId(connector_txn_id) - } - None => types::ResponseId::NoResponseId, - }, - encoded_data: payment_data.payment_attempt.encoded_data, - capture_method: payment_data.payment_attempt.capture_method, - connector_meta: payment_data.payment_attempt.connector_metadata, - sync_type: match payment_data.multiple_capture_data { - Some(multiple_capture_data) => types::SyncRequestType::MultipleCaptureSync( - multiple_capture_data.get_pending_connector_capture_ids(), - ), - None => types::SyncRequestType::SinglePaymentSync, - }, - payment_method_type: payment_data.payment_attempt.payment_method_type, - currency: payment_data.currency, - charges: None, - payment_experience: payment_data.payment_attempt.payment_experience, - }) - } -} - impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsIncrementalAuthorizationData { @@ -1929,12 +1890,14 @@ impl ConnectorTransactionId for Helcim { &self, payment_attempt: storage::PaymentAttempt, ) -> Result<Option<String>, errors::ApiErrorResponse> { - if payment_attempt.connector_transaction_id.is_none() { + if payment_attempt.get_connector_payment_id().is_none() { let metadata = Self::connector_transaction_id(self, &payment_attempt.connector_metadata); metadata.map_err(|_| errors::ApiErrorResponse::ResourceIdNotFound) } else { - Ok(payment_attempt.connector_transaction_id) + Ok(payment_attempt + .get_connector_payment_id() + .map(ToString::to_string)) } } } @@ -2349,6 +2312,16 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz } } +#[cfg(feature = "v2")] +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { + todo!() + } +} + +#[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index 66c3eb91f51..01533cefa5a 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -188,6 +188,17 @@ impl MultipleCaptureData { } } +#[cfg(feature = "v2")] +impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse { + type Error = TryFromIntError; + fn foreign_try_from( + (surcharge_details, payment_attempt): (&SurchargeDetails, &PaymentAttempt), + ) -> Result<Self, Self::Error> { + todo!() + } +} + +#[cfg(feature = "v1")] impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse { type Error = TryFromIntError; fn foreign_try_from( diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs index 1851c563d0c..5058ad600e0 100644 --- a/crates/router/src/core/user/sample_data.rs +++ b/crates/router/src/core/user/sample_data.rs @@ -74,6 +74,7 @@ pub async fn generate_sample_data_for_user( Ok(ApplicationResponse::StatusOk) } +#[cfg(feature = "v1")] pub async fn delete_sample_data_for_user( state: SessionState, user_from_token: UserFromToken, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 607de45215a..ae8b7c15a73 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -1224,6 +1224,7 @@ pub fn is_merchant_enabled_for_payment_id_as_connector_request_id( config_map.contains(merchant_id) } +#[cfg(feature = "v1")] pub fn get_connector_request_reference_id( conf: &Settings, merchant_id: &common_utils::id_type::MerchantId, @@ -1235,10 +1236,20 @@ pub fn get_connector_request_reference_id( if is_config_enabled_for_merchant { payment_attempt.payment_id.get_string_repr().to_owned() } else { - payment_attempt.attempt_id.clone() + payment_attempt.attempt_id.to_owned() } } +// TODO: Based on the connector configuration, the connector_request_reference_id should be generated +#[cfg(feature = "v2")] +pub fn get_connector_request_reference_id( + conf: &Settings, + merchant_id: &common_utils::id_type::MerchantId, + payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, +) -> String { + todo!() +} + /// Validate whether the profile_id exists and is associated with the merchant_id pub async fn validate_and_get_business_profile( db: &dyn StorageInterface, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index d14de8c2330..73d05528634 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1344,7 +1344,7 @@ impl QueueInterface for KafkaStore { #[async_trait::async_trait] impl PaymentAttemptInterface for KafkaStore { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn insert_payment_attempt( &self, payment_attempt: storage::PaymentAttemptNew, @@ -1366,7 +1366,7 @@ impl PaymentAttemptInterface for KafkaStore { Ok(attempt) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, @@ -1395,7 +1395,7 @@ impl PaymentAttemptInterface for KafkaStore { Ok(attempt) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn update_payment_attempt_with_attempt_id( &self, this: storage::PaymentAttempt, @@ -1418,7 +1418,7 @@ impl PaymentAttemptInterface for KafkaStore { Ok(attempt) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] async fn update_payment_attempt_with_attempt_id( &self, key_manager_state: &KeyManagerState, @@ -1449,7 +1449,7 @@ impl PaymentAttemptInterface for KafkaStore { Ok(attempt) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &str, @@ -1467,7 +1467,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, @@ -1483,7 +1483,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, @@ -1501,7 +1501,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, @@ -1513,27 +1513,25 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(feature = "v2", feature = "payment_v2"))] - async fn find_payment_attempt_by_attempt_id_merchant_id( + #[cfg(feature = "v2")] + async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, attempt_id: &str, - merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, - ) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> { + ) -> error_stack::Result<storage::PaymentAttempt, errors::DataStorageError> { self.diesel_store - .find_payment_attempt_by_attempt_id_merchant_id( + .find_payment_attempt_by_id( key_manager_state, merchant_key_store, attempt_id, - merchant_id, storage_scheme, ) .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -1549,7 +1547,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, @@ -1565,7 +1563,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, @@ -1581,7 +1579,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn get_filters_for_payments( &self, pi: &[hyperswitch_domain_models::payments::PaymentIntent], @@ -1596,7 +1594,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, @@ -1626,7 +1624,7 @@ impl PaymentAttemptInterface for KafkaStore { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, @@ -1821,16 +1819,6 @@ impl PaymentIntentInterface for KafkaStore { ) .await } - - async fn get_active_payment_attempt( - &self, - payment: &mut storage::PaymentIntent, - storage_scheme: MerchantStorageScheme, - ) -> error_stack::Result<storage::PaymentAttempt, errors::DataStorageError> { - self.diesel_store - .get_active_payment_attempt(payment, storage_scheme) - .await - } } #[async_trait::async_trait] @@ -3231,6 +3219,7 @@ impl DashboardMetadataInterface for KafkaStore { #[async_trait::async_trait] impl BatchSampleDataInterface for KafkaStore { + #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, @@ -3254,6 +3243,7 @@ impl BatchSampleDataInterface for KafkaStore { Ok(payment_intents_list) } + #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>, @@ -3275,6 +3265,7 @@ impl BatchSampleDataInterface for KafkaStore { Ok(payment_attempts_list) } + #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<diesel_models::RefundNew>, @@ -3294,6 +3285,7 @@ impl BatchSampleDataInterface for KafkaStore { Ok(refunds_list) } + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, @@ -3317,6 +3309,7 @@ impl BatchSampleDataInterface for KafkaStore { Ok(payment_intents_list) } + #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &id_type::MerchantId, @@ -3339,6 +3332,7 @@ impl BatchSampleDataInterface for KafkaStore { Ok(payment_attempts_list) } + #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &id_type::MerchantId, diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs index 3bcbb624cb0..709ff4a358a 100644 --- a/crates/router/src/db/user/sample_data.rs +++ b/crates/router/src/db/user/sample_data.rs @@ -19,6 +19,7 @@ use crate::{connection::pg_connection_write, core::errors::CustomResult, service #[async_trait::async_trait] pub trait BatchSampleDataInterface { + #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, @@ -26,16 +27,19 @@ pub trait BatchSampleDataInterface { key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; + #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; + #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError>; + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, @@ -43,11 +47,13 @@ pub trait BatchSampleDataInterface { key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; + #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; + #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -56,6 +62,7 @@ pub trait BatchSampleDataInterface { #[async_trait::async_trait] impl BatchSampleDataInterface for Store { + #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, @@ -89,6 +96,7 @@ impl BatchSampleDataInterface for Store { .await } + #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, @@ -105,6 +113,8 @@ impl BatchSampleDataInterface for Store { .collect() }) } + + #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, @@ -117,6 +127,7 @@ impl BatchSampleDataInterface for Store { .map_err(diesel_error_to_data_error) } + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, @@ -143,6 +154,7 @@ impl BatchSampleDataInterface for Store { .await } + #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -159,6 +171,8 @@ impl BatchSampleDataInterface for Store { .collect() }) } + + #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -174,6 +188,7 @@ impl BatchSampleDataInterface for Store { #[async_trait::async_trait] impl BatchSampleDataInterface for storage_impl::MockDb { + #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, _state: &KeyManagerState, @@ -183,6 +198,7 @@ impl BatchSampleDataInterface for storage_impl::MockDb { Err(StorageError::MockDbError)? } + #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, _batch: Vec<PaymentAttemptBatchNew>, @@ -190,6 +206,7 @@ impl BatchSampleDataInterface for storage_impl::MockDb { Err(StorageError::MockDbError)? } + #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, _batch: Vec<RefundNew>, @@ -197,6 +214,7 @@ impl BatchSampleDataInterface for storage_impl::MockDb { Err(StorageError::MockDbError)? } + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, _state: &KeyManagerState, @@ -205,12 +223,16 @@ impl BatchSampleDataInterface for storage_impl::MockDb { ) -> CustomResult<Vec<PaymentIntent>, StorageError> { Err(StorageError::MockDbError)? } + + #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { Err(StorageError::MockDbError)? } + + #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d5f73921a9d..dd3471f569b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -513,7 +513,6 @@ pub struct Payments; any(feature = "olap", feature = "oltp"), feature = "v2", feature = "payment_methods_v2", - feature = "payment_v2" ))] impl Payments { pub fn server(state: AppState) -> Scope { @@ -527,12 +526,7 @@ impl Payments { } } -#[cfg(all( - any(feature = "olap", feature = "oltp"), - any(feature = "v2", feature = "v1"), - not(feature = "payment_methods_v2"), - not(feature = "payment_v2") -))] +#[cfg(feature = "v1")] impl Payments { pub fn server(state: AppState) -> Scope { let mut route = web::scope("/payments").app_data(web::Data::new(state)); diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index b1fbd2bb6df..fdb7d8592c5 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -292,7 +292,8 @@ pub async fn generate_sample_data( )) .await } -#[cfg(feature = "dummy_connector")] + +#[cfg(all(feature = "dummy_connector", feature = "v1"))] pub async fn delete_sample_data( state: web::Data<AppState>, http_req: HttpRequest, diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index b3827450a83..76894928434 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -59,6 +59,7 @@ pub struct KafkaPaymentAttempt<'a> { pub card_network: Option<String>, } +#[cfg(feature = "v1")] impl<'a> KafkaPaymentAttempt<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { Self { @@ -118,6 +119,67 @@ impl<'a> KafkaPaymentAttempt<'a> { } } +#[cfg(feature = "v2")] +impl<'a> KafkaPaymentAttempt<'a> { + pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { + todo!() + // Self { + // payment_id: &attempt.payment_id, + // merchant_id: &attempt.merchant_id, + // attempt_id: &attempt.attempt_id, + // status: attempt.status, + // amount: attempt.amount, + // currency: attempt.currency, + // save_to_locker: attempt.save_to_locker, + // connector: attempt.connector.as_ref(), + // error_message: attempt.error_message.as_ref(), + // offer_amount: attempt.offer_amount, + // surcharge_amount: attempt.surcharge_amount, + // tax_amount: attempt.tax_amount, + // payment_method_id: attempt.payment_method_id.as_ref(), + // payment_method: attempt.payment_method, + // connector_transaction_id: attempt.connector_transaction_id.as_ref(), + // capture_method: attempt.capture_method, + // capture_on: attempt.capture_on.map(|i| i.assume_utc()), + // confirm: attempt.confirm, + // authentication_type: attempt.authentication_type, + // created_at: attempt.created_at.assume_utc(), + // modified_at: attempt.modified_at.assume_utc(), + // last_synced: attempt.last_synced.map(|i| i.assume_utc()), + // cancellation_reason: attempt.cancellation_reason.as_ref(), + // amount_to_capture: attempt.amount_to_capture, + // mandate_id: attempt.mandate_id.as_ref(), + // browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), + // error_code: attempt.error_code.as_ref(), + // connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), + // payment_experience: attempt.payment_experience.as_ref(), + // payment_method_type: attempt.payment_method_type.as_ref(), + // payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), + // error_reason: attempt.error_reason.as_ref(), + // multiple_capture_count: attempt.multiple_capture_count, + // amount_capturable: attempt.amount_capturable, + // merchant_connector_id: attempt.merchant_connector_id.as_ref(), + // net_amount: attempt.net_amount, + // unified_code: attempt.unified_code.as_ref(), + // unified_message: attempt.unified_message.as_ref(), + // mandate_data: attempt.mandate_data.as_ref(), + // client_source: attempt.client_source.as_ref(), + // client_version: attempt.client_version.as_ref(), + // profile_id: &attempt.profile_id, + // organization_id: &attempt.organization_id, + // card_network: attempt + // .payment_method_data + // .as_ref() + // .and_then(|data| data.as_object()) + // .and_then(|pm| pm.get("card")) + // .and_then(|data| data.as_object()) + // .and_then(|card| card.get("card_network")) + // .and_then(|network| network.as_str()) + // .map(|network| network.to_string()), + // } + } +} + impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> { fn key(&self) -> String { format!( diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index 13ab0319819..b4d6cd8835a 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -60,6 +60,7 @@ pub struct KafkaPaymentAttemptEvent<'a> { pub card_network: Option<String>, } +#[cfg(feature = "v1")] impl<'a> KafkaPaymentAttemptEvent<'a> { pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { Self { @@ -119,6 +120,67 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { } } +#[cfg(feature = "v2")] +impl<'a> KafkaPaymentAttemptEvent<'a> { + pub fn from_storage(attempt: &'a PaymentAttempt) -> Self { + todo!() + // Self { + // payment_id: &attempt.payment_id, + // merchant_id: &attempt.merchant_id, + // attempt_id: &attempt.attempt_id, + // status: attempt.status, + // amount: attempt.amount, + // currency: attempt.currency, + // save_to_locker: attempt.save_to_locker, + // connector: attempt.connector.as_ref(), + // error_message: attempt.error_message.as_ref(), + // offer_amount: attempt.offer_amount, + // surcharge_amount: attempt.surcharge_amount, + // tax_amount: attempt.tax_amount, + // payment_method_id: attempt.payment_method_id.as_ref(), + // payment_method: attempt.payment_method, + // connector_transaction_id: attempt.connector_transaction_id.as_ref(), + // capture_method: attempt.capture_method, + // capture_on: attempt.capture_on.map(|i| i.assume_utc()), + // confirm: attempt.confirm, + // authentication_type: attempt.authentication_type, + // created_at: attempt.created_at.assume_utc(), + // modified_at: attempt.modified_at.assume_utc(), + // last_synced: attempt.last_synced.map(|i| i.assume_utc()), + // cancellation_reason: attempt.cancellation_reason.as_ref(), + // amount_to_capture: attempt.amount_to_capture, + // mandate_id: attempt.mandate_id.as_ref(), + // browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()), + // error_code: attempt.error_code.as_ref(), + // connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()), + // payment_experience: attempt.payment_experience.as_ref(), + // payment_method_type: attempt.payment_method_type.as_ref(), + // payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()), + // error_reason: attempt.error_reason.as_ref(), + // multiple_capture_count: attempt.multiple_capture_count, + // amount_capturable: attempt.amount_capturable, + // merchant_connector_id: attempt.merchant_connector_id.as_ref(), + // net_amount: attempt.net_amount, + // unified_code: attempt.unified_code.as_ref(), + // unified_message: attempt.unified_message.as_ref(), + // mandate_data: attempt.mandate_data.as_ref(), + // client_source: attempt.client_source.as_ref(), + // client_version: attempt.client_version.as_ref(), + // profile_id: &attempt.profile_id, + // organization_id: &attempt.organization_id, + // card_network: attempt + // .payment_method_data + // .as_ref() + // .and_then(|data| data.as_object()) + // .and_then(|pm| pm.get("card")) + // .and_then(|data| data.as_object()) + // .and_then(|card| card.get("card_network")) + // .and_then(|network| network.as_str()) + // .map(|network| network.to_string()), + // } + } +} + impl<'a> super::KafkaMessage for KafkaPaymentAttemptEvent<'a> { fn key(&self) -> String { format!( diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 30bb6630684..548d216d6e8 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -101,7 +101,7 @@ use crate::{ consts, core::{ errors::{self}, - payments::PaymentData, + payments::{OperationSessionGetters, PaymentData}, }, services, types::transformers::{ForeignFrom, ForeignTryFrom}, @@ -271,10 +271,7 @@ impl Capturable for PaymentsAuthorizeData { where F: Clone, { - match payment_data - .payment_attempt - .capture_method - .unwrap_or_default() + match payment_data.get_capture_method().unwrap_or_default() { common_enums::CaptureMethod::Automatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); @@ -349,8 +346,7 @@ impl Capturable for CompleteAuthorizeData { F: Clone, { match payment_data - .payment_attempt - .capture_method + .get_capture_method() .unwrap_or_default() { common_enums::CaptureMethod::Automatic => { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 80ad6da8d25..40ba7cc7cf6 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -83,7 +83,9 @@ pub trait ConnectorTransactionId: ConnectorCommon + Sync { &self, payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, ) -> Result<Option<String>, errors::ApiErrorResponse> { - Ok(payment_attempt.connector_transaction_id) + Ok(payment_attempt + .get_connector_payment_id() + .map(ToString::to_string)) } } diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 18b6e8cc6f9..f6caa64fe6e 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -21,6 +21,16 @@ pub trait PaymentAttemptExt { } impl PaymentAttemptExt for PaymentAttempt { + #[cfg(feature = "v2")] + fn make_new_capture( + &self, + capture_amount: MinorUnit, + capture_status: enums::CaptureStatus, + ) -> RouterResult<CaptureNew> { + todo!() + } + + #[cfg(feature = "v1")] fn make_new_capture( &self, capture_amount: MinorUnit, @@ -55,10 +65,19 @@ impl PaymentAttemptExt for PaymentAttempt { connector_response_reference_id: None, }) } + + #[cfg(feature = "v1")] fn get_next_capture_id(&self) -> String { let next_sequence_number = self.multiple_capture_count.unwrap_or_default() + 1; format!("{}_{}", self.attempt_id.clone(), next_sequence_number) } + + #[cfg(feature = "v2")] + fn get_next_capture_id(&self) -> String { + todo!() + } + + #[cfg(feature = "v1")] fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> { self.surcharge_amount.map(|surcharge_amount| { api_models::payments::RequestSurchargeDetails { @@ -67,11 +86,23 @@ impl PaymentAttemptExt for PaymentAttempt { } }) } + + #[cfg(feature = "v2")] + fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> { + todo!() + } + + #[cfg(feature = "v1")] fn get_total_amount(&self) -> MinorUnit { self.amount + self.surcharge_amount.unwrap_or_default() + self.tax_amount.unwrap_or_default() } + + #[cfg(feature = "v2")] + fn get_total_amount(&self) -> MinorUnit { + todo!() + } } pub trait AttemptStatusExt { @@ -86,8 +117,7 @@ impl AttemptStatusExt for enums::AttemptStatus { #[cfg(test)] #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), // Ignoring tests for v2 since they aren't actively running + feature = "v1", // Ignoring tests for v2 since they aren't actively running feature = "dummy_connector" ))] mod tests { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 992816a3616..b032906293b 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1288,6 +1288,7 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount> } } +#[cfg(feature = "v1")] impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self { Self { @@ -1476,6 +1477,7 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { } } +#[cfg(feature = "v1")] impl ForeignTryFrom<( Option<&storage::PaymentAttempt>, diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index e6f549f4fc4..a54c2bc8ad6 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -381,7 +381,7 @@ pub async fn get_mca_from_payment_intent( let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), @@ -391,7 +391,7 @@ pub async fn get_mca_from_payment_intent( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( key_manager_state, diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index b3dc6d57c6d..0a84d5b25fe 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -15,7 +15,6 @@ olap = ["hyperswitch_domain_models/olap"] payouts = ["hyperswitch_domain_models/payouts"] v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1"] v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2"] -payment_v2 = ["hyperswitch_domain_models/payment_v2", "diesel_models/payment_v2"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] payment_methods_v2 = ["diesel_models/payment_methods_v2", "api_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2"] diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 974de5be802..5954f4791a5 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -329,7 +329,7 @@ impl UniqueConstraints for diesel_models::Address { } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] impl UniqueConstraints for diesel_models::PaymentIntent { fn unique_constraints(&self) -> Vec<String> { vec![self.id.get_string_repr().to_owned()] @@ -340,7 +340,7 @@ impl UniqueConstraints for diesel_models::PaymentIntent { } } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentIntent { #[cfg(feature = "v1")] fn unique_constraints(&self) -> Vec<String> { @@ -361,6 +361,7 @@ impl UniqueConstraints for diesel_models::PaymentIntent { } } +#[cfg(feature = "v1")] impl UniqueConstraints for diesel_models::PaymentAttempt { fn unique_constraints(&self) -> Vec<String> { vec![format!( diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 7abde140991..44c089932d9 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -1,23 +1,23 @@ -use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMethodType}; use common_utils::errors::CustomResult; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; use diesel_models::enums as storage_enums; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; +#[cfg(feature = "v1")] +use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew; use hyperswitch_domain_models::{ errors::StorageError, - payments::payment_attempt::{ - PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate, - }, + payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate}, }; use super::MockDb; +#[cfg(feature = "v1")] use crate::DataModelExt; #[async_trait::async_trait] impl PaymentAttemptInterface for MockDb { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, _payment_id: &common_utils::id_type::PaymentId, @@ -29,7 +29,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filters_for_payments( &self, _pi: &[hyperswitch_domain_models::payments::PaymentIntent], @@ -42,15 +42,15 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_total_count_of_filtered_payment_attempts( &self, _merchant_id: &common_utils::id_type::MerchantId, _active_attempt_ids: &[String], - _connector: Option<Vec<Connector>>, - _payment_method: Option<Vec<PaymentMethod>>, - _payment_method_type: Option<Vec<PaymentMethodType>>, - _authentication_type: Option<Vec<AuthenticationType>>, + _connector: Option<Vec<api_models::enums::Connector>>, + _payment_method: Option<Vec<common_enums::PaymentMethod>>, + _payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, + _authentication_type: Option<Vec<common_enums::AuthenticationType>>, _merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, _time_range: Option<common_utils::types::TimeRange>, _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, @@ -59,7 +59,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, _attempt_id: &str, @@ -70,20 +70,19 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(feature = "v2", feature = "payment_v2"))] - async fn find_payment_attempt_by_attempt_id_merchant_id( + #[cfg(feature = "v2")] + async fn find_payment_attempt_by_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &MerchantKeyStore, _attempt_id: &str, - _merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: storage_enums::MerchantStorageScheme, - ) -> CustomResult<PaymentAttempt, StorageError> { + ) -> error_stack::Result<PaymentAttempt, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, _preprocessing_id: &str, @@ -94,7 +93,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -105,7 +104,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -116,7 +115,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[allow(clippy::panic)] async fn insert_payment_attempt( &self, @@ -194,7 +193,7 @@ impl PaymentAttemptInterface for MockDb { Ok(payment_attempt) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[allow(clippy::panic)] async fn insert_payment_attempt( &self, @@ -207,7 +206,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn update_payment_attempt_with_attempt_id( @@ -232,7 +231,7 @@ impl PaymentAttemptInterface for MockDb { Ok(item.clone()) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] async fn update_payment_attempt_with_attempt_id( &self, _key_manager_state: &KeyManagerState, @@ -245,7 +244,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, _connector_transaction_id: &str, @@ -257,7 +256,7 @@ impl PaymentAttemptInterface for MockDb { Err(StorageError::MockDbError)? } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( @@ -278,7 +277,7 @@ impl PaymentAttemptInterface for MockDb { .unwrap()) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[allow(clippy::unwrap_used)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index 0f1161f644b..22160d901f4 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -6,7 +6,6 @@ use hyperswitch_domain_models::{ errors::StorageError, merchant_key_store::MerchantKeyStore, payments::{ - payment_attempt::PaymentAttempt, payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, PaymentIntent, }, @@ -16,11 +15,7 @@ use super::MockDb; #[async_trait::async_trait] impl PaymentIntentInterface for MockDb { - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, _state: &KeyManagerState, @@ -32,11 +27,8 @@ impl PaymentIntentInterface for MockDb { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + + #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, _state: &KeyManagerState, @@ -48,11 +40,8 @@ impl PaymentIntentInterface for MockDb { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_intent_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -62,11 +51,8 @@ impl PaymentIntentInterface for MockDb { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, _merchant_id: &common_utils::id_type::MerchantId, @@ -76,11 +62,8 @@ impl PaymentIntentInterface for MockDb { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, _state: &KeyManagerState, @@ -88,7 +71,13 @@ impl PaymentIntentInterface for MockDb { _constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, - ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { + ) -> error_stack::Result< + Vec<( + PaymentIntent, + hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, + )>, + StorageError, + > { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? } @@ -141,7 +130,7 @@ impl PaymentIntentInterface for MockDb { Ok(payment_intent.clone()) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] // safety: only used for testing #[allow(clippy::unwrap_used)] async fn find_payment_intent_by_payment_id_merchant_id( @@ -163,7 +152,7 @@ impl PaymentIntentInterface for MockDb { .unwrap()) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, _state: &KeyManagerState, @@ -181,24 +170,4 @@ impl PaymentIntentInterface for MockDb { Ok(payment_intent.clone()) } - - async fn get_active_payment_attempt( - &self, - payment: &mut PaymentIntent, - _storage_scheme: storage_enums::MerchantStorageScheme, - ) -> error_stack::Result<PaymentAttempt, StorageError> { - match payment.active_attempt.clone() { - hyperswitch_domain_models::RemoteStorageObject::ForeignID(id) => { - let attempts = self.payment_attempts.lock().await; - let attempt = attempts - .iter() - .find(|pa| pa.attempt_id == id && pa.merchant_id == payment.merchant_id) - .ok_or(StorageError::ValueNotFound("Attempt not found".to_string()))?; - - payment.active_attempt = attempt.clone().into(); - Ok(attempt.clone()) - } - hyperswitch_domain_models::RemoteStorageObject::Object(pa) => Ok(pa.clone()), - } - } } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 9974393e100..6d669437efd 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1,5 +1,4 @@ -use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMethodType}; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found}; use diesel_models::{ @@ -15,21 +14,21 @@ use diesel_models::{ reverse_lookup::{ReverseLookup, ReverseLookupNew}, }; use error_stack::ResultExt; +#[cfg(feature = "v2")] +use hyperswitch_domain_models::{ + behaviour::{Conversion, ReverseConversion}, + merchant_key_store::MerchantKeyStore, +}; use hyperswitch_domain_models::{ - behaviour::Conversion, errors, mandates::{MandateAmountData, MandateDataType, MandateDetails}, - payments::{ - payment_attempt::{ - PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate, - PaymentListFilters, - }, - PaymentIntent, + payments::payment_attempt::{ + PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate, }, }; -#[cfg(all(feature = "v2", feature = "payment_v2"))] +#[cfg(feature = "olap")] use hyperswitch_domain_models::{ - behaviour::ReverseConversion, merchant_key_store::MerchantKeyStore, + payments::payment_attempt::PaymentListFilters, payments::PaymentIntent, }; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; @@ -45,7 +44,7 @@ use crate::{ #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, @@ -64,7 +63,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, @@ -93,7 +92,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .change_context(errors::StorageError::DecryptionError) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, @@ -112,7 +111,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, @@ -145,7 +144,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .change_context(errors::StorageError::DecryptionError) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, @@ -169,7 +168,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, @@ -191,7 +190,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, @@ -213,7 +212,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, @@ -235,7 +234,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, @@ -260,7 +259,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filters_for_payments( &self, @@ -268,6 +267,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentListFilters, errors::StorageError> { + use hyperswitch_domain_models::behaviour::Conversion; + let conn = pg_connection_read(self).await?; let intents = futures::future::try_join_all(pi.iter().cloned().map(|pi| async { Conversion::convert(pi) @@ -301,7 +302,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { ) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, @@ -324,7 +325,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_attempts_by_merchant_id_payment_id( &self, @@ -346,7 +347,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { }) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, @@ -365,19 +366,18 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .map(PaymentAttempt::from_storage_model) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] - async fn find_payment_attempt_by_attempt_id_merchant_id( + async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, attempt_id: &str, - merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: MerchantStorageScheme, - ) -> CustomResult<PaymentAttempt, errors::StorageError> { + ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { let conn = pg_connection_read(self).await?; - DieselPaymentAttempt::find_by_merchant_id_attempt_id(&conn, merchant_id, attempt_id) + DieselPaymentAttempt::find_by_id(&conn, attempt_id) .await .map_err(|er| { let new_err = diesel_error_to_data_error(er.current_context()); @@ -392,16 +392,16 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { .change_context(errors::StorageError::DecryptionError) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], - connector: Option<Vec<Connector>>, - payment_method: Option<Vec<PaymentMethod>>, - payment_method_type: Option<Vec<PaymentMethodType>>, - authentication_type: Option<Vec<AuthenticationType>>, + connector: Option<Vec<api_models::enums::Connector>>, + payment_method: Option<Vec<common_enums::PaymentMethod>>, + payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, + authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, @@ -441,7 +441,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { #[async_trait::async_trait] impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, @@ -590,7 +590,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_payment_attempt( &self, @@ -610,7 +610,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, @@ -734,7 +734,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_payment_attempt_with_attempt_id( &self, @@ -756,7 +756,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, @@ -816,7 +816,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, @@ -875,7 +875,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, @@ -937,7 +937,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, @@ -1006,7 +1006,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, @@ -1060,7 +1060,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, @@ -1126,29 +1126,27 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] - async fn find_payment_attempt_by_attempt_id_merchant_id( + async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &MerchantKeyStore, attempt_id: &str, - merchant_id: &common_utils::id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<PaymentAttempt, errors::StorageError> { // Ignoring storage scheme for v2 implementation self.router_store - .find_payment_attempt_by_attempt_id_merchant_id( + .find_payment_attempt_by_id( key_manager_state, merchant_key_store, attempt_id, - merchant_id, storage_scheme, ) .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, @@ -1217,7 +1215,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_attempts_by_merchant_id_payment_id( &self, @@ -1267,7 +1265,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filters_for_payments( &self, @@ -1280,16 +1278,16 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { .await } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], - connector: Option<Vec<Connector>>, - payment_method: Option<Vec<PaymentMethod>>, - payment_method_type: Option<Vec<PaymentMethodType>>, - authentication_type: Option<Vec<AuthenticationType>>, + connector: Option<Vec<api_models::enums::Connector>>, + payment_method: Option<Vec<common_enums::PaymentMethod>>, + payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, + authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, @@ -1375,159 +1373,7 @@ impl DataModelExt for MandateDataType { } } -#[cfg(all(feature = "v2", feature = "payment_v2"))] -impl DataModelExt for PaymentAttempt { - type StorageModel = DieselPaymentAttempt; - - fn to_storage_model(self) -> Self::StorageModel { - DieselPaymentAttempt { - payment_id: self.payment_id, - merchant_id: self.merchant_id, - attempt_id: self.attempt_id, - status: self.status, - amount: self.amount, - net_amount: Some(self.net_amount), - currency: self.currency, - save_to_locker: self.save_to_locker, - connector: self.connector, - error_message: self.error_message, - offer_amount: self.offer_amount, - surcharge_amount: self.surcharge_amount, - tax_amount: self.tax_amount, - payment_method_id: self.payment_method_id, - payment_method: self.payment_method, - connector_transaction_id: self.connector_transaction_id, - capture_method: self.capture_method, - capture_on: self.capture_on, - confirm: self.confirm, - authentication_type: self.authentication_type, - created_at: self.created_at, - modified_at: self.modified_at, - last_synced: self.last_synced, - cancellation_reason: self.cancellation_reason, - amount_to_capture: self.amount_to_capture, - mandate_id: self.mandate_id, - browser_info: self.browser_info, - error_code: self.error_code, - payment_token: self.payment_token, - connector_metadata: self.connector_metadata, - payment_experience: self.payment_experience, - payment_method_type: self.payment_method_type, - card_network: self - .payment_method_data - .as_ref() - .and_then(|data| data.as_object()) - .and_then(|card| card.get("card")) - .and_then(|data| data.as_object()) - .and_then(|card| card.get("card_network")) - .and_then(|network| network.as_str()) - .map(|network| network.to_string()), - payment_method_data: self.payment_method_data, - business_sub_label: self.business_sub_label, - straight_through_algorithm: self.straight_through_algorithm, - preprocessing_step_id: self.preprocessing_step_id, - mandate_details: self.mandate_details.map(|d| d.to_storage_model()), - error_reason: self.error_reason, - multiple_capture_count: self.multiple_capture_count, - connector_response_reference_id: self.connector_response_reference_id, - amount_capturable: self.amount_capturable, - updated_by: self.updated_by, - authentication_data: self.authentication_data, - encoded_data: self.encoded_data, - merchant_connector_id: self.merchant_connector_id, - unified_code: self.unified_code, - unified_message: self.unified_message, - external_three_ds_authentication_attempted: self - .external_three_ds_authentication_attempted, - authentication_connector: self.authentication_connector, - authentication_id: self.authentication_id, - mandate_data: self.mandate_data.map(|d| d.to_storage_model()), - payment_method_billing_address_id: self.payment_method_billing_address_id, - fingerprint_id: self.fingerprint_id, - charge_id: self.charge_id, - client_source: self.client_source, - client_version: self.client_version, - customer_acceptance: self.customer_acceptance, - organization_id: self.organization_id, - profile_id: self.profile_id, - shipping_cost: self.shipping_cost, - order_tax_amount: self.order_tax_amount, - } - } - - fn from_storage_model(storage_model: Self::StorageModel) -> Self { - Self { - net_amount: storage_model.get_or_calculate_net_amount(), - payment_id: storage_model.payment_id, - merchant_id: storage_model.merchant_id, - attempt_id: storage_model.attempt_id, - status: storage_model.status, - amount: storage_model.amount, - currency: storage_model.currency, - save_to_locker: storage_model.save_to_locker, - connector: storage_model.connector, - error_message: storage_model.error_message, - offer_amount: storage_model.offer_amount, - surcharge_amount: storage_model.surcharge_amount, - tax_amount: storage_model.tax_amount, - payment_method_id: storage_model.payment_method_id, - payment_method: storage_model.payment_method, - connector_transaction_id: storage_model.connector_transaction_id, - capture_method: storage_model.capture_method, - capture_on: storage_model.capture_on, - confirm: storage_model.confirm, - authentication_type: storage_model.authentication_type, - created_at: storage_model.created_at, - modified_at: storage_model.modified_at, - last_synced: storage_model.last_synced, - cancellation_reason: storage_model.cancellation_reason, - amount_to_capture: storage_model.amount_to_capture, - mandate_id: storage_model.mandate_id, - browser_info: storage_model.browser_info, - error_code: storage_model.error_code, - payment_token: storage_model.payment_token, - connector_metadata: storage_model.connector_metadata, - payment_experience: storage_model.payment_experience, - payment_method_type: storage_model.payment_method_type, - payment_method_data: storage_model.payment_method_data, - business_sub_label: storage_model.business_sub_label, - straight_through_algorithm: storage_model.straight_through_algorithm, - preprocessing_step_id: storage_model.preprocessing_step_id, - mandate_details: storage_model - .mandate_details - .map(MandateDataType::from_storage_model), - error_reason: storage_model.error_reason, - multiple_capture_count: storage_model.multiple_capture_count, - connector_response_reference_id: storage_model.connector_response_reference_id, - amount_capturable: storage_model.amount_capturable, - updated_by: storage_model.updated_by, - authentication_data: storage_model.authentication_data, - encoded_data: storage_model.encoded_data, - merchant_connector_id: storage_model.merchant_connector_id, - unified_code: storage_model.unified_code, - unified_message: storage_model.unified_message, - external_three_ds_authentication_attempted: storage_model - .external_three_ds_authentication_attempted, - authentication_connector: storage_model.authentication_connector, - authentication_id: storage_model.authentication_id, - mandate_data: storage_model - .mandate_data - .map(MandateDetails::from_storage_model), - payment_method_billing_address_id: storage_model.payment_method_billing_address_id, - fingerprint_id: storage_model.fingerprint_id, - charge_id: storage_model.charge_id, - client_source: storage_model.client_source, - client_version: storage_model.client_version, - customer_acceptance: storage_model.customer_acceptance, - organization_id: storage_model.organization_id, - profile_id: storage_model.profile_id, - shipping_cost: storage_model.shipping_cost, - order_tax_amount: storage_model.order_tax_amount, - } - } -} - -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] +#[cfg(feature = "v1")] impl DataModelExt for PaymentAttempt { type StorageModel = DieselPaymentAttempt; @@ -1679,6 +1525,7 @@ impl DataModelExt for PaymentAttempt { } } +#[cfg(feature = "v1")] impl DataModelExt for PaymentAttemptNew { type StorageModel = DieselPaymentAttemptNew; @@ -1830,6 +1677,7 @@ impl DataModelExt for PaymentAttemptNew { } } +#[cfg(feature = "v1")] impl DataModelExt for PaymentAttemptUpdate { type StorageModel = DieselPaymentAttemptUpdate; diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 971c5edfcdb..4c7232f6f3f 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -12,16 +12,12 @@ use common_utils::{ use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl}; #[cfg(feature = "olap")] use diesel_models::query::generics::db_metrics; -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" -))] +#[cfg(all(feature = "v1", feature = "olap"))] use diesel_models::schema::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, }; -#[cfg(all(feature = "v2", feature = "payment_v2", feature = "olap"))] +#[cfg(all(feature = "v2", feature = "olap"))] use diesel_models::schema_v2::{ payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl}, payment_intent::dsl as pi_dsl, @@ -29,24 +25,23 @@ use diesel_models::schema_v2::{ use diesel_models::{ enums::MerchantStorageScheme, kv, - payment_attempt::PaymentAttempt as DieselPaymentAttempt, payment_intent::{ PaymentIntent as DieselPaymentIntent, PaymentIntentUpdate as DieselPaymentIntentUpdate, }, }; use error_stack::ResultExt; #[cfg(feature = "olap")] -use hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints; +use hyperswitch_domain_models::payments::{ + payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, +}; use hyperswitch_domain_models::{ behaviour::Conversion, errors::StorageError, merchant_key_store::MerchantKeyStore, payments::{ - payment_attempt::PaymentAttempt, payment_intent::{PaymentIntentInterface, PaymentIntentUpdate}, PaymentIntent, }, - RemoteStorageObject, }; use redis_interface::HsetnxReply; #[cfg(feature = "olap")] @@ -60,7 +55,7 @@ use crate::{ errors::RedisErrorExt, redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey}, utils::{self, pg_connection_read, pg_connection_write}, - DataModelExt, DatabaseStore, KVRouterStore, + DatabaseStore, KVRouterStore, }; #[async_trait::async_trait] @@ -285,7 +280,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { } } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, @@ -345,7 +340,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .change_context(StorageError::DecryptionError) } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, @@ -377,38 +372,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .change_context(StorageError::DecryptionError) } - async fn get_active_payment_attempt( - &self, - payment: &mut PaymentIntent, - _storage_scheme: MerchantStorageScheme, - ) -> error_stack::Result<PaymentAttempt, StorageError> { - match payment.active_attempt.clone() { - RemoteStorageObject::ForeignID(attempt_id) => { - let conn = pg_connection_read(self).await?; - - let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id( - &conn, - &payment.merchant_id, - attempt_id.as_str(), - ) - .await - .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); - er.change_context(new_err) - }) - .map(PaymentAttempt::from_storage_model)?; - payment.active_attempt = RemoteStorageObject::Object(pa.clone()); - Ok(pa) - } - RemoteStorageObject::Object(pa) => Ok(pa.clone()), - } - } - - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, @@ -428,11 +392,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .await } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, @@ -452,11 +412,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .await } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -468,11 +424,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .await } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, @@ -492,11 +444,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .await } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &common_utils::id_type::MerchantId, @@ -578,7 +526,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .change_context(StorageError::DecryptionError) } - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))] + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_payment_intent_by_payment_id_merchant_id( &self, @@ -609,7 +557,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .await } - #[cfg(all(feature = "v2", feature = "payment_v2"))] + #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_payment_intent_by_id( &self, @@ -638,39 +586,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .change_context(StorageError::DecryptionError) } - #[instrument(skip_all)] - async fn get_active_payment_attempt( - &self, - payment: &mut PaymentIntent, - _storage_scheme: MerchantStorageScheme, - ) -> error_stack::Result<PaymentAttempt, StorageError> { - match &payment.active_attempt { - RemoteStorageObject::ForeignID(attempt_id) => { - let conn = pg_connection_read(self).await?; - - let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id( - &conn, - &payment.merchant_id, - attempt_id.as_str(), - ) - .await - .map_err(|er| { - let new_err = diesel_error_to_data_error(er.current_context()); - er.change_context(new_err) - }) - .map(PaymentAttempt::from_storage_model)?; - payment.active_attempt = RemoteStorageObject::Object(pa.clone()); - Ok(pa) - } - RemoteStorageObject::Object(pa) => Ok(pa.clone()), - } - } - - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payment_intent_by_constraints( &self, @@ -796,11 +712,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .await } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_payment_intents_by_time_range_constraints( &self, @@ -822,11 +734,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .await } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_intent_status_with_count( &self, @@ -870,11 +778,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { }) } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_payment_intents_attempt( &self, @@ -886,6 +790,8 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { ) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> { use futures::{future::try_join_all, FutureExt}; + use crate::DataModelExt; + let conn = connection::pg_connection_read(self).await.switch()?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() @@ -1040,7 +946,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); query - .get_results_async::<(DieselPaymentIntent, DieselPaymentAttempt)>(conn) + .get_results_async::<( + DieselPaymentIntent, + diesel_models::payment_attempt::PaymentAttempt, + )>(conn) .await .map(|results| { try_join_all(results.into_iter().map(|(pi, pa)| { @@ -1067,11 +976,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .await } - #[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_v2"), - feature = "olap" - ))] + #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_filtered_active_attempt_ids_for_total_count( &self, diff --git a/justfile b/justfile index e1b9c25935d..84df776c1b0 100644 --- a/justfile +++ b/justfile @@ -114,7 +114,7 @@ run *FLAGS: alias r := run -doc_flags := '--all-features --all-targets --exclude-features "v2 payment_v2"' +doc_flags := '--all-features --all-targets --exclude-features "v2"' # Generate documentation doc *FLAGS: diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql b/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql index de4886b866f..cfc769e70e1 100644 --- a/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql +++ b/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql @@ -31,3 +31,11 @@ ALTER TABLE payment_intent DROP COLUMN merchant_reference_id, DROP COLUMN customer_present, DROP COLUMN routing_algorithm_id, DROP COLUMN payment_link_config; + +ALTER TABLE payment_attempt DROP COLUMN payment_method_type_v2, + DROP COLUMN connector_payment_id, + DROP COLUMN payment_method_subtype, + DROP COLUMN routing_result, + DROP COLUMN authentication_applied, + DROP COLUMN external_reference_id, + DROP COLUMN tax_on_surcharge; diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql index b89985ae815..520bbdf6e7e 100644 --- a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql +++ b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql @@ -33,3 +33,12 @@ ADD COLUMN merchant_reference_id VARCHAR(64), ADD COLUMN customer_present BOOLEAN, ADD COLUMN routing_algorithm_id VARCHAR(64), ADD COLUMN payment_link_config JSONB; + +ALTER TABLE payment_attempt +ADD COLUMN payment_method_type_v2 VARCHAR, + ADD COLUMN connector_payment_id VARCHAR(128), + ADD COLUMN payment_method_subtype VARCHAR(64), + ADD COLUMN routing_result JSONB, + ADD COLUMN authentication_applied "AuthenticationType", + ADD COLUMN external_reference_id VARCHAR(128), + ADD COLUMN tax_on_surcharge BIGINT; diff --git a/v2_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql b/v2_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql index 99b94417393..daaf5976618 100644 --- a/v2_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql +++ b/v2_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql @@ -30,3 +30,6 @@ ADD COLUMN IF NOT EXISTS id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; + +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS id VARCHAR(64); diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql index 50f0e89da8c..33a58538a8a 100644 --- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql +++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql @@ -9,7 +9,7 @@ ALTER TABLE ORGANIZATION DROP CONSTRAINT organization_pkey_id; ALTER TABLE ORGANIZATION ADD CONSTRAINT organization_pkey PRIMARY KEY (org_id); -ALTER TABLE organization DROP CONSTRAINT organization_organization_name_key; +ALTER TABLE ORGANIZATION DROP CONSTRAINT organization_organization_name_key; -- back fill UPDATE ORGANIZATION @@ -83,10 +83,16 @@ ALTER TABLE payment_intent ADD PRIMARY KEY (payment_id, merchant_id); ALTER TABLE payment_intent -ALTER COLUMN profile_id DROP NOT NULL; +ALTER COLUMN currency DROP NOT NULL, + ALTER COLUMN client_secret DROP NOT NULL, + ALTER COLUMN profile_id DROP NOT NULL; -ALTER TABLE payment_intent -ALTER COLUMN currency DROP NOT NULL; +------------------------ Payment Attempt ----------------------- +ALTER TABLE payment_attempt DROP CONSTRAINT payment_attempt_pkey; -ALTER TABLE payment_intent -ALTER COLUMN client_secret DROP NOT NULL; +UPDATE payment_attempt +SET attempt_id = id +WHERE attempt_id IS NULL; + +ALTER TABLE payment_attempt +ADD PRIMARY KEY (attempt_id, merchant_id); diff --git a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql index 8d89e4bc92f..33718e20500 100644 --- a/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql +++ b/v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql @@ -91,6 +91,12 @@ ALTER TABLE payment_intent DROP CONSTRAINT payment_intent_pkey; ALTER TABLE payment_intent ADD PRIMARY KEY (id); +------------------------ Payment Attempt ----------------------- +ALTER TABLE payment_attempt DROP CONSTRAINT payment_attempt_pkey; + +ALTER TABLE payment_attempt +ADD PRIMARY KEY (id); + -- This migration is to make fields mandatory in payment_intent table ALTER TABLE payment_intent ALTER COLUMN profile_id diff --git a/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql b/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql index 004c46a67d4..65e90b126fb 100644 --- a/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql +++ b/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql @@ -58,8 +58,8 @@ ADD COLUMN IF NOT EXISTS payment_id VARCHAR(64) NOT NULL, ADD COLUMN business_country "CountryAlpha2", ADD COLUMN business_label VARCHAR(64), ADD COLUMN incremental_authorization_allowed BOOLEAN, - ADD COLUMN fingerprint_id VARCHAR(64), ADD COLUMN merchant_decision VARCHAR(64), + ADD COLUMN fingerprint_id VARCHAR(64), ADD COLUMN statement_descriptor_name VARCHAR(255), ADD COLUMN amount_to_capture BIGINT, ADD COLUMN off_session BOOLEAN, @@ -67,3 +67,26 @@ ADD COLUMN IF NOT EXISTS payment_id VARCHAR(64) NOT NULL, ADD COLUMN merchant_order_reference_id VARCHAR(255), ADD COLUMN is_payment_processor_token_flow BOOLEAN, ADD COLUMN charges jsonb; + +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64) NOT NULL, + ADD COLUMN amount bigint NOT NULL, + ADD COLUMN currency "Currency", + ADD COLUMN save_to_locker BOOLEAN, + ADD COLUMN offer_amount bigint, + ADD COLUMN payment_method VARCHAR, + ADD COLUMN connector_transaction_id VARCHAR(64), + ADD COLUMN capture_method "CaptureMethod", + ADD COLUMN capture_on TIMESTAMP, + ADD COLUMN mandate_id VARCHAR(64), + ADD COLUMN payment_method_type VARCHAR(64), + ADD COLUMN business_sub_label VARCHAR(64), + ADD COLUMN mandate_details JSONB, + ADD COLUMN mandate_data JSONB, + ADD COLUMN tax_amount bigint, + ADD COLUMN straight_through_algorithm JSONB; + +-- Create the index which was dropped because of dropping the column +CREATE INDEX payment_attempt_connector_transaction_id_merchant_id_index ON payment_attempt (connector_transaction_id, merchant_id); + +CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_attempt_id_index ON payment_attempt (payment_id, merchant_id, attempt_id); diff --git a/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql b/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql index 0d2fcdd61d9..55b0b19d0b4 100644 --- a/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql @@ -65,3 +65,21 @@ ALTER TABLE payment_intent DROP COLUMN payment_id, DROP COLUMN merchant_order_reference_id, DROP COLUMN is_payment_processor_token_flow, DROP COLUMN charges; + +-- Run below queries only when V1 is deprecated +ALTER TABLE payment_attempt DROP COLUMN attempt_id, + DROP COLUMN amount, + DROP COLUMN currency, + DROP COLUMN save_to_locker, + DROP COLUMN offer_amount, + DROP COLUMN payment_method, + DROP COLUMN connector_transaction_id, + DROP COLUMN capture_method, + DROP COLUMN capture_on, + DROP COLUMN mandate_id, + DROP COLUMN payment_method_type, + DROP COLUMN business_sub_label, + DROP COLUMN mandate_details, + DROP COLUMN mandate_data, + DROP COLUMN tax_amount, + DROP COLUMN straight_through_algorithm;
refactor
add payment attempt v2 domain and diesel models (#6027)
28e3c366930d29bd59f1a0f06cf3b140387dbb84
2024-11-08 17:42:30
Pa1NarK
ci(cypressV2): update cypress v2 framework to accommodate hyperswitch v2 changes (#6493)
false
diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js index 6faea73d4ef..9785839f422 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js @@ -94,15 +94,3 @@ export function defaultErrorHandler(response, response_data) { expect(response.body.error).to.include(response_data.body.error); } } - -export function isoTimeTomorrow() { - const now = new Date(); - - // Create a new date object for tomorrow - const tomorrow = new Date(now); - tomorrow.setDate(now.getDate() + 1); - - // Convert to ISO string format - const isoStringTomorrow = tomorrow.toISOString(); - return isoStringTomorrow; -} diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js b/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js index b69506ff075..353d96260b5 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/_Reusable.js @@ -15,12 +15,23 @@ function normalise(input) { paybox: "Paybox", paypal: "Paypal", wellsfargo: "Wellsfargo", + fiuu: "Fiuu", // Add more known exceptions here }; if (typeof input !== "string") { - const spec_name = Cypress.spec.name.split("-")[1].split(".")[0]; - return `${spec_name}`; + const specName = Cypress.spec.name; + + if (specName.includes("-")) { + const parts = specName.split("-"); + + if (parts.length > 1 && parts[1].includes(".")) { + return parts[1].split(".")[0]; + } + } + + // Fallback + return `${specName}`; } const lowerCaseInput = input.toLowerCase(); diff --git a/cypress-tests-v2/cypress/e2e/spec/Payment/0001-[No3DS]Payments.cy.js b/cypress-tests-v2/cypress/e2e/spec/Payment/0001-[No3DS]Payments.cy.js new file mode 100644 index 00000000000..21766617c09 --- /dev/null +++ b/cypress-tests-v2/cypress/e2e/spec/Payment/0001-[No3DS]Payments.cy.js @@ -0,0 +1,132 @@ +/* +No 3DS Auto capture with Confirm True +No 3DS Auto capture with Confirm False +No 3DS Manual capture with Confirm True +No 3DS Manual capture with Confirm False +No 3DS Manual multiple capture with Confirm True +No 3DS Manual multiple capture with Confirm False +*/ + +import * as fixtures from "../../../fixtures/imports"; +import State from "../../../utils/State"; +import getConnectorDetails from "../../configs/Payment/Utils"; + +let globalState; + +// Below is an example of a test that is skipped just because it is not implemented yet +describe("[Payment] [No 3DS] [Payment Method: Card]", () => { + context("[Payment] [No 3DS] [Capture: Automatic] [Confirm: True]", () => { + let should_continue = true; + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it.skip("Create payment intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.paymentIntentCreateCall( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + }); + + it.skip("List payment methods", () => { + cy.paymentMethodsListCall(globalState); + }); + + it.skip("Confirm payment intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.paymentIntentConfirmCall( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + }); + + it.skip("Retrieve payment intent", () => { + cy.paymentIntentRetrieveCall(globalState); + }); + }); + context("[Payment] [No 3DS] [Capture: Automatic] [Confirm: False]", () => { + let should_continue = true; + + before("seed global state", () => { + cy.task("getGlobalState").then((state) => { + globalState = new State(state); + }); + }); + beforeEach(function () { + if (!should_continue) { + this.skip(); + } + }); + + after("flush global state", () => { + cy.task("setGlobalState", globalState.data); + }); + + it.skip("Create Payment Intent", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "PaymentIntent" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.paymentIntentCreateCall( + fixtures.createPaymentBody, + req_data, + res_data, + "no_three_ds", + "automatic", + globalState + ); + }); + + it.skip("Payment Methods", () => { + cy.paymentMethodsCallTest(globalState); + }); + + it.skip("Confirm No 3DS", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "No3DSAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; + cy.paymentIntentConfirmCall( + fixtures.confirmBody, + req_data, + res_data, + true, + globalState + ); + }); + + it.skip("Retrieve payment intent", () => { + cy.paymentIntentRetrieveCall(globalState); + }); + }); +}); diff --git a/cypress-tests-v2/cypress/e2e/spec/Payment/0002-[3DS]Payments.cy.js b/cypress-tests-v2/cypress/e2e/spec/Payment/0002-[3DS]Payments.cy.js new file mode 100644 index 00000000000..2a1aa7d5152 --- /dev/null +++ b/cypress-tests-v2/cypress/e2e/spec/Payment/0002-[3DS]Payments.cy.js @@ -0,0 +1,8 @@ +/* +3DS Auto capture with Confirm True +3DS Auto capture with Confirm False +3DS Manual capture with Confirm True +3DS Manual capture with Confirm False +3DS Manual multiple capture with Confirm True +3DS Manual multiple capture with Confirm False +*/ diff --git a/cypress-tests-v2/cypress/fixtures/organization.json b/cypress-tests-v2/cypress/fixtures/organization.json index 24d084ab606..f0577db8876 100644 --- a/cypress-tests-v2/cypress/fixtures/organization.json +++ b/cypress-tests-v2/cypress/fixtures/organization.json @@ -1,6 +1,6 @@ { "org_create": { - "organization_name": "Hyperswitch Organization" + "organization_name": "Hyperswitch" }, "org_update": { "organization_name": "Hyperswitch", diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js index abdf95194bb..eb4ca3423eb 100644 --- a/cypress-tests-v2/cypress/support/commands.js +++ b/cypress-tests-v2/cypress/support/commands.js @@ -26,10 +26,9 @@ // cy.task can only be used in support files (spec files or commands file) -import { - getValueByKey, - isoTimeTomorrow, -} from "../e2e/configs/Payment/Utils.js"; +import { nanoid } from "nanoid"; +import { getValueByKey } from "../e2e/configs/Payment/Utils.js"; +import { isoTimeTomorrow, validateEnv } from "../utils/RequestBodyUtils.js"; function logRequestId(xRequestId) { if (xRequestId) { @@ -48,6 +47,9 @@ Cypress.Commands.add( const base_url = globalState.get("baseUrl"); const url = `${base_url}/v2/organization`; + // Update request body + organizationCreateBody.organization_name += " " + nanoid(); + cy.request({ method: "POST", url: url, @@ -71,7 +73,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Organization create call failed with status ${response.status} and message ${response.body.message}` + `Organization create call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -111,7 +113,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `Organization retrieve call failed with status ${response.status} and message ${response.body.message}` + `Organization retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -125,6 +127,9 @@ Cypress.Commands.add( const organization_id = globalState.get("organizationId"); const url = `${base_url}/v2/organization/${organization_id}`; + // Update request body + organizationUpdateBody.organization_name += " " + nanoid(); + cy.request({ method: "PUT", url: url, @@ -152,7 +157,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Organization update call failed with status ${response.status} and message ${response.body.message}` + `Organization update call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -166,6 +171,8 @@ Cypress.Commands.add( // Define the necessary variables and constants const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); + const key_id_type = "publishable_key"; + const key_id = validateEnv(base_url, key_id_type); const organization_id = globalState.get("organizationId"); const url = `${base_url}/v2/merchant_accounts`; @@ -192,14 +199,9 @@ Cypress.Commands.add( .and.to.include(`${merchant_name}_`) .and.to.be.a("string").and.not.be.empty; - if (base_url.includes("sandbox") || base_url.includes("integ")) - expect(response.body) - .to.have.property("publishable_key") - .and.to.include("pk_snd").and.to.not.be.empty; - else if (base_url.includes("localhost")) - expect(response.body) - .to.have.property("publishable_key") - .and.to.include("pk_dev").and.to.not.be.empty; + expect(response.body) + .to.have.property(key_id_type) + .and.to.include(key_id).and.to.not.be.empty; globalState.set("merchantId", response.body.id); globalState.set("publishableKey", response.body.publishable_key); @@ -208,7 +210,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Merchant create call failed with status ${response.status} and message ${response.body.message}` + `Merchant create call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -218,6 +220,8 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => { // Define the necessary variables and constants const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); + const key_id_type = "publishable_key"; + const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/merchant_accounts/${merchant_id}`; @@ -236,14 +240,8 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => { expect(response.body).to.have.property("id").and.to.be.a("string").and.not .be.empty; - if (base_url.includes("sandbox") || base_url.includes("integ")) - expect(response.body) - .to.have.property("publishable_key") - .and.to.include("pk_snd").and.to.not.be.empty; - else - expect(response.body) - .to.have.property("publishable_key") - .and.to.include("pk_dev").and.to.not.be.empty; + expect(response.body).to.have.property(key_id_type).and.to.include(key_id) + .and.to.not.be.empty; if (merchant_id === undefined || merchant_id === null) { globalState.set("merchantId", response.body.id); @@ -253,7 +251,7 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `Merchant account retrieve call failed with status ${response.status} and message ${response.body.message}` + `Merchant account retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -264,6 +262,8 @@ Cypress.Commands.add( // Define the necessary variables and constants const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); + const key_id_type = "publishable_key"; + const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/merchant_accounts/${merchant_id}`; @@ -284,14 +284,10 @@ Cypress.Commands.add( if (response.status === 200) { expect(response.body.id).to.equal(merchant_id); - if (base_url.includes("sandbox") || base_url.includes("integ")) - expect(response.body) - .to.have.property("publishable_key") - .and.to.include("pk_snd").and.to.not.be.empty; - else - expect(response.body) - .to.have.property("publishable_key") - .and.to.include("pk_dev").and.to.not.be.empty; + expect(response.body) + .to.have.property(key_id_type) + .and.to.include(key_id).and.to.not.be.empty; + expect(response.body.merchant_name).to.equal(merchant_name); if (merchant_id === undefined || merchant_id === null) { @@ -302,7 +298,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Merchant account update call failed with status ${response.status} and message ${response.body.message}` + `Merchant account update call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -349,7 +345,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Business profile create call failed with status ${response.status} and message ${response.body.message}` + `Business profile create call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -390,7 +386,7 @@ Cypress.Commands.add("businessProfileRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `Business profile retrieve call failed with status ${response.status} and message ${response.body.message}` + `Business profile retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -436,7 +432,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Business profile update call failed with status ${response.status} and message ${response.body.message}` + `Business profile update call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -494,8 +490,8 @@ Cypress.Commands.add( authDetails.connector_account_details; if (authDetails && authDetails.metadata) { - createConnectorBody.metadata = { - ...createConnectorBody.metadata, // Preserve existing metadata fields + mcaCreateBody.metadata = { + ...mcaCreateBody.metadata, // Preserve existing metadata fields ...authDetails.metadata, // Merge with authDetails.metadata }; } @@ -525,7 +521,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Merchant connector account create call failed with status ${response.status} and message ${response.body.message}` + `Merchant connector account create call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -573,7 +569,7 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `Merchant connector account retrieve call failed with status ${response.status} and message ${response.body.message}` + `Merchant connector account retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -638,7 +634,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Merchant connector account update call failed with status ${response.status} and message ${response.body.message}` + `Merchant connector account update call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -654,6 +650,8 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => { // We do not want to keep API Key forever, // so we set the expiry to tomorrow as new merchant accounts are created with every run const expiry = isoTimeTomorrow(); + const key_id_type = "key_id"; + const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/api_keys`; @@ -682,13 +680,8 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => { expect(response.body.description).to.equal(apiKeyCreateBody.description); // API Key assertions are intentionally excluded to avoid being exposed in the logs - if (base_url.includes("sandbox") || base_url.includes("integ")) { - expect(response.body).to.have.property("key_id").and.to.include("snd_") - .and.to.not.be.empty; - } else if (base_url.includes("localhost")) { - expect(response.body).to.have.property("key_id").and.to.include("dev_") - .and.to.not.be.empty; - } + expect(response.body).to.have.property(key_id_type).and.to.include(key_id) + .and.to.not.be.empty; globalState.set("apiKeyId", response.body.key_id); globalState.set("apiKey", response.body.api_key); @@ -697,7 +690,7 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => { } else { // to be updated throw new Error( - `API Key create call failed with status ${response.status} and message ${response.body.message}` + `API Key create call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -706,6 +699,8 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => { // Define the necessary variables and constant const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); + const key_id_type = "key_id"; + const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); const api_key_id = globalState.get("apiKeyId"); const url = `${base_url}/v2/api_keys/${api_key_id}`; @@ -728,15 +723,9 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => { if (response.status === 200) { expect(response.body.merchant_id).to.equal(merchant_id); - // API Key assertions are intentionally excluded to avoid being exposed in the logs - if (base_url.includes("sandbox") || base_url.includes("integ")) { - expect(response.body).to.have.property("key_id").and.to.include("snd_") - .and.to.not.be.empty; - } else if (base_url.includes("localhost")) { - expect(response.body).to.have.property("key_id").and.to.include("dev_") - .and.to.not.be.empty; - } + expect(response.body).to.have.property(key_id_type).and.to.include(key_id) + .and.to.not.be.empty; if (api_key === undefined || api_key === null) { globalState.set("apiKey", response.body.api_key); @@ -745,7 +734,7 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `API Key retrieve call failed with status ${response.status} and message ${response.body.message}` + `API Key retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -758,6 +747,8 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => { // We do not want to keep API Key forever, // so we set the expiry to tomorrow as new merchant accounts are created with every run const expiry = isoTimeTomorrow(); + const key_id_type = "key_id"; + const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/api_keys/${api_key_id}`; @@ -786,13 +777,8 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => { expect(response.body.description).to.equal(apiKeyUpdateBody.description); // API Key assertions are intentionally excluded to avoid being exposed in the logs - if (base_url.includes("sandbox") || base_url.includes("integ")) { - expect(response.body).to.have.property("key_id").and.to.include("snd_") - .and.to.not.be.empty; - } else if (base_url.includes("localhost")) { - expect(response.body).to.have.property("key_id").and.to.include("dev_") - .and.to.not.be.empty; - } + expect(response.body).to.have.property(key_id_type).and.to.include(key_id) + .and.to.not.be.empty; if (api_key === undefined || api_key === null) { globalState.set("apiKey", response.body.api_key); @@ -801,7 +787,7 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => { } else { // to be updated throw new Error( - `API Key update call failed with status ${response.status} and message ${response.body.message}` + `API Key update call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -847,7 +833,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Routing algorithm setup call failed with status ${response.status} and message ${response.body.message}` + `Routing algorithm setup call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -886,7 +872,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Routing algorithm activation call failed with status ${response.status} and message ${response.body.message}` + `Routing algorithm activation call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -925,7 +911,7 @@ Cypress.Commands.add("routingActivationRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `Routing algorithm activation retrieve call failed with status ${response.status} and message ${response.body.message}` + `Routing algorithm activation retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -960,7 +946,7 @@ Cypress.Commands.add("routingDeactivateCall", (globalState) => { } else { // to be updated throw new Error( - `Routing algorithm deactivation call failed with status ${response.status} and message ${response.body.message}` + `Routing algorithm deactivation call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -997,7 +983,7 @@ Cypress.Commands.add("routingRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `Routing algorithm activation retrieve call failed with status ${response.status} and message ${response.body.message}` + `Routing algorithm activation retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1016,7 +1002,7 @@ Cypress.Commands.add( routingDefaultFallbackBody = payload; cy.request({ - method: "POST", + method: "PATCH", url: url, headers: { Authorization: `Bearer ${api_key}`, @@ -1032,7 +1018,7 @@ Cypress.Commands.add( } else { // to be updated throw new Error( - `Routing algorithm activation retrieve call failed with status ${response.status} and message ${response.body.message}` + `Routing algorithm activation retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1061,7 +1047,7 @@ Cypress.Commands.add("routingFallbackRetrieveCall", (globalState) => { } else { // to be updated throw new Error( - `Routing algorithm activation retrieve call failed with status ${response.status} and message ${response.body.message}` + `Routing algorithm activation retrieve call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1100,7 +1086,7 @@ Cypress.Commands.add("userLogin", (globalState) => { } else { // to be updated throw new Error( - `User login call failed to get totp token with status ${response.status} and message ${response.body.message}` + `User login call failed to get totp token with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1133,7 +1119,7 @@ Cypress.Commands.add("terminate2Fa", (globalState) => { } else { // to be updated throw new Error( - `2FA terminate call failed with status ${response.status} and message ${response.body.message}` + `2FA terminate call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1166,7 +1152,7 @@ Cypress.Commands.add("userInfo", (globalState) => { } else { // to be updated throw new Error( - `User login call failed to fetch user info with status ${response.status} and message ${response.body.message}` + `User login call failed to fetch user info with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1177,6 +1163,8 @@ Cypress.Commands.add("merchantAccountsListCall", (globalState) => { // Define the necessary variables and constants const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); + const key_id_type = "publishable_key"; + const key_id = validateEnv(base_url, key_id_type); const organization_id = globalState.get("organizationId"); const url = `${base_url}/v2/organization/${organization_id}/merchant_accounts`; @@ -1198,21 +1186,15 @@ Cypress.Commands.add("merchantAccountsListCall", (globalState) => { expect(response.body[key]) .to.have.property("organization_id") .and.to.equal(organization_id); - if (base_url.includes("integ") || base_url.includes("sandbox")) { - expect(response.body[key]) - .to.have.property("publishable_key") - .and.include("pk_snd_").and.to.not.be.empty; - } else if (base_url.includes("localhost")) { - expect(response.body[key]) - .to.have.property("publishable_key") - .and.include("pk_dev_").and.to.not.be.empty; - } + expect(response.body[key]) + .to.have.property(key_id_type) + .and.include(key_id).and.to.not.be.empty; expect(response.body[key]).to.have.property("id").and.to.not.be.empty; } } else { // to be updated throw new Error( - `Merchant accounts list call failed with status ${response.status} and message ${response.body.message}` + `Merchant accounts list call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1253,7 +1235,7 @@ Cypress.Commands.add("businessProfilesListCall", (globalState) => { } else { // to be updated throw new Error( - `Business profiles list call failed with status ${response.status} and message ${response.body.message}` + `Business profiles list call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1314,7 +1296,7 @@ Cypress.Commands.add("mcaListCall", (globalState, service_type) => { } else { // to be updated throw new Error( - `Merchant connector account list call failed with status ${response.status} and message ${response.body.message}` + `Merchant connector account list call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); @@ -1323,6 +1305,8 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { // Define the necessary variables and constants const api_key = globalState.get("adminApiKey"); const base_url = globalState.get("baseUrl"); + const key_id_type = "key_id"; + const key_id = validateEnv(base_url, key_id_type); const merchant_id = globalState.get("merchantId"); const url = `${base_url}/v2/api_keys/list`; @@ -1347,8 +1331,8 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { expect(response.body).to.be.an("array").and.to.not.be.empty; for (const key in response.body) { expect(response.body[key]) - .to.have.property("key_id") - .and.to.include("dev_").and.to.not.be.empty; + .to.have.property(key_id_type) + .and.to.include(key_id).and.to.not.be.empty; expect(response.body[key]) .to.have.property("merchant_id") .and.to.equal(merchant_id).and.to.not.be.empty; @@ -1356,13 +1340,74 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => { } else { // to be updated throw new Error( - `API Keys list call failed with status ${response.status} and message ${response.body.message}` + `API Keys list call failed with status ${response.status} and message: "${response.body.error.message}"` ); } }); }); -// templates +// Payment API calls +// Update the below commands while following the conventions +// Below is an example of how the payment intent create call should look like (update the below command as per the need) +Cypress.Commands.add( + "paymentIntentCreateCall", + ( + globalState, + paymentRequestBody, + paymentResponseBody + /* Add more variables based on the need*/ + ) => { + // Define the necessary variables and constants at the top + // Also construct the URL here + const api_key = globalState.get("apiKey"); + const base_url = globalState.get("baseUrl"); + const profile_id = globalState.get("profileId"); + const url = `${base_url}/v2/payments/create-intent`; + + // Update request body if needed + paymentRequestBody = {}; + + // Pass Custom Headers + const customHeaders = { + "x-profile-id": profile_id, + }; + + cy.request({ + method: "POST", + url: url, + headers: { + "api-key": api_key, + "Content-Type": "application/json", + ...customHeaders, + }, + body: paymentRequestBody, + failOnStatusCode: false, + }).then((response) => { + // Logging x-request-id is mandatory + logRequestId(response.headers["x-request-id"]); + + if (response.status === 200) { + // Update the assertions based on the need + expect(response.body).to.deep.equal(paymentResponseBody); + } else if (response.status === 400) { + // Add 4xx validations here + expect(response.body).to.deep.equal(paymentResponseBody); + } else if (response.status === 500) { + // Add 5xx validations here + expect(response.body).to.deep.equal(paymentResponseBody); + } else { + // If status code is other than the ones mentioned above, default should be thrown + throw new Error( + `Payment intent create call failed with status ${response.status} and message: "${response.body.error.message}"` + ); + } + }); + } +); +Cypress.Commands.add("paymentIntentConfirmCall", (globalState) => {}); +Cypress.Commands.add("paymentIntentRetrieveCall", (globalState) => {}); + +// templates for future use Cypress.Commands.add("", () => { cy.request({}).then((response) => {}); }); diff --git a/cypress-tests-v2/cypress/utils/RequestBodyUtils.js b/cypress-tests-v2/cypress/utils/RequestBodyUtils.js new file mode 100644 index 00000000000..0926cbd97bf --- /dev/null +++ b/cypress-tests-v2/cypress/utils/RequestBodyUtils.js @@ -0,0 +1,48 @@ +const keyPrefixes = { + localhost: { + publishable_key: "pk_dev_", + key_id: "dev_", + }, + integ: { + publishable_key: "pk_snd_", + key_id: "snd_", + }, + sandbox: { + publishable_key: "pk_snd_", + key_id: "snd_", + }, +}; + +export function isoTimeTomorrow() { + const now = new Date(); + + // Create a new date object for tomorrow + const tomorrow = new Date(now); + tomorrow.setDate(now.getDate() + 1); + + // Convert to ISO string format + const isoStringTomorrow = tomorrow.toISOString(); + return isoStringTomorrow; +} + +export function validateEnv(baseUrl, keyIdType) { + if (!baseUrl) { + throw new Error("Please provide a baseUrl"); + } + + const environment = Object.keys(keyPrefixes).find((env) => + baseUrl.includes(env) + ); + + if (!environment) { + throw new Error("Unsupported baseUrl"); + } + + const prefix = keyPrefixes[environment][keyIdType]; + + if (!prefix) { + throw new Error(`Unsupported keyIdType: ${keyIdType}`); + } + + return prefix; +} diff --git a/cypress-tests-v2/package-lock.json b/cypress-tests-v2/package-lock.json index d9282b8d3ce..36f801468a9 100644 --- a/cypress-tests-v2/package-lock.json +++ b/cypress-tests-v2/package-lock.json @@ -10,9 +10,10 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.14.2", + "cypress": "^13.15.2", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", + "nanoid": "^5.0.8", "prettier": "^3.3.2" } }, @@ -28,9 +29,9 @@ } }, "node_modules/@cypress/request": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.5.tgz", - "integrity": "sha512-v+XHd9XmWbufxF1/bTaVm2yhbxY+TB4YtWRqF2zaXBlDNMkls34KiATz0AVDLavL3iB6bQk9/7n3oY1EoLSWGA==", + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.6.tgz", + "integrity": "sha512-fi0eVdCOtKu5Ed6+E8mYxUF6ZTFJDZvHogCBelM0xVXmrDEkyM22gRArQzq1YcHPm1V47Vf/iAD+WgVdUlJCGg==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -49,7 +50,7 @@ "performance-now": "^2.1.0", "qs": "6.13.0", "safe-buffer": "^5.1.2", - "tough-cookie": "^4.1.3", + "tough-cookie": "^5.0.0", "tunnel-agent": "^0.6.0", "uuid": "^8.3.2" }, @@ -567,9 +568,9 @@ } }, "node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.0.0.tgz", + "integrity": "sha512-TdHqgGf9odd8SXNuxtUBVx8Nv+qZOejE6qyqiy5NtbYYQOeFa6zmHkxlPzmaLxWWHsU6nJmB7AETdVPi+2NBUg==", "dev": true, "funding": [ { @@ -741,14 +742,14 @@ } }, "node_modules/cypress": { - "version": "13.14.2", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.14.2.tgz", - "integrity": "sha512-lsiQrN17vHMB2fnvxIrKLAjOr9bPwsNbPZNrWf99s4u+DVmCY6U+w7O3GGG9FvP4EUVYaDu+guWeNLiUzBrqvA==", + "version": "13.15.2", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.15.2.tgz", + "integrity": "sha512-ARbnUorjcCM3XiPwgHKuqsyr5W9Qn+pIIBPaoilnoBkLdSC2oLQjV1BUpnmc7KR+b7Avah3Ly2RMFnfxr96E/A==", "dev": true, "hasInstallScript": true, "license": "MIT", "dependencies": { - "@cypress/request": "^3.0.1", + "@cypress/request": "^3.0.6", "@cypress/xvfb": "^1.2.4", "@types/sinonjs__fake-timers": "8.1.1", "@types/sizzle": "^2.3.2", @@ -759,6 +760,7 @@ "cachedir": "^2.3.0", "chalk": "^4.1.0", "check-more-types": "^2.24.0", + "ci-info": "^4.0.0", "cli-cursor": "^3.1.0", "cli-table3": "~0.6.1", "commander": "^6.2.1", @@ -773,7 +775,6 @@ "figures": "^3.2.0", "fs-extra": "^9.1.0", "getos": "^3.2.1", - "is-ci": "^3.0.1", "is-installed-globally": "~0.4.0", "lazy-ass": "^1.6.0", "listr2": "^3.8.3", @@ -788,6 +789,7 @@ "semver": "^7.5.3", "supports-color": "^8.1.1", "tmp": "~0.2.3", + "tree-kill": "1.2.2", "untildify": "^4.0.0", "yauzl": "^2.10.0" }, @@ -1203,9 +1205,9 @@ } }, "node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", "dev": true, "license": "MIT", "dependencies": { @@ -1583,19 +1585,6 @@ "node": ">=8" } }, - "node_modules/is-ci": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-3.0.1.tgz", - "integrity": "sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ci-info": "^3.2.0" - }, - "bin": { - "is-ci": "bin.js" - } - }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2457,6 +2446,25 @@ "dev": true, "license": "MIT" }, + "node_modules/nanoid": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.8.tgz", + "integrity": "sha512-TcJPw+9RV9dibz1hHUzlLVy8N4X9TnwirAjrU08Juo6BNKggzVfP2ZJ/3ZUSq15Xl5i85i+Z89XBO90pB2PghQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -2733,13 +2741,6 @@ "dev": true, "license": "MIT" }, - "node_modules/psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "dev": true, - "license": "MIT" - }, "node_modules/pump": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.2.tgz", @@ -2751,16 +2752,6 @@ "once": "^1.3.1" } }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/qs": { "version": "6.13.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", @@ -2777,13 +2768,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/querystringify": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", - "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", - "dev": true, - "license": "MIT" - }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -2843,13 +2827,6 @@ "dev": true, "license": "ISC" }, - "node_modules/requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true, - "license": "MIT" - }, "node_modules/restore-cursor": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", @@ -3150,6 +3127,26 @@ "dev": true, "license": "MIT" }, + "node_modules/tldts": { + "version": "6.1.59", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.59.tgz", + "integrity": "sha512-472ilPxsRuqBBpn+KuRBHJvZhk6tTo4yTVsmODrLBNLwRYJPkDfMEHivgNwp5iEl+cbrZzzRtLKRxZs7+QKkRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.59" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.59", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.59.tgz", + "integrity": "sha512-EiYgNf275AQyVORl8HQYYe7rTVnmLb4hkWK7wAk/12Ksy5EiHpmUmTICa4GojookBPC8qkLMBKKwCmzNA47ZPQ==", + "dev": true, + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.3.tgz", @@ -3175,29 +3172,26 @@ } }, "node_modules/tough-cookie": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", - "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.0.0.tgz", + "integrity": "sha512-FRKsF7cz96xIIeMZ82ehjC3xW2E+O2+v11udrDYewUbszngYhsGa8z6YUMMzO9QJZzzyd0nGGXnML/TReX6W8Q==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" + "tldts": "^6.1.32" }, "engines": { - "node": ">=6" + "node": ">=16" } }, - "node_modules/tough-cookie/node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", "dev": true, "license": "MIT", - "engines": { - "node": ">= 4.0.0" + "bin": { + "tree-kill": "cli.js" } }, "node_modules/tslib": { @@ -3267,17 +3261,6 @@ "node": ">=8" } }, - "node_modules/url-parse": { - "version": "1.5.10", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", - "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "querystringify": "^2.1.1", - "requires-port": "^1.0.0" - } - }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", diff --git a/cypress-tests-v2/package.json b/cypress-tests-v2/package.json index e06c1a63be2..20403f9e777 100644 --- a/cypress-tests-v2/package.json +++ b/cypress-tests-v2/package.json @@ -15,9 +15,10 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.14.2", + "cypress": "^13.15.2", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", - "prettier": "^3.3.2" + "prettier": "^3.3.2", + "nanoid": "^5.0.8" } }
ci
update cypress v2 framework to accommodate hyperswitch v2 changes (#6493)
3312e787f9873d10114e6a4ca78a0c3714ab2b1c
2024-07-11 14:49:09
Pa1NarK
chore: fix file name ignored by git in cypress (#5281)
false
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/utils.js b/cypress-tests/cypress/e2e/PaymentUtils/Utils.js similarity index 100% rename from cypress-tests/cypress/e2e/PaymentUtils/utils.js rename to cypress-tests/cypress/e2e/PaymentUtils/Utils.js diff --git a/cypress-tests/cypress/e2e/PayoutUtils/utils.js b/cypress-tests/cypress/e2e/PayoutUtils/Utils.js similarity index 100% rename from cypress-tests/cypress/e2e/PayoutUtils/utils.js rename to cypress-tests/cypress/e2e/PayoutUtils/Utils.js diff --git a/cypress-tests/cypress/e2e/RoutingUtils/utils.js b/cypress-tests/cypress/e2e/RoutingUtils/Utils.js similarity index 100% rename from cypress-tests/cypress/e2e/RoutingUtils/utils.js rename to cypress-tests/cypress/e2e/RoutingUtils/Utils.js diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js index 0ef4243f067..3a903be1e7a 100644 --- a/cypress-tests/cypress/support/commands.js +++ b/cypress-tests/cypress/support/commands.js @@ -25,7 +25,7 @@ // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) // commands.js or your custom support file -import { defaultErrorHandler, getValueByKey } from "../e2e/PaymentUtils/utils"; +import { defaultErrorHandler, getValueByKey } from "../e2e/PaymentUtils/Utils"; import * as RequestBodyUtils from "../utils/RequestBodyUtils"; import { handleRedirection } from "./redirectionHandler";
chore
fix file name ignored by git in cypress (#5281)
349036bff3ba17559b23f7e624035697997f12a6
2022-12-22 12:19:26
Sanchith Hegde
feat(middleware): return request ID in response header (#214)
false
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index da737e4ed12..5d1d8cde95a 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -35,6 +35,7 @@ pub(crate) mod macros; pub mod routes; pub mod scheduler; +mod middleware; pub mod services; pub mod types; pub mod utils; @@ -95,6 +96,7 @@ pub fn mk_app( let mut server_app = actix_web::App::new() .app_data(json_cfg) + .wrap(middleware::RequestId) .wrap(router_env::tracing_actix_web::TracingLogger::default()) .wrap(ErrorHandlers::new().handler( StatusCode::NOT_FOUND, diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs new file mode 100644 index 00000000000..4401a32c99d --- /dev/null +++ b/crates/router/src/middleware.rs @@ -0,0 +1,61 @@ +/// Middleware to include request ID in response header. +pub(crate) struct RequestId; + +impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestId +where + S: actix_web::dev::Service< + actix_web::dev::ServiceRequest, + Response = actix_web::dev::ServiceResponse<B>, + Error = actix_web::Error, + >, + S::Future: 'static, + B: 'static, +{ + type Response = actix_web::dev::ServiceResponse<B>; + type Error = actix_web::Error; + type Transform = RequestIdMiddleware<S>; + type InitError = (); + type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; + + fn new_transform(&self, service: S) -> Self::Future { + std::future::ready(Ok(RequestIdMiddleware { service })) + } +} + +pub(crate) struct RequestIdMiddleware<S> { + service: S, +} + +impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestIdMiddleware<S> +where + S: actix_web::dev::Service< + actix_web::dev::ServiceRequest, + Response = actix_web::dev::ServiceResponse<B>, + Error = actix_web::Error, + >, + S::Future: 'static, + B: 'static, +{ + type Response = actix_web::dev::ServiceResponse<B>; + type Error = actix_web::Error; + type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; + + actix_web::dev::forward_ready!(service); + + fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { + let mut req = req; + let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>(); + let response_fut = self.service.call(req); + + Box::pin(async move { + let request_id = request_id_fut.await?; + let mut response = response_fut.await?; + response.headers_mut().append( + http::header::HeaderName::from_static("x-request-id"), + http::HeaderValue::from_str(&request_id.as_hyphenated().to_string())?, + ); + + Ok(response) + }) + } +}
feat
return request ID in response header (#214)
1904ffad889bbf2c77e959fda60c0c55fd57f596
2024-07-05 13:37:46
awasthi21
feat(connector): [BRAINTREE] Implement Card Mandates (#5204)
false
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 01a18f6c008..71b3d1f8ecd 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -135,8 +135,8 @@ connectors_with_delayed_session_response = "trustpay,payme" # List of connec bank_debit.ach.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit bank_debit.becs.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit bank_debit.sepa.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" # Mandate supported payment method type and connector for card -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" # Mandate supported payment method type and connector for card +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" # Mandate supported payment method type and connector for card +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" # Mandate supported payment method type and connector for card pay_later.klarna.connector_list = "adyen" # Mandate supported payment method type and connector for pay_later wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica" # Mandate supported payment method type and connector for wallets wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica" # Mandate supported payment method type and connector for wallets diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 39f477a3639..03c328294fc 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -135,8 +135,8 @@ enabled = false bank_debit.ach.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit bank_debit.becs.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit bank_debit.sepa.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" # Mandate supported payment method type and connector for card -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" # Mandate supported payment method type and connector for card +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" # Mandate supported payment method type and connector for card +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" # Mandate supported payment method type and connector for card pay_later.klarna.connector_list = "adyen" # Mandate supported payment method type and connector for pay_later wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica" # Mandate supported payment method type and connector for wallets wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica" # Mandate supported payment method type and connector for wallets diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index c9180e1a612..a08cefdb41a 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -135,8 +135,8 @@ enabled = true bank_debit.ach.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit bank_debit.becs.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit bank_debit.sepa.connector_list = "gocardless" # Mandate supported payment method type and connector for bank_debit -card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" # Mandate supported payment method type and connector for card -card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" # Mandate supported payment method type and connector for card +card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" # Mandate supported payment method type and connector for card +card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" # Mandate supported payment method type and connector for card pay_later.klarna.connector_list = "adyen" # Mandate supported payment method type and connector for pay_later wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica" # Mandate supported payment method type and connector for wallets wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica" # Mandate supported payment method type and connector for wallets diff --git a/config/development.toml b/config/development.toml index 12ff04b012c..556b2e24afe 100644 --- a/config/development.toml +++ b/config/development.toml @@ -410,8 +410,6 @@ google_pay = { currency = "USD" } [pm_filters.braintree] paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" } -credit = { not_available_flows = { capture_method = "manual" } } -debit = { not_available_flows = { capture_method = "manual" } } [pm_filters.helcim] credit = { currency = "USD" } @@ -536,8 +534,8 @@ pay_later.klarna = { connector_list = "adyen" } wallet.google_pay = { connector_list = "stripe,adyen,cybersource,bankofamerica" } wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica" } wallet.paypal = { connector_list = "adyen" } -card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" } -card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica" } +card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" } +card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree" } bank_debit.ach = { connector_list = "gocardless" } bank_debit.becs = { connector_list = "gocardless" } bank_debit.sepa = { connector_list = "gocardless" } diff --git a/crates/hyperswitch_domain_models/src/mandates.rs b/crates/hyperswitch_domain_models/src/mandates.rs index d9080d6dc91..5bf9f0c9510 100644 --- a/crates/hyperswitch_domain_models/src/mandates.rs +++ b/crates/hyperswitch_domain_models/src/mandates.rs @@ -43,26 +43,29 @@ pub struct MandateData { pub mandate_type: Option<MandateDataType>, } -#[derive(Default, Eq, PartialEq, Debug, Clone)] +#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize)] pub struct CustomerAcceptance { /// Type of acceptance provided by the pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided + #[serde(with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } -#[derive(Default, Debug, PartialEq, Eq, Clone)] +#[derive(Default, Debug, PartialEq, Eq, Clone, serde::Deserialize)] +#[serde(rename_all = "lowercase")] pub enum AcceptanceType { Online, #[default] Offline, } -#[derive(Default, Eq, PartialEq, Debug, Clone)] +#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created + #[serde(skip_deserializing)] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 6d7e42eb1ae..efd01397f69 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -347,7 +347,7 @@ pub struct CompleteAuthorizeData { pub connector_meta: Option<serde_json::Value>, pub complete_authorize_url: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, - + pub customer_acceptance: Option<mandates::CustomerAcceptance>, // New amount for amount frame work pub minor_amount: MinorUnit, } diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 750e2e6e3cc..8964c06aaf8 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -15,6 +15,7 @@ use self::transformers as braintree; use super::utils::{self as connector_utils, PaymentsAuthorizeRequestData}; use crate::{ configs::settings, + connector::utils::PaymentMethodDataType, consts, core::{ errors::{self, CustomResult}, @@ -175,6 +176,15 @@ impl ConnectorValidation for Braintree { ), } } + + fn validate_mandate_payment( + &self, + pm_type: Option<types::storage::enums::PaymentMethodType>, + pm_data: domain::payments::PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]); + connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) + } } impl api::Payment for Braintree {} diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index bb8f2f5e38f..d52328a7783 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -5,11 +5,14 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ - connector::utils::{self, PaymentsAuthorizeRequestData, RefundsRequestData, RouterData}, + connector::utils::{ + self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + RefundsRequestData, RouterData, + }, consts, core::errors, services, - types::{self, api, domain, storage::enums}, + types::{self, api, domain, storage::enums, MandateReference}, unimplemented_payment_method, }; @@ -20,6 +23,8 @@ pub const AUTHORIZE_CREDIT_CARD_MUTATION: &str = "mutation authorizeCreditCard($ pub const CAPTURE_TRANSACTION_MUTATION: &str = "mutation captureTransaction($input: CaptureTransactionInput!) { captureTransaction(input: $input) { clientMutationId transaction { id legacyId amount { value currencyCode } status } } }"; pub const VOID_TRANSACTION_MUTATION: &str = "mutation voidTransaction($input: ReverseTransactionInput!) { reverseTransaction(input: $input) { clientMutationId reversal { ... on Transaction { id legacyId amount { value currencyCode } status } } } }"; pub const REFUND_TRANSACTION_MUTATION: &str = "mutation refundTransaction($input: RefundTransactionInput!) { refundTransaction(input: $input) {clientMutationId refund { id legacyId amount { value currencyCode } status } } }"; +pub const AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION: &str="mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }"; +pub const CHARGE_AND_VAULT_TRANSACTION_MUTATION: &str ="mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }"; #[derive(Debug, Serialize)] pub struct BraintreeRouterData<T> { @@ -58,11 +63,18 @@ pub struct CardPaymentRequest { variables: VariablePaymentInput, } +#[derive(Debug, Serialize)] +pub struct MandatePaymentRequest { + query: String, + variables: VariablePaymentInput, +} + #[derive(Debug, Serialize)] #[serde(untagged)] pub enum BraintreePaymentsRequest { Card(CardPaymentRequest), CardThreeDs(BraintreeClientTokenRequest), + Mandate(MandatePaymentRequest), } #[derive(Debug, Deserialize)] @@ -84,9 +96,67 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] -pub struct TransactionBody { +pub struct RegularTransactionBody { + amount: String, + merchant_account_id: Secret<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct VaultTransactionBody { amount: String, merchant_account_id: Secret<String>, + vault_payment_method_after_transacting: TransactionTiming, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum TransactionBody { + Regular(RegularTransactionBody), + Vault(VaultTransactionBody), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TransactionTiming { + when: String, +} + +impl + TryFrom<( + &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>, + String, + BraintreeMeta, + )> for MandatePaymentRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, connector_mandate_id, metadata): ( + &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>, + String, + BraintreeMeta, + ), + ) -> Result<Self, Self::Error> { + let (query, transaction_body) = ( + match item.router_data.request.is_auto_capture()? { + true => CHARGE_CREDIT_CARD_MUTATION.to_string(), + false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(), + }, + TransactionBody::Regular(RegularTransactionBody { + amount: item.amount.to_owned(), + merchant_account_id: metadata.merchant_account_id, + }), + ); + Ok(Self { + query, + variables: VariablePaymentInput { + input: PaymentInput { + payment_method_id: connector_mandate_id.into(), + transaction: transaction_body, + }, + }, + }) + } } impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> @@ -105,7 +175,6 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> item.router_data.request.currency, Some(metadata.merchant_config_currency), )?; - match item.router_data.request.payment_method_data.clone() { domain::PaymentMethodData::Card(_) => { if item.router_data.is_three_ds() { @@ -116,6 +185,18 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> Ok(Self::Card(CardPaymentRequest::try_from((item, metadata))?)) } } + domain::PaymentMethodData::MandatePayment => { + let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "connector_mandate_id", + }, + )?; + Ok(Self::Mandate(MandatePaymentRequest::try_from(( + item, + connector_mandate_id, + metadata, + ))?)) + } domain::PaymentMethodData::CardRedirect(_) | domain::PaymentMethodData::Wallet(_) | domain::PaymentMethodData::PayLater(_) @@ -123,7 +204,6 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> | domain::PaymentMethodData::BankDebit(_) | domain::PaymentMethodData::BankTransfer(_) | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment | domain::PaymentMethodData::Reward | domain::PaymentMethodData::RealTimePayment(_) | domain::PaymentMethodData::Upi(_) @@ -194,9 +274,16 @@ pub enum BraintreeCompleteAuthResponse { } #[derive(Debug, Clone, Deserialize, Serialize)] +struct PaymentMethodInfo { + id: Secret<String>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct TransactionAuthChargeResponseBody { id: String, status: BraintreePaymentStatus, + payment_method: Option<PaymentMethodInfo>, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -242,7 +329,12 @@ impl<F> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), redirection_data: None, - mandate_reference: None, + mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { + MandateReference { + connector_mandate_id: Some(pm.id.clone().expose()), + payment_method_id: None, + } + }), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -426,7 +518,12 @@ impl<F> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), redirection_data: None, - mandate_reference: None, + mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { + MandateReference { + connector_mandate_id: Some(pm.id.clone().expose()), + payment_method_id: None, + } + }), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -490,7 +587,12 @@ impl<F> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), redirection_data: None, - mandate_reference: None, + mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { + MandateReference { + connector_mandate_id: Some(pm.id.clone().expose()), + payment_method_id: None, + } + }), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -536,7 +638,12 @@ impl<F> response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id), redirection_data: None, - mandate_reference: None, + mandate_reference: transaction_data.payment_method.as_ref().map(|pm| { + MandateReference { + connector_mandate_id: Some(pm.id.clone().expose()), + payment_method_id: None, + } + }), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -1327,9 +1434,31 @@ impl BraintreeMeta, ), ) -> Result<Self, Self::Error> { - let query = match item.router_data.request.is_auto_capture()? { - true => CHARGE_CREDIT_CARD_MUTATION.to_string(), - false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(), + let (query, transaction_body) = if item.router_data.request.is_mandate_payment() { + ( + match item.router_data.request.is_auto_capture()? { + true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(), + false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(), + }, + TransactionBody::Vault(VaultTransactionBody { + amount: item.amount.to_owned(), + merchant_account_id: metadata.merchant_account_id, + vault_payment_method_after_transacting: TransactionTiming { + when: "ALWAYS".to_string(), + }, + }), + ) + } else { + ( + match item.router_data.request.is_auto_capture()? { + true => CHARGE_CREDIT_CARD_MUTATION.to_string(), + false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(), + }, + TransactionBody::Regular(RegularTransactionBody { + amount: item.amount.to_owned(), + merchant_account_id: metadata.merchant_account_id, + }), + ) }; Ok(Self { query, @@ -1341,10 +1470,7 @@ impl unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"), )?, }, - transaction: TransactionBody { - amount: item.amount.to_owned(), - merchant_account_id: metadata.merchant_account_id, - }, + transaction: transaction_body, }, }, }) @@ -1367,11 +1493,10 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> item.router_data.request.currency, Some(metadata.merchant_config_currency), )?; - let payload_data = - utils::PaymentsCompleteAuthorizeRequestData::get_redirect_response_payload( - &item.router_data.request, - )? - .expose(); + let payload_data = PaymentsCompleteAuthorizeRequestData::get_redirect_response_payload( + &item.router_data.request, + )? + .expose(); let redirection_response: BraintreeRedirectionResponse = serde_json::from_value( payload_data, ) @@ -1384,21 +1509,39 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>> .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "three_ds_data", })?; - let query = match utils::PaymentsCompleteAuthorizeRequestData::is_auto_capture( - &item.router_data.request, - )? { - true => CHARGE_CREDIT_CARD_MUTATION.to_string(), - false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(), + + let (query, transaction_body) = if item.router_data.request.is_mandate_payment() { + ( + match item.router_data.request.is_auto_capture()? { + true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(), + false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(), + }, + TransactionBody::Vault(VaultTransactionBody { + amount: item.amount.to_owned(), + merchant_account_id: metadata.merchant_account_id, + vault_payment_method_after_transacting: TransactionTiming { + when: "ALWAYS".to_string(), + }, + }), + ) + } else { + ( + match item.router_data.request.is_auto_capture()? { + true => CHARGE_CREDIT_CARD_MUTATION.to_string(), + false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(), + }, + TransactionBody::Regular(RegularTransactionBody { + amount: item.amount.to_owned(), + merchant_account_id: metadata.merchant_account_id, + }), + ) }; Ok(Self { query, variables: VariablePaymentInput { input: PaymentInput { payment_method_id: three_ds_data.nonce, - transaction: TransactionBody { - amount: item.amount.to_owned(), - merchant_account_id: metadata.merchant_account_id, - }, + transaction: transaction_body, }, }, }) diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 5f2b18f0c0a..67ba0219642 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1017,6 +1017,7 @@ pub trait PaymentsCompleteAuthorizeRequestData { fn get_email(&self) -> Result<Email, Error>; fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; + fn is_mandate_payment(&self) -> bool; } impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { @@ -1046,6 +1047,17 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } + fn is_mandate_payment(&self) -> bool { + ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) + && self.setup_future_usage.map_or(false, |setup_future_usage| { + setup_future_usage == storage_enums::FutureUsage::OffSession + })) + || self + .mandate_id + .as_ref() + .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) + .is_some() + } } pub trait PaymentsSyncRequestData { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index b63852e1354..e2c8d2769c8 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -610,6 +610,21 @@ pub async fn get_token_pm_type_mandate_details( ) } } else { + let payment_method_info = payment_method_id + .async_map(|payment_method_id| async move { + state + .store + .find_payment_method( + &payment_method_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::PaymentMethodNotFound, + ) + }) + .await + .transpose()?; ( request.payment_token.to_owned(), request.payment_method, @@ -617,7 +632,7 @@ pub async fn get_token_pm_type_mandate_details( None, None, None, - None, + payment_method_info, ) } } diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 7188a8216de..060acf51549 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -11,7 +11,10 @@ use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, - payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, + payments::{ + self, helpers, operations, CustomerAcceptance, CustomerDetails, PaymentAddress, + PaymentData, + }, utils as core_utils, }, db::StorageInterface, @@ -86,7 +89,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co })?; let recurring_details = request.recurring_details.clone(); - let customer_acceptance = request.customer_acceptance.clone().map(From::from); payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( @@ -127,6 +129,19 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co &payment_intent.customer_id, ) .await?; + let customer_acceptance: Option<CustomerAcceptance> = request + .customer_acceptance + .clone() + .map(From::from) + .or(payment_method_info + .clone() + .map(|pm| { + pm.customer_acceptance + .parse_value::<CustomerAcceptance>("CustomerAcceptance") + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize to CustomerAcceptance")?); let token = token.or_else(|| payment_attempt.payment_token.clone()); if let Some(payment_method) = payment_method { diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index aaf8e3b3a07..62167d592e9 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1790,6 +1790,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz connector_meta: payment_data.payment_attempt.connector_metadata, complete_authorize_url, metadata: payment_data.payment_intent.metadata, + customer_acceptance: payment_data.customer_acceptance, }) } } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index ce0ac53fdec..0bc855678ae 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -281,8 +281,8 @@ pay_later.klarna = {connector_list = "adyen"} wallet.google_pay = {connector_list = "stripe,adyen,bankofamerica"} wallet.apple_pay = {connector_list = "stripe,adyen,bankofamerica"} wallet.paypal = {connector_list = "adyen"} -card.credit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica"} -card.debit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica"} +card.credit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree"} +card.debit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree"} bank_debit.ach = { connector_list = "gocardless"} bank_debit.becs = { connector_list = "gocardless"} bank_debit.sepa = { connector_list = "gocardless"}
feat
[BRAINTREE] Implement Card Mandates (#5204)
b5ffff30dfea1ac52944734c633b7e1ec76d7831
2023-01-18 15:56:09
chikke srujan
fix(router): metadata field update in merchant_account and merchant_connector_account (#359)
false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 5ddf55acf66..4df6e88c8a5 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -3,11 +3,10 @@ use masking::{Secret, StrongSecret}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; -pub use self::CreateMerchantAccount as MerchantAccountResponse; use super::payments::AddressDetails; use crate::{enums as api_enums, payment_methods}; -#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] +#[derive(Clone, Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CreateMerchantAccount { /// The identifier for the Merchant Account @@ -68,6 +67,69 @@ pub struct CreateMerchantAccount { pub locker_id: Option<String>, } +#[derive(Clone, Debug, ToSchema, Serialize)] +pub struct MerchantAccountResponse { + /// The identifier for the Merchant Account + #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] + pub merchant_id: String, + + /// Name of the Merchant Account + #[schema(example = "NewAge Retailer")] + pub merchant_name: Option<String>, + + /// API key that will be used for server side API access + #[schema(value_type = Option<String>, example = "Ah2354543543523")] + pub api_key: Option<StrongSecret<String>>, + + /// The URL to redirect after the completion of the operation + #[schema(max_length = 255, example = "https://www.example.com/success")] + pub return_url: Option<String>, + + /// A boolean value to indicate if payment response hash needs to be enabled + #[schema(default = false, example = true)] + pub enable_payment_response_hash: bool, + + /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")] + pub payment_response_hash_key: Option<String>, + + /// A boolean value to indicate if redirect to merchant with http post needs to be enabled + #[schema(default = false, example = true)] + pub redirect_to_merchant_with_http_post: bool, + + /// Merchant related details + #[schema(value_type = Option<MerchantDetails>)] + pub merchant_details: Option<serde_json::Value>, + + /// Webhook related details + #[schema(value_type = Option<WebhookDetails>)] + pub webhook_details: Option<serde_json::Value>, + + /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' + #[schema(value_type = Option<RoutingAlgorithm>, max_length = 255, example = "custom")] + pub routing_algorithm: Option<serde_json::Value>, + + /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. + #[schema(default = false, example = false)] + pub sub_merchants_enabled: Option<bool>, + + /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant + #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")] + pub parent_merchant_id: Option<String>, + + /// API key that will be used for server side API access + #[schema(example = "AH3423bkjbkjdsfbkj")] + pub publishable_key: Option<String>, + + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] + pub metadata: Option<serde_json::Value>, + + /// An identifier for the vault used to store payment method information. + #[schema(example = "locker_abc123")] + pub locker_id: Option<String>, +} + #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantDetails { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index c94667f5fb3..b0fd4384f08 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1,3 +1,4 @@ +use common_utils::ext_traits::ValueExt; use error_stack::{report, FutureExt, ResultExt}; use uuid::Uuid; @@ -12,7 +13,7 @@ use crate::{ storage::{self, MerchantAccount}, transformers::{ForeignInto, ForeignTryInto}, }, - utils::{self, OptionExt, ValueExt}, + utils::{self, OptionExt}, }; #[inline] @@ -29,21 +30,23 @@ pub async fn create_merchant_account( db: &dyn StorageInterface, req: api::CreateMerchantAccount, ) -> RouterResponse<api::MerchantAccountResponse> { - let publishable_key = &format!("pk_{}", create_merchant_api_key()); - let api_key = create_merchant_api_key(); - let mut response = req.clone(); - response.api_key = Some(api_key.to_owned().into()); - response.publishable_key = Some(publishable_key.to_owned()); - let merchant_details = + let publishable_key = Some(format!("pk_{}", create_merchant_api_key())); + + let api_key = Some(create_merchant_api_key().into()); + + let merchant_details = Some( utils::Encode::<api::MerchantDetails>::encode_to_value(&req.merchant_details) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "merchant_details", - })?; - let webhook_details = + })?, + ); + + let webhook_details = Some( utils::Encode::<api::WebhookDetails>::encode_to_value(&req.webhook_details) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "webhook details", - })?; + })?, + ); if let Some(ref routing_algorithm) = req.routing_algorithm { let _: api::RoutingAlgorithm = routing_algorithm @@ -58,31 +61,36 @@ pub async fn create_merchant_account( let merchant_account = storage::MerchantAccountNew { merchant_id: req.merchant_id, merchant_name: req.merchant_name, - api_key: Some(api_key.to_string().into()), - merchant_details: Some(merchant_details), + api_key, + merchant_details, return_url: req.return_url, - webhook_details: Some(webhook_details), + webhook_details, routing_algorithm: req.routing_algorithm, sub_merchants_enabled: req.sub_merchants_enabled, parent_merchant_id: get_parent_merchant( db, - &req.sub_merchants_enabled, + req.sub_merchants_enabled, req.parent_merchant_id, ) .await?, enable_payment_response_hash: req.enable_payment_response_hash, payment_response_hash_key: req.payment_response_hash_key, redirect_to_merchant_with_http_post: req.redirect_to_merchant_with_http_post, - publishable_key: Some(publishable_key.to_owned()), + publishable_key, locker_id: req.locker_id, + metadata: req.metadata, }; - db.insert_merchant(merchant_account) + let merchant_account = db + .insert_merchant(merchant_account) .await .map_err(|error| { error.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount) })?; - Ok(service_api::ApplicationResponse::Json(response)) + + Ok(service_api::ApplicationResponse::Json( + merchant_account.foreign_into(), + )) } pub async fn get_merchant_account( @@ -95,34 +103,10 @@ pub async fn get_merchant_account( .map_err(|error| { error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) })?; - let merchant_details = merchant_account - .merchant_details - .parse_value("MerchantDetails") - .change_context(errors::ApiErrorResponse::InternalServerError)?; - let webhook_details = merchant_account - .webhook_details - .parse_value("WebhookDetails") - .change_context(errors::ApiErrorResponse::InternalServerError)?; - let response = api::MerchantAccountResponse { - merchant_id: req.merchant_id, - merchant_name: merchant_account.merchant_name, - api_key: merchant_account.api_key, - merchant_details, - return_url: merchant_account.return_url, - webhook_details, - routing_algorithm: merchant_account.routing_algorithm, - sub_merchants_enabled: merchant_account.sub_merchants_enabled, - parent_merchant_id: merchant_account.parent_merchant_id, - enable_payment_response_hash: Some(merchant_account.enable_payment_response_hash), - payment_response_hash_key: merchant_account.payment_response_hash_key, - redirect_to_merchant_with_http_post: Some( - merchant_account.redirect_to_merchant_with_http_post, - ), - metadata: None, - publishable_key: merchant_account.publishable_key, - locker_id: merchant_account.locker_id, - }; - Ok(service_api::ApplicationResponse::Json(response)) + + Ok(service_api::ApplicationResponse::Json( + merchant_account.foreign_into(), + )) } pub async fn merchant_account_update( @@ -159,76 +143,56 @@ pub async fn merchant_account_update( .attach_printable("Invalid routing algorithm given")?; } - let mut response = req.clone(); + let updated_merchant_account = storage::MerchantAccountUpdate::Update { + merchant_name: req.merchant_name, - let encode_error_handler = - |value: &str| format!("Unable to encode to serde_json::Value, {value}"); + merchant_details: req + .merchant_details + .as_ref() + .map(utils::Encode::<api::MerchantDetails>::encode_to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError)?, + + return_url: req.return_url, + + webhook_details: req + .webhook_details + .as_ref() + .map(utils::Encode::<api::WebhookDetails>::encode_to_value) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError)?, + + routing_algorithm: req.routing_algorithm, + sub_merchants_enabled: req.sub_merchants_enabled, - let updated_merchant_account = storage::MerchantAccountUpdate::Update { - merchant_id: merchant_id.to_string(), - merchant_name: req - .merchant_name - .or_else(|| merchant_account.merchant_name.to_owned()), - api_key: merchant_account.api_key.clone(), - merchant_details: if req.merchant_details.is_some() { - Some( - utils::Encode::<api::MerchantDetails>::encode_to_value(&req.merchant_details) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| encode_error_handler("MerchantDetails"))?, - ) - } else { - merchant_account.merchant_details.to_owned() - }, - return_url: req - .return_url - .or_else(|| merchant_account.return_url.to_owned()), - webhook_details: if req.webhook_details.is_some() { - Some( - utils::Encode::<api::WebhookDetails>::encode_to_value(&req.webhook_details) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| encode_error_handler("WebhookDetails"))?, - ) - } else { - merchant_account.webhook_details.to_owned() - }, - routing_algorithm: req - .routing_algorithm - .or_else(|| merchant_account.routing_algorithm.clone()), - sub_merchants_enabled: req - .sub_merchants_enabled - .or(merchant_account.sub_merchants_enabled), parent_merchant_id: get_parent_merchant( db, - &req.sub_merchants_enabled + req.sub_merchants_enabled .or(merchant_account.sub_merchants_enabled), req.parent_merchant_id .or_else(|| merchant_account.parent_merchant_id.clone()), ) .await?, - enable_payment_response_hash: req - .enable_payment_response_hash - .or(Some(merchant_account.enable_payment_response_hash)), - payment_response_hash_key: req - .payment_response_hash_key - .or_else(|| merchant_account.payment_response_hash_key.to_owned()), - redirect_to_merchant_with_http_post: req - .redirect_to_merchant_with_http_post - .or(Some(merchant_account.redirect_to_merchant_with_http_post)), - publishable_key: req - .publishable_key - .or_else(|| merchant_account.publishable_key.clone()), - locker_id: req - .locker_id - .or_else(|| merchant_account.locker_id.to_owned()), + enable_payment_response_hash: req.enable_payment_response_hash, + payment_response_hash_key: req.payment_response_hash_key, + redirect_to_merchant_with_http_post: req.redirect_to_merchant_with_http_post, + locker_id: req.locker_id, + metadata: req.metadata, + merchant_id: merchant_account.merchant_id.to_owned(), + api_key: None, + publishable_key: None, }; - response.merchant_id = merchant_id.to_string(); - response.api_key = merchant_account.api_key.to_owned(); - db.update_merchant(merchant_account, updated_merchant_account) + let response = db + .update_merchant(merchant_account, updated_merchant_account) .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| format!("Failed while updating merchant: {}", merchant_id))?; - Ok(service_api::ApplicationResponse::Json(response)) + .map_err(|error| { + error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) + })?; + + Ok(service_api::ApplicationResponse::Json( + response.foreign_into(), + )) } pub async fn merchant_account_delete( @@ -250,7 +214,7 @@ pub async fn merchant_account_delete( async fn get_parent_merchant( db: &dyn StorageInterface, - sub_merchants_enabled: &Option<bool>, + sub_merchants_enabled: Option<bool>, parent_merchant: Option<String>, ) -> RouterResult<Option<String>> { Ok(match sub_merchants_enabled { @@ -445,12 +409,11 @@ pub async fn update_payment_connector( connector_type: Some(req.connector_type.foreign_into()), connector_name: Some(req.connector_name), merchant_connector_id: Some(merchant_connector_id), - connector_account_details: req - .connector_account_details - .or_else(|| Some(Secret::new(mca.connector_account_details.to_owned()))), + connector_account_details: req.connector_account_details, payment_methods_enabled, test_mode: mca.test_mode, disabled: req.disabled.or(mca.disabled), + metadata: req.metadata, }; let updated_mca = db @@ -471,7 +434,7 @@ pub async fn update_payment_connector( test_mode: updated_mca.test_mode, disabled: updated_mca.disabled, payment_methods_enabled: req.payment_methods_enabled, - metadata: req.metadata, + metadata: updated_mca.metadata, }; Ok(service_api::ApplicationResponse::Json(response)) } diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 86abdb6e072..56ba7416b5b 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -143,6 +143,7 @@ impl MerchantAccountInterface for MockDb { publishable_key: merchant_account.publishable_key, storage_scheme: enums::MerchantStorageScheme::PostgresOnly, locker_id: merchant_account.locker_id, + metadata: merchant_account.metadata, }; accounts.push(account.clone()); Ok(account) diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 0099f87e557..ee33c8d3171 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -1,10 +1,36 @@ pub use api_models::admin::{ - CreateMerchantAccount, DeleteMcaResponse, DeleteResponse, MerchantConnectorId, MerchantDetails, - MerchantId, PaymentConnectorCreate, PaymentMethods, RoutingAlgorithm, WebhookDetails, + CreateMerchantAccount, DeleteMcaResponse, DeleteResponse, MerchantAccountResponse, + MerchantConnectorId, MerchantDetails, MerchantId, PaymentConnectorCreate, PaymentMethods, + RoutingAlgorithm, WebhookDetails, }; +use crate::types::{storage, transformers::Foreign}; + +impl From<Foreign<storage::MerchantAccount>> for Foreign<MerchantAccountResponse> { + fn from(value: Foreign<storage::MerchantAccount>) -> Self { + let item = value.0; + MerchantAccountResponse { + merchant_id: item.merchant_id, + merchant_name: item.merchant_name, + api_key: item.api_key, + return_url: item.return_url, + enable_payment_response_hash: item.enable_payment_response_hash, + payment_response_hash_key: item.payment_response_hash_key, + redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, + merchant_details: item.merchant_details, + webhook_details: item.webhook_details, + routing_algorithm: item.routing_algorithm, + sub_merchants_enabled: item.sub_merchants_enabled, + parent_merchant_id: item.parent_merchant_id, + publishable_key: item.publishable_key, + metadata: item.metadata, + locker_id: item.locker_id, + } + .into() + } +} + //use serde::{Serialize, Deserialize}; -pub use self::CreateMerchantAccount as MerchantAccountResponse; //use crate::newtype; diff --git a/crates/storage_models/src/merchant_account.rs b/crates/storage_models/src/merchant_account.rs index b77b681df1c..6937c70c0b5 100644 --- a/crates/storage_models/src/merchant_account.rs +++ b/crates/storage_models/src/merchant_account.rs @@ -21,6 +21,7 @@ pub struct MerchantAccount { pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, + pub metadata: Option<serde_json::Value>, pub routing_algorithm: Option<serde_json::Value>, } @@ -40,6 +41,7 @@ pub struct MerchantAccountNew { pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, pub locker_id: Option<String>, + pub metadata: Option<serde_json::Value>, pub routing_algorithm: Option<serde_json::Value>, } @@ -59,6 +61,7 @@ pub enum MerchantAccountUpdate { redirect_to_merchant_with_http_post: Option<bool>, publishable_key: Option<String>, locker_id: Option<String>, + metadata: Option<serde_json::Value>, routing_algorithm: Option<serde_json::Value>, }, } @@ -79,6 +82,7 @@ pub struct MerchantAccountUpdateInternal { redirect_to_merchant_with_http_post: Option<bool>, publishable_key: Option<String>, locker_id: Option<String>, + metadata: Option<serde_json::Value>, routing_algorithm: Option<serde_json::Value>, } @@ -100,6 +104,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { redirect_to_merchant_with_http_post, publishable_key, locker_id, + metadata, } => Self { merchant_id: Some(merchant_id), merchant_name, @@ -115,6 +120,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { redirect_to_merchant_with_http_post, publishable_key, locker_id, + metadata, }, } } diff --git a/crates/storage_models/src/merchant_connector_account.rs b/crates/storage_models/src/merchant_connector_account.rs index e63d820ac08..ffaaeb4f060 100644 --- a/crates/storage_models/src/merchant_connector_account.rs +++ b/crates/storage_models/src/merchant_connector_account.rs @@ -44,6 +44,7 @@ pub enum MerchantConnectorAccountUpdate { disabled: Option<bool>, merchant_connector_id: Option<i32>, payment_methods_enabled: Option<Vec<serde_json::Value>>, + metadata: Option<serde_json::Value>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] @@ -57,6 +58,7 @@ pub struct MerchantConnectorAccountUpdateInternal { disabled: Option<bool>, merchant_connector_id: Option<i32>, payment_methods_enabled: Option<Vec<serde_json::Value>>, + metadata: Option<serde_json::Value>, } impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal { @@ -71,6 +73,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte disabled, merchant_connector_id, payment_methods_enabled, + metadata, } => Self { merchant_id, connector_type, @@ -80,6 +83,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte disabled, merchant_connector_id, payment_methods_enabled, + metadata, }, } } diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs index bfaddd5e20d..bdd8bbea09c 100644 --- a/crates/storage_models/src/schema.rs +++ b/crates/storage_models/src/schema.rs @@ -158,6 +158,7 @@ diesel::table! { publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, locker_id -> Nullable<Varchar>, + metadata -> Nullable<Jsonb>, routing_algorithm -> Nullable<Json>, } } diff --git a/migrations/2023-01-11-134448_add_metadata_to_merchant_account/down.sql b/migrations/2023-01-11-134448_add_metadata_to_merchant_account/down.sql new file mode 100644 index 00000000000..347e0680130 --- /dev/null +++ b/migrations/2023-01-11-134448_add_metadata_to_merchant_account/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account DROP COLUMN metadata; \ No newline at end of file diff --git a/migrations/2023-01-11-134448_add_metadata_to_merchant_account/up.sql b/migrations/2023-01-11-134448_add_metadata_to_merchant_account/up.sql new file mode 100644 index 00000000000..e3d32889ba6 --- /dev/null +++ b/migrations/2023-01-11-134448_add_metadata_to_merchant_account/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE merchant_account ADD COLUMN metadata JSONB DEFAULT NULL; \ No newline at end of file
fix
metadata field update in merchant_account and merchant_connector_account (#359)